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, localised if name empty */
172 define('ROLENAME_ORIGINAL', 0);
173 /** rolename displays - the name as defined by a role alias at the course level, falls back to ROLENAME_ORIGINAL if alias not present */
174 define('ROLENAME_ALIAS', 1);
175 /** rolename displays - Both, like this: Role alias (Original) */
176 define('ROLENAME_BOTH', 2);
177 /** rolename displays - the name as defined in the role definition and the shortname in brackets */
178 define('ROLENAME_ORIGINALANDSHORT', 3);
179 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
180 define('ROLENAME_ALIAS_RAW', 4);
181 /** rolename displays - the name is simply short role name */
182 define('ROLENAME_SHORT', 5);
184 if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
185 /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
186 define('CONTEXT_CACHE_MAX_SIZE', 2500);
190 * Although this looks like a global variable, it isn't really.
192 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
193 * It is used to cache various bits of data between function calls for performance reasons.
194 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
195 * as methods of a class, instead of functions.
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() {
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);
272 // Overrides for the role IN ANY CONTEXTS down to COURSE - not below -.
275 $sql = "SELECT ctx.path,
276 rc.capability, rc.permission
278 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
279 LEFT JOIN {context} cctx
280 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
281 WHERE rc.roleid = ? AND cctx.id IS NULL";
282 $params = array($roleid);
285 // Note: the commented out query is 100% accurate but slow, so let's cheat instead by hardcoding the blocks mess directly.
287 $sql = "SELECT COALESCE(ctx.path, bctx.path) AS path, rc.capability, rc.permission
288 FROM {role_capabilities} rc
289 LEFT JOIN {context} ctx ON (ctx.id = rc.contextid AND ctx.contextlevel <= ".CONTEXT_COURSE
.")
290 LEFT JOIN ({context} bctx
291 JOIN {block_instances} bi ON (bi.id = bctx.instanceid)
292 JOIN {context} pctx ON (pctx.id = bi.parentcontextid AND pctx.contextlevel < ".CONTEXT_COURSE
.")
293 ) ON (bctx.id = rc.contextid AND bctx.contextlevel = ".CONTEXT_BLOCK
.")
294 WHERE rc.roleid = :roleid AND (ctx.id IS NOT NULL OR bctx.id IS NOT NULL)";
295 $params = array('roleid'=>$roleid);
297 // we need extra caching in CLI scripts and cron
298 $rs = $DB->get_recordset_sql($sql, $params);
299 foreach ($rs as $rd) {
300 $k = "{$rd->path}:{$roleid}";
301 $accessdata['rdef'][$k][$rd->capability
] = (int)$rd->permission
;
305 // share the role definitions
306 foreach ($accessdata['rdef'] as $k=>$unused) {
307 if (!isset($ACCESSLIB_PRIVATE->rolepermissions
[$k])) {
308 $ACCESSLIB_PRIVATE->rolepermissions
[$k] = $accessdata['rdef'][$k];
310 $accessdata['rdef_count']++
;
311 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions
[$k];
318 * Get the default guest role, this is used for guest account,
319 * search engine spiders, etc.
321 * @return stdClass role record
323 function get_guest_role() {
326 if (empty($CFG->guestroleid
)) {
327 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
328 $guestrole = array_shift($roles); // Pick the first one
329 set_config('guestroleid', $guestrole->id
);
332 debugging('Can not find any guest role!');
336 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid
))) {
339 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
340 set_config('guestroleid', '');
341 return get_guest_role();
347 * Check whether a user has a particular capability in a given context.
350 * $context = context_module::instance($cm->id);
351 * has_capability('mod/forum:replypost', $context)
353 * By default checks the capabilities of the current user, but you can pass a
354 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
356 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
357 * or capabilities with XSS, config or data loss risks.
361 * @param string $capability the name of the capability to check. For example mod/forum:view
362 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
363 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
364 * @param boolean $doanything If false, ignores effect of admin role assignment
365 * @return boolean true if the user has this capability. Otherwise false.
367 function has_capability($capability, context
$context, $user = null, $doanything = true) {
368 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
370 if (during_initial_install()) {
371 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
372 // we are in an installer - roles can not work yet
379 if (strpos($capability, 'moodle/legacy:') === 0) {
380 throw new coding_exception('Legacy capabilities can not be used any more!');
383 if (!is_bool($doanything)) {
384 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
387 // capability must exist
388 if (!$capinfo = get_capability_info($capability)) {
389 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
393 if (!isset($USER->id
)) {
394 // should never happen
396 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER
);
399 // make sure there is a real user specified
400 if ($user === null) {
403 $userid = is_object($user) ?
$user->id
: $user;
406 // make sure forcelogin cuts off not-logged-in users if enabled
407 if (!empty($CFG->forcelogin
) and $userid == 0) {
411 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
412 if (($capinfo->captype
=== 'write') or ($capinfo->riskbitmask
& (RISK_XSS | RISK_CONFIG | RISK_DATALOSS
))) {
413 if (isguestuser($userid) or $userid == 0) {
418 // somehow make sure the user is not deleted and actually exists
420 if ($userid == $USER->id
and isset($USER->deleted
)) {
421 // this prevents one query per page, it is a bit of cheating,
422 // but hopefully session is terminated properly once user is deleted
423 if ($USER->deleted
) {
427 if (!context_user
::instance($userid, IGNORE_MISSING
)) {
428 // no user context == invalid userid
434 // context path/depth must be valid
435 if (empty($context->path
) or $context->depth
== 0) {
436 // this should not happen often, each upgrade tries to rebuild the context paths
437 debugging('Context id '.$context->id
.' does not have valid path, please use build_context_path()');
438 if (is_siteadmin($userid)) {
445 // Find out if user is admin - it is not possible to override the doanything in any way
446 // and it is not possible to switch to admin role either.
448 if (is_siteadmin($userid)) {
449 if ($userid != $USER->id
) {
452 // make sure switchrole is not used in this context
453 if (empty($USER->access
['rsw'])) {
456 $parts = explode('/', trim($context->path
, '/'));
459 foreach ($parts as $part) {
460 $path .= '/' . $part;
461 if (!empty($USER->access
['rsw'][$path])) {
469 //ok, admin switched role in this context, let's use normal access control rules
473 // Careful check for staleness...
474 $context->reload_if_dirty();
476 if ($USER->id
== $userid) {
477 if (!isset($USER->access
)) {
478 load_all_capabilities();
480 $access =& $USER->access
;
483 // make sure user accessdata is really loaded
484 get_user_accessdata($userid, true);
485 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser
[$userid];
489 // Load accessdata for below-the-course context if necessary,
490 // all contexts at and above all courses are already loaded
491 if ($context->contextlevel
!= CONTEXT_COURSE
and $coursecontext = $context->get_course_context(false)) {
492 load_course_context($userid, $coursecontext, $access);
495 return has_capability_in_accessdata($capability, $context, $access);
499 * Check if the user has any one of several capabilities from a list.
501 * This is just a utility method that calls has_capability in a loop. Try to put
502 * the capabilities that most users are likely to have first in the list for best
506 * @see has_capability()
508 * @param array $capabilities an array of capability names.
509 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
510 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
511 * @param boolean $doanything If false, ignore effect of admin role assignment
512 * @return boolean true if the user has any of these capabilities. Otherwise false.
514 function has_any_capability(array $capabilities, context
$context, $user = null, $doanything = true) {
515 foreach ($capabilities as $capability) {
516 if (has_capability($capability, $context, $user, $doanything)) {
524 * Check if the user has all the capabilities in a list.
526 * This is just a utility method that calls has_capability in a loop. Try to put
527 * the capabilities that fewest users are likely to have first in the list for best
531 * @see has_capability()
533 * @param array $capabilities an array of capability names.
534 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
535 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
536 * @param boolean $doanything If false, ignore effect of admin role assignment
537 * @return boolean true if the user has all of these capabilities. Otherwise false.
539 function has_all_capabilities(array $capabilities, context
$context, $user = null, $doanything = true) {
540 foreach ($capabilities as $capability) {
541 if (!has_capability($capability, $context, $user, $doanything)) {
549 * Is course creator going to have capability in a new course?
551 * This is intended to be used in enrolment plugins before or during course creation,
552 * do not use after the course is fully created.
556 * @param string $capability the name of the capability to check.
557 * @param context $context course or category context where is course going to be created
558 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
559 * @return boolean true if the user will have this capability.
561 * @throws coding_exception if different type of context submitted
563 function guess_if_creator_will_have_course_capability($capability, context
$context, $user = null) {
566 if ($context->contextlevel
!= CONTEXT_COURSE
and $context->contextlevel
!= CONTEXT_COURSECAT
) {
567 throw new coding_exception('Only course or course category context expected');
570 if (has_capability($capability, $context, $user)) {
571 // User already has the capability, it could be only removed if CAP_PROHIBIT
572 // was involved here, but we ignore that.
576 if (!has_capability('moodle/course:create', $context, $user)) {
580 if (!enrol_is_enabled('manual')) {
584 if (empty($CFG->creatornewroleid
)) {
588 if ($context->contextlevel
== CONTEXT_COURSE
) {
589 if (is_viewing($context, $user, 'moodle/role:assign') or is_enrolled($context, $user, 'moodle/role:assign')) {
593 if (has_capability('moodle/course:view', $context, $user) and has_capability('moodle/role:assign', $context, $user)) {
598 // Most likely they will be enrolled after the course creation is finished,
599 // does the new role have the required capability?
600 list($neededroles, $forbiddenroles) = get_roles_with_cap_in_context($context, $capability);
601 return isset($neededroles[$CFG->creatornewroleid
]);
605 * Check if the user is an admin at the site level.
607 * Please note that use of proper capabilities is always encouraged,
608 * this function is supposed to be used from core or for temporary hacks.
612 * @param int|stdClass $user_or_id user id or user object
613 * @return bool true if user is one of the administrators, false otherwise
615 function is_siteadmin($user_or_id = null) {
618 if ($user_or_id === null) {
622 if (empty($user_or_id)) {
625 if (!empty($user_or_id->id
)) {
626 $userid = $user_or_id->id
;
628 $userid = $user_or_id;
631 // Because this script is called many times (150+ for course page) with
632 // the same parameters, it is worth doing minor optimisations. This static
633 // cache stores the value for a single userid, saving about 2ms from course
634 // page load time without using significant memory. As the static cache
635 // also includes the value it depends on, this cannot break unit tests.
636 static $knownid, $knownresult, $knownsiteadmins;
637 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins
) {
641 $knownsiteadmins = $CFG->siteadmins
;
643 $siteadmins = explode(',', $CFG->siteadmins
);
644 $knownresult = in_array($userid, $siteadmins);
649 * Returns true if user has at least one role assign
650 * of 'coursecontact' role (is potentially listed in some course descriptions).
655 function has_coursecontact_role($userid) {
658 if (empty($CFG->coursecontact
)) {
662 FROM {role_assignments}
663 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
664 return $DB->record_exists_sql($sql, array('userid'=>$userid));
668 * Does the user have a capability to do something?
670 * Walk the accessdata array and return true/false.
671 * Deals with prohibits, role switching, aggregating
674 * The main feature of here is being FAST and with no
679 * Switch Role merges with default role
680 * ------------------------------------
681 * If you are a teacher in course X, you have at least
682 * teacher-in-X + defaultloggedinuser-sitewide. So in the
683 * course you'll have techer+defaultloggedinuser.
684 * We try to mimic that in switchrole.
686 * Permission evaluation
687 * ---------------------
688 * Originally there was an extremely complicated way
689 * to determine the user access that dealt with
690 * "locality" or role assignments and role overrides.
691 * Now we simply evaluate access for each role separately
692 * and then verify if user has at least one role with allow
693 * and at the same time no role with prohibit.
696 * @param string $capability
697 * @param context $context
698 * @param array $accessdata
701 function has_capability_in_accessdata($capability, context
$context, array &$accessdata) {
704 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
705 $path = $context->path
;
706 $paths = array($path);
707 while($path = rtrim($path, '0123456789')) {
708 $path = rtrim($path, '/');
716 $switchedrole = false;
718 // Find out if role switched
719 if (!empty($accessdata['rsw'])) {
720 // From the bottom up...
721 foreach ($paths as $path) {
722 if (isset($accessdata['rsw'][$path])) {
723 // Found a switchrole assignment - check for that role _plus_ the default user role
724 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid
=>null);
725 $switchedrole = true;
731 if (!$switchedrole) {
732 // get all users roles in this context and above
733 foreach ($paths as $path) {
734 if (isset($accessdata['ra'][$path])) {
735 foreach ($accessdata['ra'][$path] as $roleid) {
736 $roles[$roleid] = null;
742 // Now find out what access is given to each role, going bottom-->up direction
744 foreach ($roles as $roleid => $ignored) {
745 foreach ($paths as $path) {
746 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
747 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
748 if ($perm === CAP_PROHIBIT
) {
749 // any CAP_PROHIBIT found means no permission for the user
752 if (is_null($roles[$roleid])) {
753 $roles[$roleid] = $perm;
757 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
758 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW
);
765 * A convenience function that tests has_capability, and displays an error if
766 * the user does not have that capability.
768 * NOTE before Moodle 2.0, this function attempted to make an appropriate
769 * require_login call before checking the capability. This is no longer the case.
770 * You must call require_login (or one of its variants) if you want to check the
771 * user is logged in, before you call this function.
773 * @see has_capability()
775 * @param string $capability the name of the capability to check. For example mod/forum:view
776 * @param context $context the context to check the capability in. You normally get this with context_xxxx::instance().
777 * @param int $userid A user id. By default (null) checks the permissions of the current user.
778 * @param bool $doanything If false, ignore effect of admin role assignment
779 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
780 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
781 * @return void terminates with an error if the user does not have the given capability.
783 function require_capability($capability, context
$context, $userid = null, $doanything = true,
784 $errormessage = 'nopermissions', $stringfile = '') {
785 if (!has_capability($capability, $context, $userid, $doanything)) {
786 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
791 * Return a nested array showing role assignments
792 * all relevant role capabilities for the user at
793 * site/course_category/course levels
795 * We do _not_ delve deeper than courses because the number of
796 * overrides at the module/block levels can be HUGE.
798 * [ra] => [/path][roleid]=roleid
799 * [rdef] => [/path:roleid][capability]=permission
802 * @param int $userid - the id of the user
803 * @return array access info array
805 function get_user_access_sitewide($userid) {
806 global $CFG, $DB, $ACCESSLIB_PRIVATE;
808 /* Get in a few cheap DB queries...
810 * - relevant role caps
811 * - above and within this user's RAs
812 * - below this user's RAs - limited to course level
815 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
816 $raparents = array();
817 $accessdata = get_empty_accessdata();
819 // start with the default role
820 if (!empty($CFG->defaultuserroleid
)) {
821 $syscontext = context_system
::instance();
822 $accessdata['ra'][$syscontext->path
][(int)$CFG->defaultuserroleid
] = (int)$CFG->defaultuserroleid
;
823 $raparents[$CFG->defaultuserroleid
][$syscontext->id
] = $syscontext->id
;
826 // load the "default frontpage role"
827 if (!empty($CFG->defaultfrontpageroleid
)) {
828 $frontpagecontext = context_course
::instance(get_site()->id
);
829 if ($frontpagecontext->path
) {
830 $accessdata['ra'][$frontpagecontext->path
][(int)$CFG->defaultfrontpageroleid
] = (int)$CFG->defaultfrontpageroleid
;
831 $raparents[$CFG->defaultfrontpageroleid
][$frontpagecontext->id
] = $frontpagecontext->id
;
835 // preload every assigned role at and above course context
836 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
837 FROM {role_assignments} ra
839 ON ctx.id = ra.contextid
840 LEFT JOIN {block_instances} bi
841 ON (ctx.contextlevel = ".CONTEXT_BLOCK
." AND bi.id = ctx.instanceid)
842 LEFT JOIN {context} bpctx
843 ON (bpctx.id = bi.parentcontextid)
844 WHERE ra.userid = :userid
845 AND (ctx.contextlevel <= ".CONTEXT_COURSE
." OR bpctx.contextlevel < ".CONTEXT_COURSE
.")";
846 $params = array('userid'=>$userid);
847 $rs = $DB->get_recordset_sql($sql, $params);
848 foreach ($rs as $ra) {
849 // RAs leafs are arrays to support multi-role assignments...
850 $accessdata['ra'][$ra->path
][(int)$ra->roleid
] = (int)$ra->roleid
;
851 $raparents[$ra->roleid
][$ra->contextid
] = $ra->contextid
;
855 if (empty($raparents)) {
859 // now get overrides of interesting roles in all interesting child contexts
860 // hopefully we will not run out of SQL limits here,
861 // users would have to have very many roles at/above course context...
866 foreach ($raparents as $roleid=>$ras) {
868 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED
, 'c'.$cp.'_');
869 $params = array_merge($params, $cids);
870 $params['r'.$cp] = $roleid;
871 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
872 FROM {role_capabilities} rc
874 ON (ctx.id = rc.contextid)
877 AND (ctx.id = pctx.id
878 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
879 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
880 LEFT JOIN {block_instances} bi
881 ON (ctx.contextlevel = ".CONTEXT_BLOCK
." AND bi.id = ctx.instanceid)
882 LEFT JOIN {context} bpctx
883 ON (bpctx.id = bi.parentcontextid)
884 WHERE rc.roleid = :r{$cp}
885 AND (ctx.contextlevel <= ".CONTEXT_COURSE
." OR bpctx.contextlevel < ".CONTEXT_COURSE
.")
889 // fixed capability order is necessary for rdef dedupe
890 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
892 foreach ($rs as $rd) {
893 $k = $rd->path
.':'.$rd->roleid
;
894 $accessdata['rdef'][$k][$rd->capability
] = (int)$rd->permission
;
898 // share the role definitions
899 foreach ($accessdata['rdef'] as $k=>$unused) {
900 if (!isset($ACCESSLIB_PRIVATE->rolepermissions
[$k])) {
901 $ACCESSLIB_PRIVATE->rolepermissions
[$k] = $accessdata['rdef'][$k];
903 $accessdata['rdef_count']++
;
904 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions
[$k];
911 * Add to the access ctrl array the data needed by a user for a given course.
913 * This function injects all course related access info into the accessdata array.
916 * @param int $userid the id of the user
917 * @param context_course $coursecontext course context
918 * @param array $accessdata accessdata array (modified)
919 * @return void modifies $accessdata parameter
921 function load_course_context($userid, context_course
$coursecontext, &$accessdata) {
922 global $DB, $CFG, $ACCESSLIB_PRIVATE;
924 if (empty($coursecontext->path
)) {
925 // weird, this should not happen
929 if (isset($accessdata['loaded'][$coursecontext->instanceid
])) {
930 // already loaded, great!
936 if (empty($userid)) {
937 if (!empty($CFG->notloggedinroleid
)) {
938 $roles[$CFG->notloggedinroleid
] = $CFG->notloggedinroleid
;
941 } else if (isguestuser($userid)) {
942 if ($guestrole = get_guest_role()) {
943 $roles[$guestrole->id
] = $guestrole->id
;
947 // Interesting role assignments at, above and below the course context
948 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'pc_');
949 $params['userid'] = $userid;
950 $params['children'] = $coursecontext->path
."/%";
951 $sql = "SELECT ra.*, ctx.path
952 FROM {role_assignments} ra
953 JOIN {context} ctx ON ra.contextid = ctx.id
954 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
955 $rs = $DB->get_recordset_sql($sql, $params);
957 // add missing role definitions
958 foreach ($rs as $ra) {
959 $accessdata['ra'][$ra->path
][(int)$ra->roleid
] = (int)$ra->roleid
;
960 $roles[$ra->roleid
] = $ra->roleid
;
964 // add the "default frontpage role" when on the frontpage
965 if (!empty($CFG->defaultfrontpageroleid
)) {
966 $frontpagecontext = context_course
::instance(get_site()->id
);
967 if ($frontpagecontext->id
== $coursecontext->id
) {
968 $roles[$CFG->defaultfrontpageroleid
] = $CFG->defaultfrontpageroleid
;
972 // do not forget the default role
973 if (!empty($CFG->defaultuserroleid
)) {
974 $roles[$CFG->defaultuserroleid
] = $CFG->defaultuserroleid
;
979 // weird, default roles must be missing...
980 $accessdata['loaded'][$coursecontext->instanceid
] = 1;
984 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
985 $params = array('c'=>$coursecontext->id
);
986 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'pc_');
987 $params = array_merge($params, $rparams);
988 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED
, 'r_');
989 $params = array_merge($params, $rparams);
991 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
992 FROM {role_capabilities} rc
994 ON (ctx.id = rc.contextid)
997 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
998 WHERE rc.roleid $roleids
999 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
1000 $rs = $DB->get_recordset_sql($sql, $params);
1002 $newrdefs = array();
1003 foreach ($rs as $rd) {
1004 $k = $rd->path
.':'.$rd->roleid
;
1005 if (isset($accessdata['rdef'][$k])) {
1008 $newrdefs[$k][$rd->capability
] = (int)$rd->permission
;
1012 // share new role definitions
1013 foreach ($newrdefs as $k=>$unused) {
1014 if (!isset($ACCESSLIB_PRIVATE->rolepermissions
[$k])) {
1015 $ACCESSLIB_PRIVATE->rolepermissions
[$k] = $newrdefs[$k];
1017 $accessdata['rdef_count']++
;
1018 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions
[$k];
1021 $accessdata['loaded'][$coursecontext->instanceid
] = 1;
1023 // we want to deduplicate the USER->access from time to time, this looks like a good place,
1024 // because we have to do it before the end of session
1025 dedupe_user_access();
1029 * Add to the access ctrl array the data needed by a role for a given context.
1031 * The data is added in the rdef key.
1032 * This role-centric function is useful for role_switching
1033 * and temporary course roles.
1036 * @param int $roleid the id of the user
1037 * @param context $context needs path!
1038 * @param array $accessdata accessdata array (is modified)
1041 function load_role_access_by_context($roleid, context
$context, &$accessdata) {
1042 global $DB, $ACCESSLIB_PRIVATE;
1044 /* Get the relevant rolecaps into rdef
1045 * - relevant role caps
1046 * - at ctx and above
1050 if (empty($context->path
)) {
1051 // weird, this should not happen
1055 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'pc_');
1056 $params['roleid'] = $roleid;
1057 $params['childpath'] = $context->path
.'/%';
1059 $sql = "SELECT ctx.path, rc.capability, rc.permission
1060 FROM {role_capabilities} rc
1061 JOIN {context} ctx ON (rc.contextid = ctx.id)
1062 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
1063 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
1064 $rs = $DB->get_recordset_sql($sql, $params);
1066 $newrdefs = array();
1067 foreach ($rs as $rd) {
1068 $k = $rd->path
.':'.$roleid;
1069 if (isset($accessdata['rdef'][$k])) {
1072 $newrdefs[$k][$rd->capability
] = (int)$rd->permission
;
1076 // share new role definitions
1077 foreach ($newrdefs as $k=>$unused) {
1078 if (!isset($ACCESSLIB_PRIVATE->rolepermissions
[$k])) {
1079 $ACCESSLIB_PRIVATE->rolepermissions
[$k] = $newrdefs[$k];
1081 $accessdata['rdef_count']++
;
1082 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions
[$k];
1087 * Returns empty accessdata structure.
1090 * @return array empt accessdata
1092 function get_empty_accessdata() {
1093 $accessdata = array(); // named list
1094 $accessdata['ra'] = array();
1095 $accessdata['rdef'] = array();
1096 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1097 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1098 $accessdata['loaded'] = array(); // loaded course contexts
1099 $accessdata['time'] = time();
1100 $accessdata['rsw'] = array();
1106 * Get accessdata for a given user.
1109 * @param int $userid
1110 * @param bool $preloadonly true means do not return access array
1111 * @return array accessdata
1113 function get_user_accessdata($userid, $preloadonly=false) {
1114 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1116 if (!empty($USER->acces
['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions
)) {
1117 // share rdef from USER session with rolepermissions cache in order to conserve memory
1118 foreach($USER->acces
['rdef'] as $k=>$v) {
1119 $ACCESSLIB_PRIVATE->rolepermissions
[$k] =& $USER->acces
['rdef'][$k];
1121 $ACCESSLIB_PRIVATE->accessdatabyuser
[$USER->id
] = $USER->acces
;
1124 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser
[$userid])) {
1125 if (empty($userid)) {
1126 if (!empty($CFG->notloggedinroleid
)) {
1127 $accessdata = get_role_access($CFG->notloggedinroleid
);
1130 return get_empty_accessdata();
1133 } else if (isguestuser($userid)) {
1134 if ($guestrole = get_guest_role()) {
1135 $accessdata = get_role_access($guestrole->id
);
1138 return get_empty_accessdata();
1142 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1145 $ACCESSLIB_PRIVATE->accessdatabyuser
[$userid] = $accessdata;
1151 return $ACCESSLIB_PRIVATE->accessdatabyuser
[$userid];
1156 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1157 * this function looks for contexts with the same overrides and shares them.
1162 function dedupe_user_access() {
1166 // no session in CLI --> no compression necessary
1170 if (empty($USER->access
['rdef_count'])) {
1171 // weird, this should not happen
1175 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1176 if ($USER->access
['rdef_count'] - $USER->access
['rdef_lcc'] > 10) {
1177 // do not compress after each change, wait till there is more stuff to be done
1182 foreach ($USER->access
['rdef'] as $k=>$def) {
1183 $hash = sha1(serialize($def));
1184 if (isset($hashmap[$hash])) {
1185 $USER->access
['rdef'][$k] =& $hashmap[$hash];
1187 $hashmap[$hash] =& $USER->access
['rdef'][$k];
1191 $USER->access
['rdef_lcc'] = $USER->access
['rdef_count'];
1195 * A convenience function to completely load all the capabilities
1196 * for the current user. It is called from has_capability() and functions change permissions.
1198 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1199 * @see check_enrolment_plugins()
1204 function load_all_capabilities() {
1207 // roles not installed yet - we are in the middle of installation
1208 if (during_initial_install()) {
1212 if (!isset($USER->id
)) {
1213 // this should not happen
1217 unset($USER->access
);
1218 $USER->access
= get_user_accessdata($USER->id
);
1220 // deduplicate the overrides to minimize session size
1221 dedupe_user_access();
1223 // Clear to force a refresh
1224 unset($USER->mycourses
);
1226 // init/reset internal enrol caches - active course enrolments and temp access
1227 $USER->enrol
= array('enrolled'=>array(), 'tempguest'=>array());
1231 * A convenience function to completely reload all the capabilities
1232 * for the current user when roles have been updated in a relevant
1233 * context -- but PRESERVING switchroles and loginas.
1234 * This function resets all accesslib and context caches.
1236 * That is - completely transparent to the user.
1238 * Note: reloads $USER->access completely.
1243 function reload_all_capabilities() {
1244 global $USER, $DB, $ACCESSLIB_PRIVATE;
1248 if (!empty($USER->access
['rsw'])) {
1249 $sw = $USER->access
['rsw'];
1252 accesslib_clear_all_caches(true);
1253 unset($USER->access
);
1254 $ACCESSLIB_PRIVATE->dirtycontexts
= array(); // prevent dirty flags refetching on this page
1256 load_all_capabilities();
1258 foreach ($sw as $path => $roleid) {
1259 if ($record = $DB->get_record('context', array('path'=>$path))) {
1260 $context = context
::instance_by_id($record->id
);
1261 role_switch($roleid, $context);
1267 * Adds a temp role to current USER->access array.
1269 * Useful for the "temporary guest" access we grant to logged-in users.
1270 * This is useful for enrol plugins only.
1273 * @param context_course $coursecontext
1274 * @param int $roleid
1277 function load_temp_course_role(context_course
$coursecontext, $roleid) {
1278 global $USER, $SITE;
1280 if (empty($roleid)) {
1281 debugging('invalid role specified in load_temp_course_role()');
1285 if ($coursecontext->instanceid
== $SITE->id
) {
1286 debugging('Can not use temp roles on the frontpage');
1290 if (!isset($USER->access
)) {
1291 load_all_capabilities();
1294 $coursecontext->reload_if_dirty();
1296 if (isset($USER->access
['ra'][$coursecontext->path
][$roleid])) {
1300 // load course stuff first
1301 load_course_context($USER->id
, $coursecontext, $USER->access
);
1303 $USER->access
['ra'][$coursecontext->path
][(int)$roleid] = (int)$roleid;
1305 load_role_access_by_context($roleid, $coursecontext, $USER->access
);
1309 * Removes any extra guest roles from current USER->access array.
1310 * This is useful for enrol plugins only.
1313 * @param context_course $coursecontext
1316 function remove_temp_course_roles(context_course
$coursecontext) {
1317 global $DB, $USER, $SITE;
1319 if ($coursecontext->instanceid
== $SITE->id
) {
1320 debugging('Can not use temp roles on the frontpage');
1324 if (empty($USER->access
['ra'][$coursecontext->path
])) {
1325 //no roles here, weird
1329 $sql = "SELECT DISTINCT ra.roleid AS id
1330 FROM {role_assignments} ra
1331 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1332 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id
, 'userid'=>$USER->id
));
1334 $USER->access
['ra'][$coursecontext->path
] = array();
1335 foreach($ras as $r) {
1336 $USER->access
['ra'][$coursecontext->path
][(int)$r->id
] = (int)$r->id
;
1341 * Returns array of all role archetypes.
1345 function get_role_archetypes() {
1347 'manager' => 'manager',
1348 'coursecreator' => 'coursecreator',
1349 'editingteacher' => 'editingteacher',
1350 'teacher' => 'teacher',
1351 'student' => 'student',
1354 'frontpage' => 'frontpage'
1359 * Assign the defaults found in this capability definition to roles that have
1360 * the corresponding legacy capabilities assigned to them.
1362 * @param string $capability
1363 * @param array $legacyperms an array in the format (example):
1364 * 'guest' => CAP_PREVENT,
1365 * 'student' => CAP_ALLOW,
1366 * 'teacher' => CAP_ALLOW,
1367 * 'editingteacher' => CAP_ALLOW,
1368 * 'coursecreator' => CAP_ALLOW,
1369 * 'manager' => CAP_ALLOW
1370 * @return boolean success or failure.
1372 function assign_legacy_capabilities($capability, $legacyperms) {
1374 $archetypes = get_role_archetypes();
1376 foreach ($legacyperms as $type => $perm) {
1378 $systemcontext = context_system
::instance();
1379 if ($type === 'admin') {
1380 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1384 if (!array_key_exists($type, $archetypes)) {
1385 print_error('invalidlegacy', '', '', $type);
1388 if ($roles = get_archetype_roles($type)) {
1389 foreach ($roles as $role) {
1390 // Assign a site level capability.
1391 if (!assign_capability($capability, $perm, $role->id
, $systemcontext->id
)) {
1401 * Verify capability risks.
1403 * @param stdClass $capability a capability - a row from the capabilities table.
1404 * @return boolean whether this capability is safe - that is, whether people with the
1405 * safeoverrides capability should be allowed to change it.
1407 function is_safe_capability($capability) {
1408 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL
) & $capability->riskbitmask
);
1412 * Get the local override (if any) for a given capability in a role in a context
1414 * @param int $roleid
1415 * @param int $contextid
1416 * @param string $capability
1417 * @return stdClass local capability override
1419 function get_local_override($roleid, $contextid, $capability) {
1421 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1425 * Returns context instance plus related course and cm instances
1427 * @param int $contextid
1428 * @return array of ($context, $course, $cm)
1430 function get_context_info_array($contextid) {
1433 $context = context
::instance_by_id($contextid, MUST_EXIST
);
1437 if ($context->contextlevel
== CONTEXT_COURSE
) {
1438 $course = $DB->get_record('course', array('id'=>$context->instanceid
), '*', MUST_EXIST
);
1440 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1441 $cm = get_coursemodule_from_id('', $context->instanceid
, 0, false, MUST_EXIST
);
1442 $course = $DB->get_record('course', array('id'=>$cm->course
), '*', MUST_EXIST
);
1444 } else if ($context->contextlevel
== CONTEXT_BLOCK
) {
1445 $parent = $context->get_parent_context();
1447 if ($parent->contextlevel
== CONTEXT_COURSE
) {
1448 $course = $DB->get_record('course', array('id'=>$parent->instanceid
), '*', MUST_EXIST
);
1449 } else if ($parent->contextlevel
== CONTEXT_MODULE
) {
1450 $cm = get_coursemodule_from_id('', $parent->instanceid
, 0, false, MUST_EXIST
);
1451 $course = $DB->get_record('course', array('id'=>$cm->course
), '*', MUST_EXIST
);
1455 return array($context, $course, $cm);
1459 * Function that creates a role
1461 * @param string $name role name
1462 * @param string $shortname role short name
1463 * @param string $description role description
1464 * @param string $archetype
1465 * @return int id or dml_exception
1467 function create_role($name, $shortname, $description, $archetype = '') {
1470 if (strpos($archetype, 'moodle/legacy:') !== false) {
1471 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1474 // verify role archetype actually exists
1475 $archetypes = get_role_archetypes();
1476 if (empty($archetypes[$archetype])) {
1480 // Insert the role record.
1481 $role = new stdClass();
1482 $role->name
= $name;
1483 $role->shortname
= $shortname;
1484 $role->description
= $description;
1485 $role->archetype
= $archetype;
1487 //find free sortorder number
1488 $role->sortorder
= $DB->get_field('role', 'MAX(sortorder) + 1', array());
1489 if (empty($role->sortorder
)) {
1490 $role->sortorder
= 1;
1492 $id = $DB->insert_record('role', $role);
1498 * Function that deletes a role and cleanups up after it
1500 * @param int $roleid id of role to delete
1501 * @return bool always true
1503 function delete_role($roleid) {
1506 // first unssign all users
1507 role_unassign_all(array('roleid'=>$roleid));
1509 // cleanup all references to this role, ignore errors
1510 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1511 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1512 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1513 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1514 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1515 $DB->delete_records('role_names', array('roleid'=>$roleid));
1516 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1518 // Get role record before it's deleted.
1519 $role = $DB->get_record('role', array('id'=>$roleid));
1521 // Finally delete the role itself.
1522 $DB->delete_records('role', array('id'=>$roleid));
1525 $event = \core\event\role_deleted
::create(
1527 'context' => context_system
::instance(),
1528 'objectid' => $roleid,
1531 'name' => $role->name
,
1532 'shortname' => $role->shortname
,
1533 'description' => $role->description
,
1534 'archetype' => $role->archetype
1538 $event->add_record_snapshot('role', $role);
1545 * Function to write context specific overrides, or default capabilities.
1547 * NOTE: use $context->mark_dirty() after this
1549 * @param string $capability string name
1550 * @param int $permission CAP_ constants
1551 * @param int $roleid role id
1552 * @param int|context $contextid context id
1553 * @param bool $overwrite
1554 * @return bool always true or exception
1556 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1559 if ($contextid instanceof context
) {
1560 $context = $contextid;
1562 $context = context
::instance_by_id($contextid);
1565 if (empty($permission) ||
$permission == CAP_INHERIT
) { // if permission is not set
1566 unassign_capability($capability, $roleid, $context->id
);
1570 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id
, 'roleid'=>$roleid, 'capability'=>$capability));
1572 if ($existing and !$overwrite) { // We want to keep whatever is there already
1576 $cap = new stdClass();
1577 $cap->contextid
= $context->id
;
1578 $cap->roleid
= $roleid;
1579 $cap->capability
= $capability;
1580 $cap->permission
= $permission;
1581 $cap->timemodified
= time();
1582 $cap->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
1585 $cap->id
= $existing->id
;
1586 $DB->update_record('role_capabilities', $cap);
1588 if ($DB->record_exists('context', array('id'=>$context->id
))) {
1589 $DB->insert_record('role_capabilities', $cap);
1596 * Unassign a capability from a role.
1598 * NOTE: use $context->mark_dirty() after this
1600 * @param string $capability the name of the capability
1601 * @param int $roleid the role id
1602 * @param int|context $contextid null means all contexts
1603 * @return boolean true or exception
1605 function unassign_capability($capability, $roleid, $contextid = null) {
1608 if (!empty($contextid)) {
1609 if ($contextid instanceof context
) {
1610 $context = $contextid;
1612 $context = context
::instance_by_id($contextid);
1614 // delete from context rel, if this is the last override in this context
1615 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id
));
1617 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1623 * Get the roles that have a given capability assigned to it
1625 * This function does not resolve the actual permission of the capability.
1626 * It just checks for permissions and overrides.
1627 * Use get_roles_with_cap_in_context() if resolution is required.
1629 * @param string $capability capability name (string)
1630 * @param string $permission optional, the permission defined for this capability
1631 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1632 * @param stdClass $context null means any
1633 * @return array of role records
1635 function get_roles_with_capability($capability, $permission = null, $context = null) {
1639 $contexts = $context->get_parent_context_ids(true);
1640 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED
, 'ctx');
1641 $contextsql = "AND rc.contextid $insql";
1648 $permissionsql = " AND rc.permission = :permission";
1649 $params['permission'] = $permission;
1651 $permissionsql = '';
1656 WHERE r.id IN (SELECT rc.roleid
1657 FROM {role_capabilities} rc
1658 WHERE rc.capability = :capname
1661 $params['capname'] = $capability;
1664 return $DB->get_records_sql($sql, $params);
1668 * This function makes a role-assignment (a role for a user in a particular context)
1670 * @param int $roleid the role of the id
1671 * @param int $userid userid
1672 * @param int|context $contextid id of the context
1673 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1674 * @param int $itemid id of enrolment/auth plugin
1675 * @param string $timemodified defaults to current time
1676 * @return int new/existing id of the assignment
1678 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1681 // first of all detect if somebody is using old style parameters
1682 if ($contextid === 0 or is_numeric($component)) {
1683 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1686 // now validate all parameters
1687 if (empty($roleid)) {
1688 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1691 if (empty($userid)) {
1692 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1696 if (strpos($component, '_') === false) {
1697 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1701 if ($component !== '' and strpos($component, '_') === false) {
1702 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1706 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1707 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1710 if ($contextid instanceof context
) {
1711 $context = $contextid;
1713 $context = context
::instance_by_id($contextid, MUST_EXIST
);
1716 if (!$timemodified) {
1717 $timemodified = time();
1720 // Check for existing entry
1721 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id
, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1724 // role already assigned - this should not happen
1725 if (count($ras) > 1) {
1726 // very weird - remove all duplicates!
1727 $ra = array_shift($ras);
1728 foreach ($ras as $r) {
1729 $DB->delete_records('role_assignments', array('id'=>$r->id
));
1735 // actually there is no need to update, reset anything or trigger any event, so just return
1739 // Create a new entry
1740 $ra = new stdClass();
1741 $ra->roleid
= $roleid;
1742 $ra->contextid
= $context->id
;
1743 $ra->userid
= $userid;
1744 $ra->component
= $component;
1745 $ra->itemid
= $itemid;
1746 $ra->timemodified
= $timemodified;
1747 $ra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
1749 $ra->id
= $DB->insert_record('role_assignments', $ra);
1751 // mark context as dirty - again expensive, but needed
1752 $context->mark_dirty();
1754 if (!empty($USER->id
) && $USER->id
== $userid) {
1755 // If the user is the current user, then do full reload of capabilities too.
1756 reload_all_capabilities();
1759 $event = \core\event\role_assigned
::create(
1760 array('context'=>$context, 'objectid'=>$ra->roleid
, 'relateduserid'=>$ra->userid
,
1761 'other'=>array('id'=>$ra->id
, 'component'=>$ra->component
, 'itemid'=>$ra->itemid
)));
1762 $event->add_record_snapshot('role_assignments', $ra);
1769 * Removes one role assignment
1771 * @param int $roleid
1772 * @param int $userid
1773 * @param int $contextid
1774 * @param string $component
1775 * @param int $itemid
1778 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1779 // first make sure the params make sense
1780 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1781 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1785 if (strpos($component, '_') === false) {
1786 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1790 if ($component !== '' and strpos($component, '_') === false) {
1791 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1795 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1799 * Removes multiple role assignments, parameters may contain:
1800 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1802 * @param array $params role assignment parameters
1803 * @param bool $subcontexts unassign in subcontexts too
1804 * @param bool $includemanual include manual role assignments too
1807 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1808 global $USER, $CFG, $DB;
1811 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1814 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1815 foreach ($params as $key=>$value) {
1816 if (!in_array($key, $allowed)) {
1817 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1821 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1822 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1825 if ($includemanual) {
1826 if (!isset($params['component']) or $params['component'] === '') {
1827 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1832 if (empty($params['contextid'])) {
1833 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1837 $ras = $DB->get_records('role_assignments', $params);
1838 foreach($ras as $ra) {
1839 $DB->delete_records('role_assignments', array('id'=>$ra->id
));
1840 if ($context = context
::instance_by_id($ra->contextid
, IGNORE_MISSING
)) {
1841 // this is a bit expensive but necessary
1842 $context->mark_dirty();
1843 // If the user is the current user, then do full reload of capabilities too.
1844 if (!empty($USER->id
) && $USER->id
== $ra->userid
) {
1845 reload_all_capabilities();
1847 $event = \core\event\role_unassigned
::create(
1848 array('context'=>$context, 'objectid'=>$ra->roleid
, 'relateduserid'=>$ra->userid
,
1849 'other'=>array('id'=>$ra->id
, 'component'=>$ra->component
, 'itemid'=>$ra->itemid
)));
1850 $event->add_record_snapshot('role_assignments', $ra);
1856 // process subcontexts
1857 if ($subcontexts and $context = context
::instance_by_id($params['contextid'], IGNORE_MISSING
)) {
1858 if ($params['contextid'] instanceof context
) {
1859 $context = $params['contextid'];
1861 $context = context
::instance_by_id($params['contextid'], IGNORE_MISSING
);
1865 $contexts = $context->get_child_contexts();
1867 foreach($contexts as $context) {
1868 $mparams['contextid'] = $context->id
;
1869 $ras = $DB->get_records('role_assignments', $mparams);
1870 foreach($ras as $ra) {
1871 $DB->delete_records('role_assignments', array('id'=>$ra->id
));
1872 // this is a bit expensive but necessary
1873 $context->mark_dirty();
1874 // If the user is the current user, then do full reload of capabilities too.
1875 if (!empty($USER->id
) && $USER->id
== $ra->userid
) {
1876 reload_all_capabilities();
1878 $event = \core\event\role_unassigned
::create(
1879 array('context'=>$context, 'objectid'=>$ra->roleid
, 'relateduserid'=>$ra->userid
,
1880 'other'=>array('id'=>$ra->id
, 'component'=>$ra->component
, 'itemid'=>$ra->itemid
)));
1881 $event->add_record_snapshot('role_assignments', $ra);
1888 // do this once more for all manual role assignments
1889 if ($includemanual) {
1890 $params['component'] = '';
1891 role_unassign_all($params, $subcontexts, false);
1896 * Determines if a user is currently logged in
1902 function isloggedin() {
1905 return (!empty($USER->id
));
1909 * Determines if a user is logged in as real guest user with username 'guest'.
1913 * @param int|object $user mixed user object or id, $USER if not specified
1914 * @return bool true if user is the real guest user, false if not logged in or other user
1916 function isguestuser($user = null) {
1917 global $USER, $DB, $CFG;
1919 // make sure we have the user id cached in config table, because we are going to use it a lot
1920 if (empty($CFG->siteguest
)) {
1921 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id
))) {
1922 // guest does not exist yet, weird
1925 set_config('siteguest', $guestid);
1927 if ($user === null) {
1931 if ($user === null) {
1932 // happens when setting the $USER
1935 } else if (is_numeric($user)) {
1936 return ($CFG->siteguest
== $user);
1938 } else if (is_object($user)) {
1939 if (empty($user->id
)) {
1940 return false; // not logged in means is not be guest
1942 return ($CFG->siteguest
== $user->id
);
1946 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1951 * Does user have a (temporary or real) guest access to course?
1955 * @param context $context
1956 * @param stdClass|int $user
1959 function is_guest(context
$context, $user = null) {
1962 // first find the course context
1963 $coursecontext = $context->get_course_context();
1965 // make sure there is a real user specified
1966 if ($user === null) {
1967 $userid = isset($USER->id
) ?
$USER->id
: 0;
1969 $userid = is_object($user) ?
$user->id
: $user;
1972 if (isguestuser($userid)) {
1973 // can not inspect or be enrolled
1977 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1978 // viewing users appear out of nowhere, they are neither guests nor participants
1982 // consider only real active enrolments here
1983 if (is_enrolled($coursecontext, $user, '', true)) {
1991 * Returns true if the user has moodle/course:view capability in the course,
1992 * this is intended for admins, managers (aka small admins), inspectors, etc.
1996 * @param context $context
1997 * @param int|stdClass $user if null $USER is used
1998 * @param string $withcapability extra capability name
2001 function is_viewing(context
$context, $user = null, $withcapability = '') {
2002 // first find the course context
2003 $coursecontext = $context->get_course_context();
2005 if (isguestuser($user)) {
2010 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2011 // admins are allowed to inspect courses
2015 if ($withcapability and !has_capability($withcapability, $context, $user)) {
2016 // site admins always have the capability, but the enrolment above blocks
2024 * Returns true if user is enrolled (is participating) in course
2025 * this is intended for students and teachers.
2027 * Since 2.2 the result for active enrolments and current user are cached.
2029 * @package core_enrol
2032 * @param context $context
2033 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
2034 * @param string $withcapability extra capability name
2035 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2038 function is_enrolled(context
$context, $user = null, $withcapability = '', $onlyactive = false) {
2041 // first find the course context
2042 $coursecontext = $context->get_course_context();
2044 // make sure there is a real user specified
2045 if ($user === null) {
2046 $userid = isset($USER->id
) ?
$USER->id
: 0;
2048 $userid = is_object($user) ?
$user->id
: $user;
2051 if (empty($userid)) {
2054 } else if (isguestuser($userid)) {
2055 // guest account can not be enrolled anywhere
2059 if ($coursecontext->instanceid
== SITEID
) {
2060 // everybody participates on frontpage
2062 // try cached info first - the enrolled flag is set only when active enrolment present
2063 if ($USER->id
== $userid) {
2064 $coursecontext->reload_if_dirty();
2065 if (isset($USER->enrol
['enrolled'][$coursecontext->instanceid
])) {
2066 if ($USER->enrol
['enrolled'][$coursecontext->instanceid
] > time()) {
2067 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2076 // look for active enrolments only
2077 $until = enrol_get_enrolment_end($coursecontext->instanceid
, $userid);
2079 if ($until === false) {
2083 if ($USER->id
== $userid) {
2085 $until = ENROL_MAX_TIMESTAMP
;
2087 $USER->enrol
['enrolled'][$coursecontext->instanceid
] = $until;
2088 if (isset($USER->enrol
['tempguest'][$coursecontext->instanceid
])) {
2089 unset($USER->enrol
['tempguest'][$coursecontext->instanceid
]);
2090 remove_temp_course_roles($coursecontext);
2095 // any enrolment is good for us here, even outdated, disabled or inactive
2097 FROM {user_enrolments} ue
2098 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2099 JOIN {user} u ON u.id = ue.userid
2100 WHERE ue.userid = :userid AND u.deleted = 0";
2101 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid
);
2102 if (!$DB->record_exists_sql($sql, $params)) {
2108 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2116 * Returns true if the user is able to access the course.
2118 * This function is in no way, shape, or form a substitute for require_login.
2119 * It should only be used in circumstances where it is not possible to call require_login
2120 * such as the navigation.
2122 * This function checks many of the methods of access to a course such as the view
2123 * capability, enrollments, and guest access. It also makes use of the cache
2124 * generated by require_login for guest access.
2126 * The flags within the $USER object that are used here should NEVER be used outside
2127 * of this function can_access_course and require_login. Doing so WILL break future
2130 * @param stdClass $course record
2131 * @param stdClass|int|null $user user record or id, current user if null
2132 * @param string $withcapability Check for this capability as well.
2133 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2134 * @return boolean Returns true if the user is able to access the course
2136 function can_access_course(stdClass
$course, $user = null, $withcapability = '', $onlyactive = false) {
2139 // this function originally accepted $coursecontext parameter
2140 if ($course instanceof context
) {
2141 if ($course instanceof context_course
) {
2142 debugging('deprecated context parameter, please use $course record');
2143 $coursecontext = $course;
2144 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid
));
2146 debugging('Invalid context parameter, please use $course record');
2150 $coursecontext = context_course
::instance($course->id
);
2153 if (!isset($USER->id
)) {
2154 // should never happen
2156 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER
);
2159 // make sure there is a user specified
2160 if ($user === null) {
2161 $userid = $USER->id
;
2163 $userid = is_object($user) ?
$user->id
: $user;
2167 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2171 if ($userid == $USER->id
) {
2172 if (!empty($USER->access
['rsw'][$coursecontext->path
])) {
2173 // the fact that somebody switched role means they can access the course no matter to what role they switched
2178 if (!$course->visible
and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2182 if (is_viewing($coursecontext, $userid)) {
2186 if ($userid != $USER->id
) {
2187 // for performance reasons we do not verify temporary guest access for other users, sorry...
2188 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2191 // === from here we deal only with $USER ===
2193 $coursecontext->reload_if_dirty();
2195 if (isset($USER->enrol
['enrolled'][$course->id
])) {
2196 if ($USER->enrol
['enrolled'][$course->id
] > time()) {
2200 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2201 if ($USER->enrol
['tempguest'][$course->id
] > time()) {
2206 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2210 // if not enrolled try to gain temporary guest access
2211 $instances = $DB->get_records('enrol', array('courseid'=>$course->id
, 'status'=>ENROL_INSTANCE_ENABLED
), 'sortorder, id ASC');
2212 $enrols = enrol_get_plugins(true);
2213 foreach($instances as $instance) {
2214 if (!isset($enrols[$instance->enrol
])) {
2217 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2218 $until = $enrols[$instance->enrol
]->try_guestaccess($instance);
2219 if ($until !== false and $until > time()) {
2220 $USER->enrol
['tempguest'][$course->id
] = $until;
2224 if (isset($USER->enrol
['tempguest'][$course->id
])) {
2225 unset($USER->enrol
['tempguest'][$course->id
]);
2226 remove_temp_course_roles($coursecontext);
2233 * Returns array with sql code and parameters returning all ids
2234 * of users enrolled into course.
2236 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2238 * @package core_enrol
2241 * @param context $context
2242 * @param string $withcapability
2243 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2244 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2245 * @return array list($sql, $params)
2247 function get_enrolled_sql(context
$context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2250 // use unique prefix just in case somebody makes some SQL magic with the result
2253 $prefix = 'eu'.$i.'_';
2255 // first find the course context
2256 $coursecontext = $context->get_course_context();
2258 $isfrontpage = ($coursecontext->instanceid
== SITEID
);
2264 list($contextids, $contextpaths) = get_context_info_list($context);
2266 // get all relevant capability info for all roles
2267 if ($withcapability) {
2268 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED
, 'ctx');
2269 $cparams['cap'] = $withcapability;
2272 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2273 FROM {role_capabilities} rc
2274 JOIN {context} ctx on rc.contextid = ctx.id
2275 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2276 $rcs = $DB->get_records_sql($sql, $cparams);
2277 foreach ($rcs as $rc) {
2278 $defs[$rc->path
][$rc->roleid
] = $rc->permission
;
2282 if (!empty($defs)) {
2283 foreach ($contextpaths as $path) {
2284 if (empty($defs[$path])) {
2287 foreach($defs[$path] as $roleid => $perm) {
2288 if ($perm == CAP_PROHIBIT
) {
2289 $access[$roleid] = CAP_PROHIBIT
;
2292 if (!isset($access[$roleid])) {
2293 $access[$roleid] = (int)$perm;
2301 // make lists of roles that are needed and prohibited
2302 $needed = array(); // one of these is enough
2303 $prohibited = array(); // must not have any of these
2304 foreach ($access as $roleid => $perm) {
2305 if ($perm == CAP_PROHIBIT
) {
2306 unset($needed[$roleid]);
2307 $prohibited[$roleid] = true;
2308 } else if ($perm == CAP_ALLOW
and empty($prohibited[$roleid])) {
2309 $needed[$roleid] = true;
2313 $defaultuserroleid = isset($CFG->defaultuserroleid
) ?
$CFG->defaultuserroleid
: 0;
2314 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid
) ?
$CFG->defaultfrontpageroleid
: 0;
2319 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2321 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2322 // everybody not having prohibit has the capability
2324 } else if (empty($needed)) {
2328 if (!empty($prohibited[$defaultuserroleid])) {
2330 } else if (!empty($needed[$defaultuserroleid])) {
2331 // everybody not having prohibit has the capability
2333 } else if (empty($needed)) {
2339 // nobody can match so return some SQL that does not return any results
2340 $wheres[] = "1 = 2";
2345 $ctxids = implode(',', $contextids);
2346 $roleids = implode(',', array_keys($needed));
2347 $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))";
2351 $ctxids = implode(',', $contextids);
2352 $roleids = implode(',', array_keys($prohibited));
2353 $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))";
2354 $wheres[] = "{$prefix}ra4.id IS NULL";
2358 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2359 $params["{$prefix}gmid"] = $groupid;
2365 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2366 $params["{$prefix}gmid"] = $groupid;
2370 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2371 $params["{$prefix}guestid"] = $CFG->siteguest
;
2374 // all users are "enrolled" on the frontpage
2376 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2377 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2378 $params[$prefix.'courseid'] = $coursecontext->instanceid
;
2381 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2382 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2383 $now = round(time(), -2); // rounding helps caching in DB
2384 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED
,
2385 $prefix.'active'=>ENROL_USER_ACTIVE
,
2386 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2390 $joins = implode("\n", $joins);
2391 $wheres = "WHERE ".implode(" AND ", $wheres);
2393 $sql = "SELECT DISTINCT {$prefix}u.id
2394 FROM {user} {$prefix}u
2398 return array($sql, $params);
2402 * Returns list of users enrolled into course.
2404 * @package core_enrol
2407 * @param context $context
2408 * @param string $withcapability
2409 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2410 * @param string $userfields requested user record fields
2411 * @param string $orderby
2412 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2413 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2414 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2415 * @return array of user records
2417 function get_enrolled_users(context
$context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
2418 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
2421 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2422 $sql = "SELECT $userfields
2424 JOIN ($esql) je ON je.id = u.id
2425 WHERE u.deleted = 0";
2428 $sql = "$sql ORDER BY $orderby";
2430 list($sort, $sortparams) = users_order_by_sql('u');
2431 $sql = "$sql ORDER BY $sort";
2432 $params = array_merge($params, $sortparams);
2435 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2439 * Counts list of users enrolled into course (as per above function)
2441 * @package core_enrol
2444 * @param context $context
2445 * @param string $withcapability
2446 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2447 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2448 * @return array of user records
2450 function count_enrolled_users(context
$context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2453 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
2454 $sql = "SELECT count(u.id)
2456 JOIN ($esql) je ON je.id = u.id
2457 WHERE u.deleted = 0";
2459 return $DB->count_records_sql($sql, $params);
2463 * Loads the capability definitions for the component (from file).
2465 * Loads the capability definitions for the component (from file). If no
2466 * capabilities are defined for the component, we simply return an empty array.
2469 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2470 * @return array array of capabilities
2472 function load_capability_def($component) {
2473 $defpath = core_component
::get_component_directory($component).'/db/access.php';
2475 $capabilities = array();
2476 if (file_exists($defpath)) {
2478 if (!empty($
{$component.'_capabilities'})) {
2479 // BC capability array name
2480 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2481 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2482 $capabilities = $
{$component.'_capabilities'};
2486 return $capabilities;
2490 * Gets the capabilities that have been cached in the database for this component.
2493 * @param string $component - examples: 'moodle', 'mod_forum'
2494 * @return array array of capabilities
2496 function get_cached_capabilities($component = 'moodle') {
2498 return $DB->get_records('capabilities', array('component'=>$component));
2502 * Returns default capabilities for given role archetype.
2504 * @param string $archetype role archetype
2507 function get_default_capabilities($archetype) {
2515 $defaults = array();
2516 $components = array();
2517 $allcaps = $DB->get_records('capabilities');
2519 foreach ($allcaps as $cap) {
2520 if (!in_array($cap->component
, $components)) {
2521 $components[] = $cap->component
;
2522 $alldefs = array_merge($alldefs, load_capability_def($cap->component
));
2525 foreach($alldefs as $name=>$def) {
2526 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2527 if (isset($def['archetypes'])) {
2528 if (isset($def['archetypes'][$archetype])) {
2529 $defaults[$name] = $def['archetypes'][$archetype];
2531 // 'legacy' is for backward compatibility with 1.9 access.php
2533 if (isset($def['legacy'][$archetype])) {
2534 $defaults[$name] = $def['legacy'][$archetype];
2543 * Return default roles that can be assigned, overridden or switched
2544 * by give role archetype.
2546 * @param string $type assign|override|switch
2547 * @param string $archetype
2548 * @return array of role ids
2550 function get_default_role_archetype_allows($type, $archetype) {
2553 if (empty($archetype)) {
2557 $roles = $DB->get_records('role');
2558 $archetypemap = array();
2559 foreach ($roles as $role) {
2560 if ($role->archetype
) {
2561 $archetypemap[$role->archetype
][$role->id
] = $role->id
;
2567 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student'),
2568 'coursecreator' => array(),
2569 'editingteacher' => array('teacher', 'student'),
2570 'teacher' => array(),
2571 'student' => array(),
2574 'frontpage' => array(),
2576 'override' => array(
2577 'manager' => array('manager', 'coursecreator', 'editingteacher', 'teacher', 'student', 'guest', 'user', 'frontpage'),
2578 'coursecreator' => array(),
2579 'editingteacher' => array('teacher', 'student', 'guest'),
2580 'teacher' => array(),
2581 'student' => array(),
2584 'frontpage' => array(),
2587 'manager' => array('editingteacher', 'teacher', 'student', 'guest'),
2588 'coursecreator' => array(),
2589 'editingteacher' => array('teacher', 'student', 'guest'),
2590 'teacher' => array('student', 'guest'),
2591 'student' => array(),
2594 'frontpage' => array(),
2598 if (!isset($defaults[$type][$archetype])) {
2599 debugging("Unknown type '$type'' or archetype '$archetype''");
2604 foreach ($defaults[$type][$archetype] as $at) {
2605 if (isset($archetypemap[$at])) {
2606 foreach ($archetypemap[$at] as $roleid) {
2607 $return[$roleid] = $roleid;
2616 * Reset role capabilities to default according to selected role archetype.
2617 * If no archetype selected, removes all capabilities.
2619 * @param int $roleid
2622 function reset_role_capabilities($roleid) {
2625 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST
);
2626 $defaultcaps = get_default_capabilities($role->archetype
);
2628 $systemcontext = context_system
::instance();
2630 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2632 foreach($defaultcaps as $cap=>$permission) {
2633 assign_capability($cap, $permission, $roleid, $systemcontext->id
);
2638 * Updates the capabilities table with the component capability definitions.
2639 * If no parameters are given, the function updates the core moodle
2642 * Note that the absence of the db/access.php capabilities definition file
2643 * will cause any stored capabilities for the component to be removed from
2647 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2648 * @return boolean true if success, exception in case of any problems
2650 function update_capabilities($component = 'moodle') {
2651 global $DB, $OUTPUT;
2653 $storedcaps = array();
2655 $filecaps = load_capability_def($component);
2656 foreach($filecaps as $capname=>$unused) {
2657 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2658 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2662 $cachedcaps = get_cached_capabilities($component);
2664 foreach ($cachedcaps as $cachedcap) {
2665 array_push($storedcaps, $cachedcap->name
);
2666 // update risk bitmasks and context levels in existing capabilities if needed
2667 if (array_key_exists($cachedcap->name
, $filecaps)) {
2668 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name
])) {
2669 $filecaps[$cachedcap->name
]['riskbitmask'] = 0; // no risk if not specified
2671 if ($cachedcap->captype
!= $filecaps[$cachedcap->name
]['captype']) {
2672 $updatecap = new stdClass();
2673 $updatecap->id
= $cachedcap->id
;
2674 $updatecap->captype
= $filecaps[$cachedcap->name
]['captype'];
2675 $DB->update_record('capabilities', $updatecap);
2677 if ($cachedcap->riskbitmask
!= $filecaps[$cachedcap->name
]['riskbitmask']) {
2678 $updatecap = new stdClass();
2679 $updatecap->id
= $cachedcap->id
;
2680 $updatecap->riskbitmask
= $filecaps[$cachedcap->name
]['riskbitmask'];
2681 $DB->update_record('capabilities', $updatecap);
2684 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name
])) {
2685 $filecaps[$cachedcap->name
]['contextlevel'] = 0; // no context level defined
2687 if ($cachedcap->contextlevel
!= $filecaps[$cachedcap->name
]['contextlevel']) {
2688 $updatecap = new stdClass();
2689 $updatecap->id
= $cachedcap->id
;
2690 $updatecap->contextlevel
= $filecaps[$cachedcap->name
]['contextlevel'];
2691 $DB->update_record('capabilities', $updatecap);
2697 // Are there new capabilities in the file definition?
2700 foreach ($filecaps as $filecap => $def) {
2702 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2703 if (!array_key_exists('riskbitmask', $def)) {
2704 $def['riskbitmask'] = 0; // no risk if not specified
2706 $newcaps[$filecap] = $def;
2709 // Add new capabilities to the stored definition.
2710 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2711 foreach ($newcaps as $capname => $capdef) {
2712 $capability = new stdClass();
2713 $capability->name
= $capname;
2714 $capability->captype
= $capdef['captype'];
2715 $capability->contextlevel
= $capdef['contextlevel'];
2716 $capability->component
= $component;
2717 $capability->riskbitmask
= $capdef['riskbitmask'];
2719 $DB->insert_record('capabilities', $capability, false);
2721 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2722 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2723 foreach ($rolecapabilities as $rolecapability){
2724 //assign_capability will update rather than insert if capability exists
2725 if (!assign_capability($capname, $rolecapability->permission
,
2726 $rolecapability->roleid
, $rolecapability->contextid
, true)){
2727 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2731 // we ignore archetype key if we have cloned permissions
2732 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2733 assign_legacy_capabilities($capname, $capdef['archetypes']);
2734 // 'legacy' is for backward compatibility with 1.9 access.php
2735 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2736 assign_legacy_capabilities($capname, $capdef['legacy']);
2739 // Are there any capabilities that have been removed from the file
2740 // definition that we need to delete from the stored capabilities and
2741 // role assignments?
2742 capabilities_cleanup($component, $filecaps);
2744 // reset static caches
2745 accesslib_clear_all_caches(false);
2751 * Deletes cached capabilities that are no longer needed by the component.
2752 * Also unassigns these capabilities from any roles that have them.
2753 * NOTE: this function is called from lib/db/upgrade.php
2756 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2757 * @param array $newcapdef array of the new capability definitions that will be
2758 * compared with the cached capabilities
2759 * @return int number of deprecated capabilities that have been removed
2761 function capabilities_cleanup($component, $newcapdef = null) {
2766 if ($cachedcaps = get_cached_capabilities($component)) {
2767 foreach ($cachedcaps as $cachedcap) {
2768 if (empty($newcapdef) ||
2769 array_key_exists($cachedcap->name
, $newcapdef) === false) {
2771 // Remove from capabilities cache.
2772 $DB->delete_records('capabilities', array('name'=>$cachedcap->name
));
2774 // Delete from roles.
2775 if ($roles = get_roles_with_capability($cachedcap->name
)) {
2776 foreach($roles as $role) {
2777 if (!unassign_capability($cachedcap->name
, $role->id
)) {
2778 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name
, 'role'=>$role->name
));
2785 return $removedcount;
2789 * Returns an array of all the known types of risk
2790 * The array keys can be used, for example as CSS class names, or in calls to
2791 * print_risk_icon. The values are the corresponding RISK_ constants.
2793 * @return array all the known types of risk.
2795 function get_all_risks() {
2797 'riskmanagetrust' => RISK_MANAGETRUST
,
2798 'riskconfig' => RISK_CONFIG
,
2799 'riskxss' => RISK_XSS
,
2800 'riskpersonal' => RISK_PERSONAL
,
2801 'riskspam' => RISK_SPAM
,
2802 'riskdataloss' => RISK_DATALOSS
,
2807 * Return a link to moodle docs for a given capability name
2809 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2810 * @return string the human-readable capability name as a link to Moodle Docs.
2812 function get_capability_docs_link($capability) {
2813 $url = get_docs_url('Capabilities/' . $capability->name
);
2814 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name
) . '</a>';
2818 * This function pulls out all the resolved capabilities (overrides and
2819 * defaults) of a role used in capability overrides in contexts at a given
2822 * @param int $roleid
2823 * @param context $context
2824 * @param string $cap capability, optional, defaults to ''
2825 * @return array Array of capabilities
2827 function role_context_capabilities($roleid, context
$context, $cap = '') {
2830 $contexts = $context->get_parent_context_ids(true);
2831 $contexts = '('.implode(',', $contexts).')';
2833 $params = array($roleid);
2836 $search = " AND rc.capability = ? ";
2843 FROM {role_capabilities} rc, {context} c
2844 WHERE rc.contextid in $contexts
2846 AND rc.contextid = c.id $search
2847 ORDER BY c.contextlevel DESC, rc.capability DESC";
2849 $capabilities = array();
2851 if ($records = $DB->get_records_sql($sql, $params)) {
2852 // We are traversing via reverse order.
2853 foreach ($records as $record) {
2854 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2855 if (!isset($capabilities[$record->capability
]) ||
$record->permission
<-500) {
2856 $capabilities[$record->capability
] = $record->permission
;
2860 return $capabilities;
2864 * Constructs array with contextids as first parameter and context paths,
2865 * in both cases bottom top including self.
2868 * @param context $context
2871 function get_context_info_list(context
$context) {
2872 $contextids = explode('/', ltrim($context->path
, '/'));
2873 $contextpaths = array();
2874 $contextids2 = $contextids;
2875 while ($contextids2) {
2876 $contextpaths[] = '/' . implode('/', $contextids2);
2877 array_pop($contextids2);
2879 return array($contextids, $contextpaths);
2883 * Check if context is the front page context or a context inside it
2885 * Returns true if this context is the front page context, or a context inside it,
2888 * @param context $context a context object.
2891 function is_inside_frontpage(context
$context) {
2892 $frontpagecontext = context_course
::instance(SITEID
);
2893 return strpos($context->path
. '/', $frontpagecontext->path
. '/') === 0;
2897 * Returns capability information (cached)
2899 * @param string $capabilityname
2900 * @return stdClass or null if capability not found
2902 function get_capability_info($capabilityname) {
2903 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2905 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2907 if (empty($ACCESSLIB_PRIVATE->capabilities
)) {
2908 $ACCESSLIB_PRIVATE->capabilities
= array();
2909 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2910 foreach ($caps as $cap) {
2911 $capname = $cap->name
;
2914 $cap->riskbitmask
= (int)$cap->riskbitmask
;
2915 $ACCESSLIB_PRIVATE->capabilities
[$capname] = $cap;
2919 return isset($ACCESSLIB_PRIVATE->capabilities
[$capabilityname]) ?
$ACCESSLIB_PRIVATE->capabilities
[$capabilityname] : null;
2923 * Returns the human-readable, translated version of the capability.
2924 * Basically a big switch statement.
2926 * @param string $capabilityname e.g. mod/choice:readresponses
2929 function get_capability_string($capabilityname) {
2931 // Typical capability name is 'plugintype/pluginname:capabilityname'
2932 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2934 if ($type === 'moodle') {
2935 $component = 'core_role';
2936 } else if ($type === 'quizreport') {
2938 $component = 'quiz_'.$name;
2940 $component = $type.'_'.$name;
2943 $stringname = $name.':'.$capname;
2945 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2946 return get_string($stringname, $component);
2949 $dir = core_component
::get_component_directory($component);
2950 if (!file_exists($dir)) {
2951 // plugin broken or does not exist, do not bother with printing of debug message
2952 return $capabilityname.' ???';
2955 // something is wrong in plugin, better print debug
2956 return get_string($stringname, $component);
2960 * This gets the mod/block/course/core etc strings.
2962 * @param string $component
2963 * @param int $contextlevel
2964 * @return string|bool String is success, false if failed
2966 function get_component_string($component, $contextlevel) {
2968 if ($component === 'moodle' or $component === 'core') {
2969 switch ($contextlevel) {
2970 // TODO: this should probably use context level names instead
2971 case CONTEXT_SYSTEM
: return get_string('coresystem');
2972 case CONTEXT_USER
: return get_string('users');
2973 case CONTEXT_COURSECAT
: return get_string('categories');
2974 case CONTEXT_COURSE
: return get_string('course');
2975 case CONTEXT_MODULE
: return get_string('activities');
2976 case CONTEXT_BLOCK
: return get_string('block');
2977 default: print_error('unknowncontext');
2981 list($type, $name) = core_component
::normalize_component($component);
2982 $dir = core_component
::get_plugin_directory($type, $name);
2983 if (!file_exists($dir)) {
2984 // plugin not installed, bad luck, there is no way to find the name
2985 return $component.' ???';
2989 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2990 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2991 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2992 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2993 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2994 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2995 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2996 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2998 if (get_string_manager()->string_exists('pluginname', $component)) {
2999 return get_string('activity').': '.get_string('pluginname', $component);
3001 return get_string('activity').': '.get_string('modulename', $component);
3003 default: return get_string('pluginname', $component);
3008 * Gets the list of roles assigned to this context and up (parents)
3009 * from the list of roles that are visible on user profile page
3010 * and participants page.
3012 * @param context $context
3015 function get_profile_roles(context
$context) {
3018 if (empty($CFG->profileroles
)) {
3022 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles
), SQL_PARAMS_NAMED
, 'a');
3023 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'p');
3024 $params = array_merge($params, $cparams);
3026 if ($coursecontext = $context->get_course_context(false)) {
3027 $params['coursecontext'] = $coursecontext->id
;
3029 $params['coursecontext'] = 0;
3032 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3033 FROM {role_assignments} ra, {role} r
3034 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3035 WHERE r.id = ra.roleid
3036 AND ra.contextid $contextlist
3038 ORDER BY r.sortorder ASC";
3040 return $DB->get_records_sql($sql, $params);
3044 * Gets the list of roles assigned to this context and up (parents)
3046 * @param context $context
3049 function get_roles_used_in_context(context
$context) {
3052 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'cl');
3054 if ($coursecontext = $context->get_course_context(false)) {
3055 $params['coursecontext'] = $coursecontext->id
;
3057 $params['coursecontext'] = 0;
3060 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3061 FROM {role_assignments} ra, {role} r
3062 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3063 WHERE r.id = ra.roleid
3064 AND ra.contextid $contextlist
3065 ORDER BY r.sortorder ASC";
3067 return $DB->get_records_sql($sql, $params);
3071 * This function is used to print roles column in user profile page.
3072 * It is using the CFG->profileroles to limit the list to only interesting roles.
3073 * (The permission tab has full details of user role assignments.)
3075 * @param int $userid
3076 * @param int $courseid
3079 function get_user_roles_in_course($userid, $courseid) {
3082 if (empty($CFG->profileroles
)) {
3086 if ($courseid == SITEID
) {
3087 $context = context_system
::instance();
3089 $context = context_course
::instance($courseid);
3092 if (empty($CFG->profileroles
)) {
3096 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles
), SQL_PARAMS_NAMED
, 'a');
3097 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED
, 'p');
3098 $params = array_merge($params, $cparams);
3100 if ($coursecontext = $context->get_course_context(false)) {
3101 $params['coursecontext'] = $coursecontext->id
;
3103 $params['coursecontext'] = 0;
3106 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
3107 FROM {role_assignments} ra, {role} r
3108 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3109 WHERE r.id = ra.roleid
3110 AND ra.contextid $contextlist
3112 AND ra.userid = :userid
3113 ORDER BY r.sortorder ASC";
3114 $params['userid'] = $userid;
3118 if ($roles = $DB->get_records_sql($sql, $params)) {
3119 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS
, true); // Substitute aliases
3121 foreach ($rolenames as $roleid => $rolename) {
3122 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot
.'/user/index.php?contextid='.$context->id
.'&roleid='.$roleid.'">'.$rolename.'</a>';
3124 $rolestring = implode(',', $rolenames);
3131 * Checks if a user can assign users to a particular role in this context
3133 * @param context $context
3134 * @param int $targetroleid - the id of the role you want to assign users to
3137 function user_can_assign(context
$context, $targetroleid) {
3140 // First check to see if the user is a site administrator.
3141 if (is_siteadmin()) {
3145 // Check if user has override capability.
3146 // If not return false.
3147 if (!has_capability('moodle/role:assign', $context)) {
3150 // pull out all active roles of this user from this context(or above)
3151 if ($userroles = get_user_roles($context)) {
3152 foreach ($userroles as $userrole) {
3153 // if any in the role_allow_override table, then it's ok
3154 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid
, 'allowassign'=>$targetroleid))) {
3164 * Returns all site roles in correct sort order.
3166 * Note: this method does not localise role names or descriptions,
3167 * use role_get_names() if you need role names.
3169 * @param context $context optional context for course role name aliases
3170 * @return array of role records with optional coursealias property
3172 function get_all_roles(context
$context = null) {
3175 if (!$context or !$coursecontext = $context->get_course_context(false)) {
3176 $coursecontext = null;
3179 if ($coursecontext) {
3180 $sql = "SELECT r.*, rn.name AS coursealias
3182 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3183 ORDER BY r.sortorder ASC";
3184 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id
));
3187 return $DB->get_records('role', array(), 'sortorder ASC');
3192 * Returns roles of a specified archetype
3194 * @param string $archetype
3195 * @return array of full role records
3197 function get_archetype_roles($archetype) {
3199 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
3203 * Gets all the user roles assigned in this context, or higher contexts
3204 * this is mainly used when checking if a user can assign a role, or overriding a role
3205 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3206 * allow_override tables
3208 * @param context $context
3209 * @param int $userid
3210 * @param bool $checkparentcontexts defaults to true
3211 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3214 function get_user_roles(context
$context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3217 if (empty($userid)) {
3218 if (empty($USER->id
)) {
3221 $userid = $USER->id
;
3224 if ($checkparentcontexts) {
3225 $contextids = $context->get_parent_context_ids();
3227 $contextids = array();
3229 $contextids[] = $context->id
;
3231 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM
);
3233 array_unshift($params, $userid);
3235 $sql = "SELECT ra.*, r.name, r.shortname
3236 FROM {role_assignments} ra, {role} r, {context} c
3238 AND ra.roleid = r.id
3239 AND ra.contextid = c.id
3240 AND ra.contextid $contextids
3243 return $DB->get_records_sql($sql ,$params);
3247 * Like get_user_roles, but adds in the authenticated user role, and the front
3248 * page roles, if applicable.
3250 * @param context $context the context.
3251 * @param int $userid optional. Defaults to $USER->id
3252 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3254 function get_user_roles_with_special(context
$context, $userid = 0) {
3257 if (empty($userid)) {
3258 if (empty($USER->id
)) {
3261 $userid = $USER->id
;
3264 $ras = get_user_roles($context, $userid);
3266 // Add front-page role if relevant.
3267 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid
) ?
$CFG->defaultfrontpageroleid
: 0;
3268 $isfrontpage = ($context->contextlevel
== CONTEXT_COURSE
&& $context->instanceid
== SITEID
) ||
3269 is_inside_frontpage($context);
3270 if ($defaultfrontpageroleid && $isfrontpage) {
3271 $frontpagecontext = context_course
::instance(SITEID
);
3272 $ra = new stdClass();
3273 $ra->userid
= $userid;
3274 $ra->contextid
= $frontpagecontext->id
;
3275 $ra->roleid
= $defaultfrontpageroleid;
3279 // Add authenticated user role if relevant.
3280 $defaultuserroleid = isset($CFG->defaultuserroleid
) ?
$CFG->defaultuserroleid
: 0;
3281 if ($defaultuserroleid && !isguestuser($userid)) {
3282 $systemcontext = context_system
::instance();
3283 $ra = new stdClass();
3284 $ra->userid
= $userid;
3285 $ra->contextid
= $systemcontext->id
;
3286 $ra->roleid
= $defaultuserroleid;
3294 * Creates a record in the role_allow_override table
3296 * @param int $sroleid source roleid
3297 * @param int $troleid target roleid
3300 function allow_override($sroleid, $troleid) {
3303 $record = new stdClass();
3304 $record->roleid
= $sroleid;
3305 $record->allowoverride
= $troleid;
3306 $DB->insert_record('role_allow_override', $record);
3310 * Creates a record in the role_allow_assign table
3312 * @param int $fromroleid source roleid
3313 * @param int $targetroleid target roleid
3316 function allow_assign($fromroleid, $targetroleid) {
3319 $record = new stdClass();
3320 $record->roleid
= $fromroleid;
3321 $record->allowassign
= $targetroleid;
3322 $DB->insert_record('role_allow_assign', $record);
3326 * Creates a record in the role_allow_switch table
3328 * @param int $fromroleid source roleid
3329 * @param int $targetroleid target roleid
3332 function allow_switch($fromroleid, $targetroleid) {
3335 $record = new stdClass();
3336 $record->roleid
= $fromroleid;
3337 $record->allowswitch
= $targetroleid;
3338 $DB->insert_record('role_allow_switch', $record);
3342 * Gets a list of roles that this user can assign in this context
3344 * @param context $context the context.
3345 * @param int $rolenamedisplay the type of role name to display. One of the
3346 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3347 * @param bool $withusercounts if true, count the number of users with each role.
3348 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3349 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3350 * if $withusercounts is true, returns a list of three arrays,
3351 * $rolenames, $rolecounts, and $nameswithcounts.
3353 function get_assignable_roles(context
$context, $rolenamedisplay = ROLENAME_ALIAS
, $withusercounts = false, $user = null) {
3356 // make sure there is a real user specified
3357 if ($user === null) {
3358 $userid = isset($USER->id
) ?
$USER->id
: 0;
3360 $userid = is_object($user) ?
$user->id
: $user;
3363 if (!has_capability('moodle/role:assign', $context, $userid)) {
3364 if ($withusercounts) {
3365 return array(array(), array(), array());
3374 if ($withusercounts) {
3375 $extrafields = ', (SELECT count(u.id)
3376 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3377 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3379 $params['conid'] = $context->id
;
3382 if (is_siteadmin($userid)) {
3383 // show all roles allowed in this context to admins
3384 $assignrestriction = "";
3386 $parents = $context->get_parent_context_ids(true);
3387 $contexts = implode(',' , $parents);
3388 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3389 FROM {role_allow_assign} raa
3390 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3391 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3392 ) ar ON ar.id = r.id";
3393 $params['userid'] = $userid;
3395 $params['contextlevel'] = $context->contextlevel
;
3397 if ($coursecontext = $context->get_course_context(false)) {
3398 $params['coursecontext'] = $coursecontext->id
;
3400 $params['coursecontext'] = 0; // no course aliases
3401 $coursecontext = null;
3403 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3406 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3407 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3408 ORDER BY r.sortorder ASC";
3409 $roles = $DB->get_records_sql($sql, $params);
3411 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3413 if (!$withusercounts) {
3417 $rolecounts = array();
3418 $nameswithcounts = array();
3419 foreach ($roles as $role) {
3420 $nameswithcounts[$role->id
] = $rolenames[$role->id
] . ' (' . $roles[$role->id
]->usercount
. ')';
3421 $rolecounts[$role->id
] = $roles[$role->id
]->usercount
;
3423 return array($rolenames, $rolecounts, $nameswithcounts);
3427 * Gets a list of roles that this user can switch to in a context
3429 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3430 * This function just process the contents of the role_allow_switch table. You also need to
3431 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3433 * @param context $context a context.
3434 * @return array an array $roleid => $rolename.
3436 function get_switchable_roles(context
$context) {
3442 if (!is_siteadmin()) {
3443 // Admins are allowed to switch to any role with.
3444 // Others are subject to the additional constraint that the switch-to role must be allowed by
3445 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3446 $parents = $context->get_parent_context_ids(true);
3447 $contexts = implode(',' , $parents);
3449 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3450 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3451 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3452 $params['userid'] = $USER->id
;
3455 if ($coursecontext = $context->get_course_context(false)) {
3456 $params['coursecontext'] = $coursecontext->id
;
3458 $params['coursecontext'] = 0; // no course aliases
3459 $coursecontext = null;
3463 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3464 FROM (SELECT DISTINCT rc.roleid
3465 FROM {role_capabilities} rc
3468 JOIN {role} r ON r.id = idlist.roleid
3469 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3470 ORDER BY r.sortorder";
3471 $roles = $DB->get_records_sql($query, $params);
3473 return role_fix_names($roles, $context, ROLENAME_ALIAS
, true);
3477 * Gets a list of roles that this user can override in this context.
3479 * @param context $context the context.
3480 * @param int $rolenamedisplay the type of role name to display. One of the
3481 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3482 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3483 * @return array if $withcounts is false, then an array $roleid => $rolename.
3484 * if $withusercounts is true, returns a list of three arrays,
3485 * $rolenames, $rolecounts, and $nameswithcounts.
3487 function get_overridable_roles(context
$context, $rolenamedisplay = ROLENAME_ALIAS
, $withcounts = false) {
3490 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3492 return array(array(), array(), array());
3498 $parents = $context->get_parent_context_ids(true);
3499 $contexts = implode(',' , $parents);
3504 $params['userid'] = $USER->id
;
3506 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3507 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3508 $params['conid'] = $context->id
;
3511 if ($coursecontext = $context->get_course_context(false)) {
3512 $params['coursecontext'] = $coursecontext->id
;
3514 $params['coursecontext'] = 0; // no course aliases
3515 $coursecontext = null;
3518 if (is_siteadmin()) {
3519 // show all roles to admins
3520 $roles = $DB->get_records_sql("
3521 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3523 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3524 ORDER BY ro.sortorder ASC", $params);
3527 $roles = $DB->get_records_sql("
3528 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3530 JOIN (SELECT DISTINCT r.id
3532 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3533 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3534 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3535 ) inline_view ON ro.id = inline_view.id
3536 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3537 ORDER BY ro.sortorder ASC", $params);
3540 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3546 $rolecounts = array();
3547 $nameswithcounts = array();
3548 foreach ($roles as $role) {
3549 $nameswithcounts[$role->id
] = $rolenames[$role->id
] . ' (' . $roles[$role->id
]->overridecount
. ')';
3550 $rolecounts[$role->id
] = $roles[$role->id
]->overridecount
;
3552 return array($rolenames, $rolecounts, $nameswithcounts);
3556 * Create a role menu suitable for default role selection in enrol plugins.
3558 * @package core_enrol
3560 * @param context $context
3561 * @param int $addroleid current or default role - always added to list
3562 * @return array roleid=>localised role name
3564 function get_default_enrol_roles(context
$context, $addroleid = null) {
3567 $params = array('contextlevel'=>CONTEXT_COURSE
);
3569 if ($coursecontext = $context->get_course_context(false)) {
3570 $params['coursecontext'] = $coursecontext->id
;
3572 $params['coursecontext'] = 0; // no course names
3573 $coursecontext = null;
3577 $addrole = "OR r.id = :addroleid";
3578 $params['addroleid'] = $addroleid;
3583 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3585 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3586 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3587 WHERE rcl.id IS NOT NULL $addrole
3588 ORDER BY sortorder DESC";
3590 $roles = $DB->get_records_sql($sql, $params);
3592 return role_fix_names($roles, $context, ROLENAME_BOTH
, true);
3596 * Return context levels where this role is assignable.
3598 * @param integer $roleid the id of a role.
3599 * @return array list of the context levels at which this role may be assigned.
3601 function get_role_contextlevels($roleid) {
3603 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3604 'contextlevel', 'id,contextlevel');
3608 * Return roles suitable for assignment at the specified context level.
3610 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3612 * @param integer $contextlevel a contextlevel.
3613 * @return array list of role ids that are assignable at this context level.
3615 function get_roles_for_contextlevels($contextlevel) {
3617 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3622 * Returns default context levels where roles can be assigned.
3624 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3625 * from the array returned by get_role_archetypes();
3626 * @return array list of the context levels at which this type of role may be assigned by default.
3628 function get_default_contextlevels($rolearchetype) {
3629 static $defaults = array(
3630 'manager' => array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
, CONTEXT_COURSE
),
3631 'coursecreator' => array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
),
3632 'editingteacher' => array(CONTEXT_COURSE
, CONTEXT_MODULE
),
3633 'teacher' => array(CONTEXT_COURSE
, CONTEXT_MODULE
),
3634 'student' => array(CONTEXT_COURSE
, CONTEXT_MODULE
),
3637 'frontpage' => array());
3639 if (isset($defaults[$rolearchetype])) {
3640 return $defaults[$rolearchetype];
3647 * Set the context levels at which a particular role can be assigned.
3648 * Throws exceptions in case of error.
3650 * @param integer $roleid the id of a role.
3651 * @param array $contextlevels the context levels at which this role should be assignable,
3652 * duplicate levels are removed.
3655 function set_role_contextlevels($roleid, array $contextlevels) {
3657 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3658 $rcl = new stdClass();
3659 $rcl->roleid
= $roleid;
3660 $contextlevels = array_unique($contextlevels);
3661 foreach ($contextlevels as $level) {
3662 $rcl->contextlevel
= $level;
3663 $DB->insert_record('role_context_levels', $rcl, false, true);
3668 * Who has this capability in this context?
3670 * This can be a very expensive call - use sparingly and keep
3671 * the results if you are going to need them again soon.
3673 * Note if $fields is empty this function attempts to get u.*
3674 * which can get rather large - and has a serious perf impact
3677 * @param context $context
3678 * @param string|array $capability - capability name(s)
3679 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3680 * @param string $sort - the sort order. Default is lastaccess time.
3681 * @param mixed $limitfrom - number of records to skip (offset)
3682 * @param mixed $limitnum - number of records to fetch
3683 * @param string|array $groups - single group or array of groups - only return
3684 * users who are in one of these group(s).
3685 * @param string|array $exceptions - list of users to exclude, comma separated or array
3686 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3687 * @param bool $view_ignored - use get_enrolled_sql() instead
3688 * @param bool $useviewallgroups if $groups is set the return users who
3689 * have capability both $capability and moodle/site:accessallgroups
3690 * in this context, as well as users who have $capability and who are
3692 * @return array of user records
3694 function get_users_by_capability(context
$context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3695 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3698 $defaultuserroleid = isset($CFG->defaultuserroleid
) ?
$CFG->defaultuserroleid
: 0;
3699 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid
) ?
$CFG->defaultfrontpageroleid
: 0;
3701 $ctxids = trim($context->path
, '/');
3702 $ctxids = str_replace('/', ',', $ctxids);
3704 // Context is the frontpage
3705 $iscoursepage = false; // coursepage other than fp
3706 $isfrontpage = false;
3707 if ($context->contextlevel
== CONTEXT_COURSE
) {
3708 if ($context->instanceid
== SITEID
) {
3709 $isfrontpage = true;
3711 $iscoursepage = true;
3714 $isfrontpage = ($isfrontpage ||
is_inside_frontpage($context));
3716 $caps = (array)$capability;
3718 // construct list of context paths bottom-->top
3719 list($contextids, $paths) = get_context_info_list($context);
3721 // we need to find out all roles that have these capabilities either in definition or in overrides
3723 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED
, 'con');
3724 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED
, 'cap');
3725 $params = array_merge($params, $params2);
3726 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3727 FROM {role_capabilities} rc
3728 JOIN {context} ctx on rc.contextid = ctx.id
3729 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3731 $rcs = $DB->get_records_sql($sql, $params);
3732 foreach ($rcs as $rc) {
3733 $defs[$rc->capability
][$rc->path
][$rc->roleid
] = $rc->permission
;
3736 // go through the permissions bottom-->top direction to evaluate the current permission,
3737 // first one wins (prohibit is an exception that always wins)
3739 foreach ($caps as $cap) {
3740 foreach ($paths as $path) {
3741 if (empty($defs[$cap][$path])) {
3744 foreach($defs[$cap][$path] as $roleid => $perm) {
3745 if ($perm == CAP_PROHIBIT
) {
3746 $access[$cap][$roleid] = CAP_PROHIBIT
;
3749 if (!isset($access[$cap][$roleid])) {
3750 $access[$cap][$roleid] = (int)$perm;
3756 // make lists of roles that are needed and prohibited in this context
3757 $needed = array(); // one of these is enough
3758 $prohibited = array(); // must not have any of these
3759 foreach ($caps as $cap) {
3760 if (empty($access[$cap])) {
3763 foreach ($access[$cap] as $roleid => $perm) {
3764 if ($perm == CAP_PROHIBIT
) {
3765 unset($needed[$cap][$roleid]);
3766 $prohibited[$cap][$roleid] = true;
3767 } else if ($perm == CAP_ALLOW
and empty($prohibited[$cap][$roleid])) {
3768 $needed[$cap][$roleid] = true;
3771 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3772 // easy, nobody has the permission
3773 unset($needed[$cap]);
3774 unset($prohibited[$cap]);
3775 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3776 // everybody is disqualified on the frontpage
3777 unset($needed[$cap]);
3778 unset($prohibited[$cap]);
3780 if (empty($prohibited[$cap])) {
3781 unset($prohibited[$cap]);
3785 if (empty($needed)) {
3786 // there can not be anybody if no roles match this request
3790 if (empty($prohibited)) {
3791 // we can compact the needed roles
3793 foreach ($needed as $cap) {
3794 foreach ($cap as $roleid=>$unused) {
3798 $needed = array('any'=>$n);
3802 // ***** Set up default fields ******
3803 if (empty($fields)) {
3804 if ($iscoursepage) {
3805 $fields = 'u.*, ul.timeaccess AS lastaccess';
3810 if ($CFG->debugdeveloper
&& strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3811 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER
);
3815 // Set up default sort
3816 if (empty($sort)) { // default to course lastaccess or just lastaccess
3817 if ($iscoursepage) {
3818 $sort = 'ul.timeaccess';
3820 $sort = 'u.lastaccess';
3824 // Prepare query clauses
3825 $wherecond = array();
3829 // User lastaccess JOIN
3830 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3831 // user_lastaccess is not required MDL-13810
3833 if ($iscoursepage) {
3834 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3836 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3840 // We never return deleted users or guest account.
3841 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3842 $params['guestid'] = $CFG->siteguest
;
3846 $groups = (array)$groups;
3847 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED
, 'grp');
3848 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3849 $params = array_merge($params, $grpparams);
3851 if ($useviewallgroups) {
3852 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3853 if (!empty($viewallgroupsusers)) {
3854 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3856 $wherecond[] = "($grouptest)";
3859 $wherecond[] = "($grouptest)";
3864 if (!empty($exceptions)) {
3865 $exceptions = (array)$exceptions;
3866 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED
, 'exc', false);
3867 $params = array_merge($params, $exparams);
3868 $wherecond[] = "u.id $exsql";
3871 // now add the needed and prohibited roles conditions as joins
3872 if (!empty($needed['any'])) {
3873 // simple case - there are no prohibits involved
3874 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3877 $joins[] = "JOIN (SELECT DISTINCT userid
3878 FROM {role_assignments}
3879 WHERE contextid IN ($ctxids)
3880 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3881 ) ra ON ra.userid = u.id";
3886 foreach ($needed as $cap=>$unused) {
3887 if (empty($prohibited[$cap])) {
3888 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3892 $unions[] = "SELECT userid
3893 FROM {role_assignments}
3894 WHERE contextid IN ($ctxids)
3895 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3898 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3899 // nobody can have this cap because it is prevented in default roles
3902 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3903 // everybody except the prohibitted - hiding does not matter
3904 $unions[] = "SELECT id AS userid
3906 WHERE id NOT IN (SELECT userid
3907 FROM {role_assignments}
3908 WHERE contextid IN ($ctxids)
3909 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3912 $unions[] = "SELECT userid
3913 FROM {role_assignments}
3914 WHERE contextid IN ($ctxids)
3915 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3916 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3922 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3924 // only prohibits found - nobody can be matched
3925 $wherecond[] = "1 = 2";
3930 // Collect WHERE conditions and needed joins
3931 $where = implode(' AND ', $wherecond);
3932 if ($where !== '') {
3933 $where = 'WHERE ' . $where;
3935 $joins = implode("\n", $joins);
3937 // Ok, let's get the users!
3938 $sql = "SELECT $fields
3944 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3948 * Re-sort a users array based on a sorting policy
3950 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3951 * based on a sorting policy. This is to support the odd practice of
3952 * sorting teachers by 'authority', where authority was "lowest id of the role
3955 * Will execute 1 database query. Only suitable for small numbers of users, as it
3956 * uses an u.id IN() clause.
3958 * Notes about the sorting criteria.
3960 * As a default, we cannot rely on role.sortorder because then
3961 * admins/coursecreators will always win. That is why the sane
3962 * rule "is locality matters most", with sortorder as 2nd
3965 * If you want role.sortorder, use the 'sortorder' policy, and
3966 * name explicitly what roles you want to cover. It's probably
3967 * a good idea to see what roles have the capabilities you want
3968 * (array_diff() them against roiles that have 'can-do-anything'
3969 * to weed out admin-ish roles. Or fetch a list of roles from
3970 * variables like $CFG->coursecontact .
3972 * @param array $users Users array, keyed on userid
3973 * @param context $context
3974 * @param array $roles ids of the roles to include, optional
3975 * @param string $sortpolicy defaults to locality, more about
3976 * @return array sorted copy of the array
3978 function sort_by_roleassignment_authority($users, context
$context, $roles = array(), $sortpolicy = 'locality') {
3981 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3982 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path
, 1)).')';
3983 if (empty($roles)) {
3986 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3989 $sql = "SELECT ra.userid
3990 FROM {role_assignments} ra
3994 ON ra.contextid=ctx.id
3999 // Default 'locality' policy -- read PHPDoc notes
4000 // about sort policies...
4001 $orderby = 'ORDER BY '
4002 .'ctx.depth DESC, ' /* locality wins */
4003 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
4004 .'ra.id'; /* role assignment order tie-breaker */
4005 if ($sortpolicy === 'sortorder') {
4006 $orderby = 'ORDER BY '
4007 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
4008 .'ra.id'; /* role assignment order tie-breaker */
4011 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
4012 $sortedusers = array();
4015 foreach ($sortedids as $id) {
4017 if (isset($seen[$id])) {
4023 $sortedusers[$id] = $users[$id];
4025 return $sortedusers;
4029 * Gets all the users assigned this role in this context or higher
4031 * @param int $roleid (can also be an array of ints!)
4032 * @param context $context
4033 * @param bool $parent if true, get list of users assigned in higher context too
4034 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
4035 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
4036 * null => use default sort from users_order_by_sql.
4037 * @param bool $all true means all, false means limit to enrolled users
4038 * @param string $group defaults to ''
4039 * @param mixed $limitfrom defaults to ''
4040 * @param mixed $limitnum defaults to ''
4041 * @param string $extrawheretest defaults to ''
4042 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
4045 function get_role_users($roleid, context
$context, $parent = false, $fields = '',
4046 $sort = null, $all = true, $group = '',
4047 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
4050 if (empty($fields)) {
4051 $allnames = get_all_user_name_fields(true, 'u');
4052 $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
4053 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
4054 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4055 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
4056 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
4059 $parentcontexts = '';
4061 $parentcontexts = substr($context->path
, 1); // kill leading slash
4062 $parentcontexts = str_replace('/', ',', $parentcontexts);
4063 if ($parentcontexts !== '') {
4064 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4069 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED
, 'r');
4070 $roleselect = "AND ra.roleid $rids";
4076 if ($coursecontext = $context->get_course_context(false)) {
4077 $params['coursecontext'] = $coursecontext->id
;
4079 $params['coursecontext'] = 0;
4083 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
4084 $groupselect = " AND gm.groupid = :groupid ";
4085 $params['groupid'] = $group;
4091 $params['contextid'] = $context->id
;
4093 if ($extrawheretest) {
4094 $extrawheretest = ' AND ' . $extrawheretest;
4097 if ($whereorsortparams) {
4098 $params = array_merge($params, $whereorsortparams);
4102 list($sort, $sortparams) = users_order_by_sql('u');
4103 $params = array_merge($params, $sortparams);
4106 if ($all === null) {
4107 // Previously null was used to indicate that parameter was not used.
4110 if (!$all and $coursecontext) {
4111 // Do not use get_enrolled_sql() here for performance reasons.
4112 $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
4113 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
4114 $params['ecourseid'] = $coursecontext->instanceid
;
4119 $sql = "SELECT DISTINCT $fields, ra.roleid
4120 FROM {role_assignments} ra
4121 JOIN {user} u ON u.id = ra.userid
4122 JOIN {role} r ON ra.roleid = r.id
4124 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
4126 WHERE (ra.contextid = :contextid $parentcontexts)
4130 ORDER BY $sort"; // join now so that we can just use fullname() later
4132 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
4136 * Counts all the users assigned this role in this context or higher
4138 * @param int|array $roleid either int or an array of ints
4139 * @param context $context
4140 * @param bool $parent if true, get list of users assigned in higher context too
4141 * @return int Returns the result count
4143 function count_role_users($roleid, context
$context, $parent = false) {
4147 if ($contexts = $context->get_parent_context_ids()) {
4148 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4150 $parentcontexts = '';
4153 $parentcontexts = '';
4157 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM
);
4158 $roleselect = "AND r.roleid $rids";
4164 array_unshift($params, $context->id
);
4166 $sql = "SELECT COUNT(u.id)
4167 FROM {role_assignments} r
4168 JOIN {user} u ON u.id = r.userid
4169 WHERE (r.contextid = ? $parentcontexts)
4173 return $DB->count_records_sql($sql, $params);
4177 * This function gets the list of courses that this user has a particular capability in.
4178 * It is still not very efficient.
4180 * @param string $capability Capability in question
4181 * @param int $userid User ID or null for current user
4182 * @param bool $doanything True if 'doanything' is permitted (default)
4183 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4184 * otherwise use a comma-separated list of the fields you require, not including id
4185 * @param string $orderby If set, use a comma-separated list of fields from course
4186 * table with sql modifiers (DESC) if needed
4187 * @return array Array of courses, may have zero entries. Or false if query failed.
4189 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
4192 // Convert fields list and ordering
4194 if ($fieldsexceptid) {
4195 $fields = explode(',', $fieldsexceptid);
4196 foreach($fields as $field) {
4197 $fieldlist .= ',c.'.$field;
4201 $fields = explode(',', $orderby);
4203 foreach($fields as $field) {
4207 $orderby .= 'c.'.$field;
4209 $orderby = 'ORDER BY '.$orderby;
4212 // Obtain a list of everything relevant about all courses including context.
4213 // Note the result can be used directly as a context (we are going to), the course
4214 // fields are just appended.
4216 $contextpreload = context_helper
::get_preload_record_columns_sql('x');
4219 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
4221 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE
.")
4223 // Check capability for each course in turn
4224 foreach ($rs as $course) {
4225 context_helper
::preload_from_record($course);
4226 $context = context_course
::instance($course->id
);
4227 if (has_capability($capability, $context, $userid, $doanything)) {
4228 // We've got the capability. Make the record look like a course record
4230 $courses[] = $course;
4234 return empty($courses) ?
false : $courses;
4238 * This function finds the roles assigned directly to this context only
4239 * i.e. no roles in parent contexts
4241 * @param context $context
4244 function get_roles_on_exact_context(context
$context) {
4247 return $DB->get_records_sql("SELECT r.*
4248 FROM {role_assignments} ra, {role} r
4249 WHERE ra.roleid = r.id AND ra.contextid = ?",
4250 array($context->id
));
4254 * Switches the current user to another role for the current session and only
4255 * in the given context.
4257 * The caller *must* check
4258 * - that this op is allowed
4259 * - that the requested role can be switched to in this context (use get_switchable_roles)
4260 * - that the requested role is NOT $CFG->defaultuserroleid
4262 * To "unswitch" pass 0 as the roleid.
4264 * This function *will* modify $USER->access - beware
4266 * @param integer $roleid the role to switch to.
4267 * @param context $context the context in which to perform the switch.
4268 * @return bool success or failure.
4270 function role_switch($roleid, context
$context) {
4276 // - Add the ghost RA to $USER->access
4277 // as $USER->access['rsw'][$path] = $roleid
4279 // - Make sure $USER->access['rdef'] has the roledefs
4280 // it needs to honour the switcherole
4282 // Roledefs will get loaded "deep" here - down to the last child
4283 // context. Note that
4285 // - When visiting subcontexts, our selective accessdata loading
4286 // will still work fine - though those ra/rdefs will be ignored
4287 // appropriately while the switch is in place
4289 // - If a switcherole happens at a category with tons of courses
4290 // (that have many overrides for switched-to role), the session
4291 // will get... quite large. Sometimes you just can't win.
4293 // To un-switch just unset($USER->access['rsw'][$path])
4295 // Note: it is not possible to switch to roles that do not have course:view
4297 if (!isset($USER->access
)) {
4298 load_all_capabilities();
4302 // Add the switch RA
4304 unset($USER->access
['rsw'][$context->path
]);
4308 $USER->access
['rsw'][$context->path
] = $roleid;
4311 load_role_access_by_context($roleid, $context, $USER->access
);
4317 * Checks if the user has switched roles within the given course.
4319 * Note: You can only switch roles within the course, hence it takes a course id
4320 * rather than a context. On that note Petr volunteered to implement this across
4321 * all other contexts, all requests for this should be forwarded to him ;)
4323 * @param int $courseid The id of the course to check
4324 * @return bool True if the user has switched roles within the course.
4326 function is_role_switched($courseid) {
4328 $context = context_course
::instance($courseid, MUST_EXIST
);
4329 return (!empty($USER->access
['rsw'][$context->path
]));
4333 * Get any role that has an override on exact context
4335 * @param context $context The context to check
4336 * @return array An array of roles
4338 function get_roles_with_override_on_context(context
$context) {
4341 return $DB->get_records_sql("SELECT r.*
4342 FROM {role_capabilities} rc, {role} r
4343 WHERE rc.roleid = r.id AND rc.contextid = ?",
4344 array($context->id
));
4348 * Get all capabilities for this role on this context (overrides)
4350 * @param stdClass $role
4351 * @param context $context
4354 function get_capabilities_from_role_on_context($role, context
$context) {
4357 return $DB->get_records_sql("SELECT *
4358 FROM {role_capabilities}
4359 WHERE contextid = ? AND roleid = ?",
4360 array($context->id
, $role->id
));
4364 * Find out which roles has assignment on this context
4366 * @param context $context
4370 function get_roles_with_assignment_on_context(context
$context) {
4373 return $DB->get_records_sql("SELECT r.*
4374 FROM {role_assignments} ra, {role} r
4375 WHERE ra.roleid = r.id AND ra.contextid = ?",
4376 array($context->id
));
4380 * Find all user assignment of users for this role, on this context
4382 * @param stdClass $role
4383 * @param context $context
4386 function get_users_from_role_on_context($role, context
$context) {
4389 return $DB->get_records_sql("SELECT *
4390 FROM {role_assignments}
4391 WHERE contextid = ? AND roleid = ?",
4392 array($context->id
, $role->id
));
4396 * Simple function returning a boolean true if user has roles
4397 * in context or parent contexts, otherwise false.
4399 * @param int $userid
4400 * @param int $roleid
4401 * @param int $contextid empty means any context
4404 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4408 if (!$context = context
::instance_by_id($contextid, IGNORE_MISSING
)) {
4411 $parents = $context->get_parent_context_ids(true);
4412 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED
, 'r');
4413 $params['userid'] = $userid;
4414 $params['roleid'] = $roleid;
4416 $sql = "SELECT COUNT(ra.id)
4417 FROM {role_assignments} ra
4418 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4420 $count = $DB->get_field_sql($sql, $params);
4421 return ($count > 0);
4424 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4429 * Get localised role name or alias if exists and format the text.
4431 * @param stdClass $role role object
4432 * - optional 'coursealias' property should be included for performance reasons if course context used
4433 * - description property is not required here
4434 * @param context|bool $context empty means system context
4435 * @param int $rolenamedisplay type of role name
4436 * @return string localised role name or course role name alias
4438 function role_get_name(stdClass
$role, $context = null, $rolenamedisplay = ROLENAME_ALIAS
) {
4441 if ($rolenamedisplay == ROLENAME_SHORT
) {
4442 return $role->shortname
;
4445 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4446 $coursecontext = null;
4449 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS
or $rolenamedisplay == ROLENAME_BOTH
or $rolenamedisplay == ROLENAME_ALIAS_RAW
)) {
4450 $role = clone($role); // Do not modify parameters.
4451 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id
, 'contextid'=>$coursecontext->id
))) {
4452 $role->coursealias
= $r->name
;
4454 $role->coursealias
= null;
4458 if ($rolenamedisplay == ROLENAME_ALIAS_RAW
) {
4459 if ($coursecontext) {
4460 return $role->coursealias
;
4466 if (trim($role->name
) !== '') {
4467 // For filtering always use context where was the thing defined - system for roles here.
4468 $original = format_string($role->name
, true, array('context'=>context_system
::instance()));
4471 // Empty role->name means we want to see localised role name based on shortname,
4472 // only default roles are supposed to be localised.
4473 switch ($role->shortname
) {
4474 case 'manager': $original = get_string('manager', 'role'); break;
4475 case 'coursecreator': $original = get_string('coursecreators'); break;
4476 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4477 case 'teacher': $original = get_string('noneditingteacher'); break;
4478 case 'student': $original = get_string('defaultcoursestudent'); break;
4479 case 'guest': $original = get_string('guest'); break;
4480 case 'user': $original = get_string('authenticateduser'); break;
4481 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4482 // We should not get here, the role UI should require the name for custom roles!
4483 default: $original = $role->shortname
; break;
4487 if ($rolenamedisplay == ROLENAME_ORIGINAL
) {
4491 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT
) {
4492 return "$original ($role->shortname)";
4495 if ($rolenamedisplay == ROLENAME_ALIAS
) {
4496 if ($coursecontext and trim($role->coursealias
) !== '') {
4497 return format_string($role->coursealias
, true, array('context'=>$coursecontext));
4503 if ($rolenamedisplay == ROLENAME_BOTH
) {
4504 if ($coursecontext and trim($role->coursealias
) !== '') {
4505 return format_string($role->coursealias
, true, array('context'=>$coursecontext)) . " ($original)";
4511 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4515 * Returns localised role description if available.
4516 * If the name is empty it tries to find the default role name using
4517 * hardcoded list of default role names or other methods in the future.
4519 * @param stdClass $role
4520 * @return string localised role name
4522 function role_get_description(stdClass
$role) {
4523 if (!html_is_blank($role->description
)) {
4524 return format_text($role->description
, FORMAT_HTML
, array('context'=>context_system
::instance()));
4527 switch ($role->shortname
) {
4528 case 'manager': return get_string('managerdescription', 'role');
4529 case 'coursecreator': return get_string('coursecreatorsdescription');
4530 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4531 case 'teacher': return get_string('noneditingteacherdescription');
4532 case 'student': return get_string('defaultcoursestudentdescription');
4533 case 'guest': return get_string('guestdescription');
4534 case 'user': return get_string('authenticateduserdescription');
4535 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4541 * Get all the localised role names for a context.
4543 * In new installs default roles have empty names, this function
4544 * add localised role names using current language pack.
4546 * @param context $context the context, null means system context
4547 * @param array of role objects with a ->localname field containing the context-specific role name.
4548 * @param int $rolenamedisplay
4549 * @param bool $returnmenu true means id=>localname, false means id=>rolerecord
4550 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4552 function role_get_names(context
$context = null, $rolenamedisplay = ROLENAME_ALIAS
, $returnmenu = null) {
4553 return role_fix_names(get_all_roles($context), $context, $rolenamedisplay, $returnmenu);
4557 * Prepare list of roles for display, apply aliases and localise default role names.
4559 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4560 * @param context $context the context, null means system context
4561 * @param int $rolenamedisplay
4562 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4563 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4565 function role_fix_names($roleoptions, context
$context = null, $rolenamedisplay = ROLENAME_ALIAS
, $returnmenu = null) {
4568 if (empty($roleoptions)) {
4572 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4573 $coursecontext = null;
4576 // We usually need all role columns...
4577 $first = reset($roleoptions);
4578 if ($returnmenu === null) {
4579 $returnmenu = !is_object($first);
4582 if (!is_object($first) or !property_exists($first, 'shortname')) {
4583 $allroles = get_all_roles($context);
4584 foreach ($roleoptions as $rid => $unused) {
4585 $roleoptions[$rid] = $allroles[$rid];
4589 // Inject coursealias if necessary.
4590 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW
or $rolenamedisplay == ROLENAME_ALIAS
or $rolenamedisplay == ROLENAME_BOTH
)) {
4591 $first = reset($roleoptions);
4592 if (!property_exists($first, 'coursealias')) {
4593 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id
));
4594 foreach ($aliasnames as $alias) {
4595 if (isset($roleoptions[$alias->roleid
])) {
4596 $roleoptions[$alias->roleid
]->coursealias
= $alias->name
;
4602 // Add localname property.
4603 foreach ($roleoptions as $rid => $role) {
4604 $roleoptions[$rid]->localname
= role_get_name($role, $coursecontext, $rolenamedisplay);
4608 return $roleoptions;
4612 foreach ($roleoptions as $rid => $role) {
4613 $menu[$rid] = $role->localname
;
4620 * Aids in detecting if a new line is required when reading a new capability
4622 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4623 * when we read in a new capability.
4624 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4625 * but when we are in grade, all reports/import/export capabilities should be together
4627 * @param string $cap component string a
4628 * @param string $comp component string b
4629 * @param int $contextlevel
4630 * @return bool whether 2 component are in different "sections"
4632 function component_level_changed($cap, $comp, $contextlevel) {
4634 if (strstr($cap->component
, '/') && strstr($comp, '/')) {
4635 $compsa = explode('/', $cap->component
);
4636 $compsb = explode('/', $comp);
4638 // list of system reports
4639 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4643 // we are in gradebook, still
4644 if (($compsa[0] == 'gradeexport' ||
$compsa[0] == 'gradeimport' ||
$compsa[0] == 'gradereport') &&
4645 ($compsb[0] == 'gradeexport' ||
$compsb[0] == 'gradeimport' ||
$compsb[0] == 'gradereport')) {
4649 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4654 return ($cap->component
!= $comp ||
$cap->contextlevel
!= $contextlevel);
4658 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4659 * and return an array of roleids in order.
4661 * @param array $allroles array of roles, as returned by get_all_roles();
4662 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4664 function fix_role_sortorder($allroles) {
4667 $rolesort = array();
4669 foreach ($allroles as $role) {
4670 $rolesort[$i] = $role->id
;
4671 if ($role->sortorder
!= $i) {
4672 $r = new stdClass();
4675 $DB->update_record('role', $r);
4676 $allroles[$role->id
]->sortorder
= $i;
4684 * Switch the sort order of two roles (used in admin/roles/manage.php).
4686 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4687 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4688 * @return boolean success or failure
4690 function switch_roles($first, $second) {
4692 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4693 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder
));
4694 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder
, array('sortorder' => $second->sortorder
));
4695 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder
, array('sortorder' => $temp));
4700 * Duplicates all the base definitions of a role
4702 * @param stdClass $sourcerole role to copy from
4703 * @param int $targetrole id of role to copy to
4705 function role_cap_duplicate($sourcerole, $targetrole) {
4708 $systemcontext = context_system
::instance();
4709 $caps = $DB->get_records_sql("SELECT *
4710 FROM {role_capabilities}
4711 WHERE roleid = ? AND contextid = ?",
4712 array($sourcerole->id
, $systemcontext->id
));
4713 // adding capabilities
4714 foreach ($caps as $cap) {
4716 $cap->roleid
= $targetrole;
4717 $DB->insert_record('role_capabilities', $cap);
4722 * Returns two lists, this can be used to find out if user has capability.
4723 * Having any needed role and no forbidden role in this context means
4724 * user has this capability in this context.
4725 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4727 * @param stdClass $context
4728 * @param string $capability
4729 * @return array($neededroles, $forbiddenroles)
4731 function get_roles_with_cap_in_context($context, $capability) {
4734 $ctxids = trim($context->path
, '/'); // kill leading slash
4735 $ctxids = str_replace('/', ',', $ctxids);
4737 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4738 FROM {role_capabilities} rc
4739 JOIN {context} ctx ON ctx.id = rc.contextid
4740 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4741 ORDER BY rc.roleid ASC, ctx.depth DESC";
4742 $params = array('cap'=>$capability);
4744 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4745 // no cap definitions --> no capability
4746 return array(array(), array());
4749 $forbidden = array();
4751 foreach($capdefs as $def) {
4752 if (isset($forbidden[$def->roleid
])) {
4755 if ($def->permission
== CAP_PROHIBIT
) {
4756 $forbidden[$def->roleid
] = $def->roleid
;
4757 unset($needed[$def->roleid
]);
4760 if (!isset($needed[$def->roleid
])) {
4761 if ($def->permission
== CAP_ALLOW
) {
4762 $needed[$def->roleid
] = true;
4763 } else if ($def->permission
== CAP_PREVENT
) {
4764 $needed[$def->roleid
] = false;
4770 // remove all those roles not allowing
4771 foreach($needed as $key=>$value) {
4773 unset($needed[$key]);
4775 $needed[$key] = $key;
4779 return array($needed, $forbidden);
4783 * Returns an array of role IDs that have ALL of the the supplied capabilities
4784 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4786 * @param stdClass $context
4787 * @param array $capabilities An array of capabilities
4788 * @return array of roles with all of the required capabilities
4790 function get_roles_with_caps_in_context($context, $capabilities) {
4791 $neededarr = array();
4792 $forbiddenarr = array();
4793 foreach($capabilities as $caprequired) {
4794 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4797 $rolesthatcanrate = array();
4798 if (!empty($neededarr)) {
4799 foreach ($neededarr as $needed) {
4800 if (empty($rolesthatcanrate)) {
4801 $rolesthatcanrate = $needed;
4803 //only want roles that have all caps
4804 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4808 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4809 foreach ($forbiddenarr as $forbidden) {
4810 //remove any roles that are forbidden any of the caps
4811 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4814 return $rolesthatcanrate;
4818 * Returns an array of role names that have ALL of the the supplied capabilities
4819 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4821 * @param stdClass $context
4822 * @param array $capabilities An array of capabilities
4823 * @return array of roles with all of the required capabilities
4825 function get_role_names_with_caps_in_context($context, $capabilities) {
4828 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4829 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4832 foreach ($rolesthatcanrate as $r) {
4833 $roles[$r] = $allroles[$r];
4836 return role_fix_names($roles, $context, ROLENAME_ALIAS
, true);
4840 * This function verifies the prohibit comes from this context
4841 * and there are no more prohibits in parent contexts.
4843 * @param int $roleid
4844 * @param context $context
4845 * @param string $capability name
4848 function prohibit_is_removable($roleid, context
$context, $capability) {
4851 $ctxids = trim($context->path
, '/'); // kill leading slash
4852 $ctxids = str_replace('/', ',', $ctxids);
4854 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT
);
4856 $sql = "SELECT ctx.id
4857 FROM {role_capabilities} rc
4858 JOIN {context} ctx ON ctx.id = rc.contextid
4859 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4860 ORDER BY ctx.depth DESC";
4862 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4863 // no prohibits == nothing to remove
4867 if (count($prohibits) > 1) {
4868 // more prohibits can not be removed
4872 return !empty($prohibits[$context->id
]);
4876 * More user friendly role permission changing,
4877 * it should produce as few overrides as possible.
4879 * @param int $roleid
4880 * @param stdClass $context
4881 * @param string $capname capability name
4882 * @param int $permission
4885 function role_change_permission($roleid, $context, $capname, $permission) {
4888 if ($permission == CAP_INHERIT
) {
4889 unassign_capability($capname, $roleid, $context->id
);
4890 $context->mark_dirty();
4894 $ctxids = trim($context->path
, '/'); // kill leading slash
4895 $ctxids = str_replace('/', ',', $ctxids);
4897 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4899 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4900 FROM {role_capabilities} rc
4901 JOIN {context} ctx ON ctx.id = rc.contextid
4902 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4903 ORDER BY ctx.depth DESC";
4905 if ($existing = $DB->get_records_sql($sql, $params)) {
4906 foreach($existing as $e) {
4907 if ($e->permission
== CAP_PROHIBIT
) {
4908 // prohibit can not be overridden, no point in changing anything
4912 $lowest = array_shift($existing);
4913 if ($lowest->permission
== $permission) {
4914 // permission already set in this context or parent - nothing to do
4918 $parent = array_shift($existing);
4919 if ($parent->permission
== $permission) {
4920 // permission already set in parent context or parent - just unset in this context
4921 // we do this because we want as few overrides as possible for performance reasons
4922 unassign_capability($capname, $roleid, $context->id
);
4923 $context->mark_dirty();
4929 if ($permission == CAP_PREVENT
) {
4930 // nothing means role does not have permission
4935 // assign the needed capability
4936 assign_capability($capname, $permission, $roleid, $context->id
, true);
4938 // force cap reloading
4939 $context->mark_dirty();
4944 * Basic moodle context abstraction class.
4946 * Google confirms that no other important framework is using "context" class,
4947 * we could use something else like mcontext or moodle_context, but we need to type
4948 * this very often which would be annoying and it would take too much space...
4950 * This class is derived from stdClass for backwards compatibility with
4951 * odl $context record that was returned from DML $DB->get_record()
4953 * @package core_access
4955 * @copyright Petr Skoda {@link http://skodak.org}
4956 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4959 * @property-read int $id context id
4960 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4961 * @property-read int $instanceid id of related instance in each context
4962 * @property-read string $path path to context, starts with system context
4963 * @property-read int $depth
4965 abstract class context
extends stdClass
implements IteratorAggregate
{
4969 * Can be accessed publicly through $context->id
4976 * Can be accessed publicly through $context->contextlevel
4977 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4979 protected $_contextlevel;
4982 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4983 * Can be accessed publicly through $context->instanceid
4986 protected $_instanceid;
4989 * The path to the context always starting from the system context
4990 * Can be accessed publicly through $context->path
4996 * The depth of the context in relation to parent contexts
4997 * Can be accessed publicly through $context->depth
5003 * @var array Context caching info
5005 private static $cache_contextsbyid = array();
5008 * @var array Context caching info
5010 private static $cache_contexts = array();
5014 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
5017 protected static $cache_count = 0;
5020 * @var array Context caching info
5022 protected static $cache_preloaded = array();
5025 * @var context_system The system context once initialised
5027 protected static $systemcontext = null;
5030 * Resets the cache to remove all data.
5033 protected static function reset_caches() {
5034 self
::$cache_contextsbyid = array();
5035 self
::$cache_contexts = array();
5036 self
::$cache_count = 0;
5037 self
::$cache_preloaded = array();
5039 self
::$systemcontext = null;
5043 * Adds a context to the cache. If the cache is full, discards a batch of
5047 * @param context $context New context to add
5050 protected static function cache_add(context
$context) {
5051 if (isset(self
::$cache_contextsbyid[$context->id
])) {
5052 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5056 if (self
::$cache_count >= CONTEXT_CACHE_MAX_SIZE
) {
5058 foreach(self
::$cache_contextsbyid as $ctx) {
5061 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
5064 if ($i > (CONTEXT_CACHE_MAX_SIZE
/ 3)) {
5065 // we remove oldest third of the contexts to make room for more contexts
5068 unset(self
::$cache_contextsbyid[$ctx->id
]);
5069 unset(self
::$cache_contexts[$ctx->contextlevel
][$ctx->instanceid
]);
5070 self
::$cache_count--;
5074 self
::$cache_contexts[$context->contextlevel
][$context->instanceid
] = $context;
5075 self
::$cache_contextsbyid[$context->id
] = $context;
5076 self
::$cache_count++
;
5080 * Removes a context from the cache.
5083 * @param context $context Context object to remove
5086 protected static function cache_remove(context
$context) {
5087 if (!isset(self
::$cache_contextsbyid[$context->id
])) {
5088 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
5091 unset(self
::$cache_contexts[$context->contextlevel
][$context->instanceid
]);
5092 unset(self
::$cache_contextsbyid[$context->id
]);
5094 self
::$cache_count--;
5096 if (self
::$cache_count < 0) {
5097 self
::$cache_count = 0;
5102 * Gets a context from the cache.
5105 * @param int $contextlevel Context level
5106 * @param int $instance Instance ID
5107 * @return context|bool Context or false if not in cache
5109 protected static function cache_get($contextlevel, $instance) {
5110 if (isset(self
::$cache_contexts[$contextlevel][$instance])) {
5111 return self
::$cache_contexts[$contextlevel][$instance];
5117 * Gets a context from the cache based on its id.
5120 * @param int $id Context ID
5121 * @return context|bool Context or false if not in cache
5123 protected static function cache_get_by_id($id) {
5124 if (isset(self
::$cache_contextsbyid[$id])) {
5125 return self
::$cache_contextsbyid[$id];
5131 * Preloads context information from db record and strips the cached info.
5134 * @param stdClass $rec
5135 * @return void (modifies $rec)
5137 protected static function preload_from_record(stdClass
$rec) {
5138 if (empty($rec->ctxid
) or empty($rec->ctxlevel
) or empty($rec->ctxinstance
) or empty($rec->ctxpath
) or empty($rec->ctxdepth
)) {
5139 // $rec does not have enough data, passed here repeatedly or context does not exist yet
5143 // note: in PHP5 the objects are passed by reference, no need to return $rec
5144 $record = new stdClass();
5145 $record->id
= $rec->ctxid
; unset($rec->ctxid
);
5146 $record->contextlevel
= $rec->ctxlevel
; unset($rec->ctxlevel
);
5147 $record->instanceid
= $rec->ctxinstance
; unset($rec->ctxinstance
);
5148 $record->path
= $rec->ctxpath
; unset($rec->ctxpath
);
5149 $record->depth
= $rec->ctxdepth
; unset($rec->ctxdepth
);
5151 return context
::create_instance_from_record($record);
5155 // ====== magic methods =======
5158 * Magic setter method, we do not want anybody to modify properties from the outside
5159 * @param string $name
5160 * @param mixed $value
5162 public function __set($name, $value) {
5163 debugging('Can not change context instance properties!');
5167 * Magic method getter, redirects to read only values.
5168 * @param string $name
5171 public function __get($name) {
5173 case 'id': return $this->_id
;
5174 case 'contextlevel': return $this->_contextlevel
;
5175 case 'instanceid': return $this->_instanceid
;
5176 case 'path': return $this->_path
;
5177 case 'depth': return $this->_depth
;
5180 debugging('Invalid context property accessed! '.$name);
5186 * Full support for isset on our magic read only properties.
5187 * @param string $name
5190 public function __isset($name) {
5192 case 'id': return isset($this->_id
);
5193 case 'contextlevel': return isset($this->_contextlevel
);
5194 case 'instanceid': return isset($this->_instanceid
);
5195 case 'path': return isset($this->_path
);
5196 case 'depth': return isset($this->_depth
);
5198 default: return false;
5204 * ALl properties are read only, sorry.
5205 * @param string $name
5207 public function __unset($name) {
5208 debugging('Can not unset context instance properties!');
5211 // ====== implementing method from interface IteratorAggregate ======
5214 * Create an iterator because magic vars can't be seen by 'foreach'.
5216 * Now we can convert context object to array using convert_to_array(),
5217 * and feed it properly to json_encode().
5219 public function getIterator() {
5222 'contextlevel' => $this->contextlevel
,
5223 'instanceid' => $this->instanceid
,
5224 'path' => $this->path
,
5225 'depth' => $this->depth
5227 return new ArrayIterator($ret);
5230 // ====== general context methods ======
5233 * Constructor is protected so that devs are forced to
5234 * use context_xxx::instance() or context::instance_by_id().
5236 * @param stdClass $record
5238 protected function __construct(stdClass
$record) {
5239 $this->_id
= $record->id
;
5240 $this->_contextlevel
= (int)$record->contextlevel
;
5241 $this->_instanceid
= $record->instanceid
;
5242 $this->_path
= $record->path
;
5243 $this->_depth
= $record->depth
;
5247 * This function is also used to work around 'protected' keyword problems in context_helper.
5249 * @param stdClass $record
5250 * @return context instance
5252 protected static function create_instance_from_record(stdClass
$record) {
5253 $classname = context_helper
::get_class_for_level($record->contextlevel
);
5255 if ($context = context
::cache_get_by_id($record->id
)) {
5259 $context = new $classname($record);
5260 context
::cache_add($context);
5266 * Copy prepared new contexts from temp table to context table,
5267 * we do this in db specific way for perf reasons only.
5270 protected static function merge_context_temp_table() {
5274 * - mysql does not allow to use FROM in UPDATE statements
5275 * - using two tables after UPDATE works in mysql, but might give unexpected
5276 * results in pg 8 (depends on configuration)
5277 * - using table alias in UPDATE does not work in pg < 8.2
5279 * Different code for each database - mostly for performance reasons
5282 $dbfamily = $DB->get_dbfamily();
5283 if ($dbfamily == 'mysql') {
5284 $updatesql = "UPDATE {context} ct, {context_temp} temp
5285 SET ct.path = temp.path,
5286 ct.depth = temp.depth
5287 WHERE ct.id = temp.id";
5288 } else if ($dbfamily == 'oracle') {
5289 $updatesql = "UPDATE {context} ct
5290 SET (ct.path, ct.depth) =
5291 (SELECT temp.path, temp.depth
5292 FROM {context_temp} temp
5293 WHERE temp.id=ct.id)
5294 WHERE EXISTS (SELECT 'x'
5295 FROM {context_temp} temp
5296 WHERE temp.id = ct.id)";
5297 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5298 $updatesql = "UPDATE {context}
5299 SET path = temp.path,
5301 FROM {context_temp} temp
5302 WHERE temp.id={context}.id";
5304 // sqlite and others
5305 $updatesql = "UPDATE {context}
5306 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5307 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5308 WHERE id IN (SELECT id FROM {context_temp})";
5311 $DB->execute($updatesql);
5315 * Get a context instance as an object, from a given context id.
5318 * @param int $id context id
5319 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5320 * MUST_EXIST means throw exception if no record found
5321 * @return context|bool the context object or false if not found
5323 public static function instance_by_id($id, $strictness = MUST_EXIST
) {
5326 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5327 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5328 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5331 if ($id == SYSCONTEXTID
) {
5332 return context_system
::instance(0, $strictness);
5335 if (is_array($id) or is_object($id) or empty($id)) {
5336 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5339 if ($context = context
::cache_get_by_id($id)) {
5343 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5344 return context
::create_instance_from_record($record);
5351 * Update context info after moving context in the tree structure.
5353 * @param context $newparent
5356 public function update_moved(context
$newparent) {
5359 $frompath = $this->_path
;
5360 $newpath = $newparent->path
. '/' . $this->_id
;
5362 $trans = $DB->start_delegated_transaction();
5364 $this->mark_dirty();
5367 if (($newparent->depth +
1) != $this->_depth
) {
5368 $diff = $newparent->depth
- $this->_depth +
1;
5369 $setdepth = ", depth = depth + $diff";
5371 $sql = "UPDATE {context}
5375 $params = array($newpath, $this->_id
);
5376 $DB->execute($sql, $params);
5378 $this->_path
= $newpath;
5379 $this->_depth
= $newparent->depth +
1;
5381 $sql = "UPDATE {context}
5382 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+
1))."
5385 $params = array($newpath, "{$frompath}/%");
5386 $DB->execute($sql, $params);
5388 $this->mark_dirty();
5390 context
::reset_caches();
5392 $trans->allow_commit();
5396 * Remove all context path info and optionally rebuild it.
5398 * @param bool $rebuild
5401 public function reset_paths($rebuild = true) {
5405 $this->mark_dirty();
5407 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5408 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5409 if ($this->_contextlevel
!= CONTEXT_SYSTEM
) {
5410 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id
));
5411 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id
));
5413 $this->_path
= null;
5417 context_helper
::build_all_paths(false);
5420 context
::reset_caches();
5424 * Delete all data linked to content, do not delete the context record itself
5426 public function delete_content() {
5429 blocks_delete_all_for_context($this->_id
);
5430 filter_delete_all_for_context($this->_id
);
5432 require_once($CFG->dirroot
. '/comment/lib.php');
5433 comment
::delete_comments(array('contextid'=>$this->_id
));
5435 require_once($CFG->dirroot
.'/rating/lib.php');
5436 $delopt = new stdclass();
5437 $delopt->contextid
= $this->_id
;
5438 $rm = new rating_manager();
5439 $rm->delete_ratings($delopt);
5441 // delete all files attached to this context
5442 $fs = get_file_storage();
5443 $fs->delete_area_files($this->_id
);
5445 // Delete all repository instances attached to this context.
5446 require_once($CFG->dirroot
. '/repository/lib.php');
5447 repository
::delete_all_for_context($this->_id
);
5449 // delete all advanced grading data attached to this context
5450 require_once($CFG->dirroot
.'/grade/grading/lib.php');
5451 grading_manager
::delete_all_for_context($this->_id
);
5453 // now delete stuff from role related tables, role_unassign_all
5454 // and unenrol should be called earlier to do proper cleanup
5455 $DB->delete_records('role_assignments', array('contextid'=>$this->_id
));
5456 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id
));
5457 $DB->delete_records('role_names', array('contextid'=>$this->_id
));
5461 * Delete the context content and the context record itself
5463 public function delete() {
5466 // double check the context still exists
5467 if (!$DB->record_exists('context', array('id'=>$this->_id
))) {
5468 context
::cache_remove($this);
5472 $this->delete_content();
5473 $DB->delete_records('context', array('id'=>$this->_id
));
5474 // purge static context cache if entry present
5475 context
::cache_remove($this);
5477 // do not mark dirty contexts if parents unknown
5478 if (!is_null($this->_path
) and $this->_depth
> 0) {
5479 $this->mark_dirty();
5483 // ====== context level related methods ======
5486 * Utility method for context creation
5489 * @param int $contextlevel
5490 * @param int $instanceid
5491 * @param string $parentpath
5492 * @return stdClass context record
5494 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5497 $record = new stdClass();
5498 $record->contextlevel
= $contextlevel;
5499 $record->instanceid
= $instanceid;
5501 $record->path
= null; //not known before insert
5503 $record->id
= $DB->insert_record('context', $record);
5505 // now add path if known - it can be added later
5506 if (!is_null($parentpath)) {
5507 $record->path
= $parentpath.'/'.$record->id
;
5508 $record->depth
= substr_count($record->path
, '/');
5509 $DB->update_record('context', $record);
5516 * Returns human readable context identifier.
5518 * @param boolean $withprefix whether to prefix the name of the context with the
5519 * type of context, e.g. User, Course, Forum, etc.
5520 * @param boolean $short whether to use the short name of the thing. Only applies
5521 * to course contexts
5522 * @return string the human readable context name.
5524 public function get_context_name($withprefix = true, $short = false) {
5525 // must be implemented in all context levels
5526 throw new coding_exception('can not get name of abstract context');
5530 * Returns the most relevant URL for this context.
5532 * @return moodle_url
5534 public abstract function get_url();
5537 * Returns array of relevant context capability records.
5541 public abstract function get_capabilities();
5544 * Recursive function which, given a context, find all its children context ids.
5546 * For course category contexts it will return immediate children and all subcategory contexts.
5547 * It will NOT recurse into courses or subcategories categories.
5548 * If you want to do that, call it on the returned courses/categories.
5550 * When called for a course context, it will return the modules and blocks
5551 * displayed in the course page and blocks displayed on the module pages.
5553 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5556 * @return array Array of child records
5558 public function get_child_contexts() {
5561 $sql = "SELECT ctx.*
5563 WHERE ctx.path LIKE ?";
5564 $params = array($this->_path
.'/%');
5565 $records = $DB->get_records_sql($sql, $params);
5568 foreach ($records as $record) {
5569 $result[$record->id
] = context
::create_instance_from_record($record);
5576 * Returns parent contexts of this context in reversed order, i.e. parent first,
5577 * then grand parent, etc.
5579 * @param bool $includeself tre means include self too
5580 * @return array of context instances
5582 public function get_parent_contexts($includeself = false) {
5583 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5588 foreach ($contextids as $contextid) {
5589 $parent = context
::instance_by_id($contextid, MUST_EXIST
);
5590 $result[$parent->id
] = $parent;
5597 * Returns parent contexts of this context in reversed order, i.e. parent first,
5598 * then grand parent, etc.
5600 * @param bool $includeself tre means include self too
5601 * @return array of context ids
5603 public function get_parent_context_ids($includeself = false) {
5604 if (empty($this->_path
)) {
5608 $parentcontexts = trim($this->_path
, '/'); // kill leading slash
5609 $parentcontexts = explode('/', $parentcontexts);
5610 if (!$includeself) {
5611 array_pop($parentcontexts); // and remove its own id
5614 return array_reverse($parentcontexts);
5618 * Returns parent context
5622 public function get_parent_context() {
5623 if (empty($this->_path
) or $this->_id
== SYSCONTEXTID
) {
5627 $parentcontexts = trim($this->_path
, '/'); // kill leading slash
5628 $parentcontexts = explode('/', $parentcontexts);
5629 array_pop($parentcontexts); // self
5630 $contextid = array_pop($parentcontexts); // immediate parent
5632 return context
::instance_by_id($contextid, MUST_EXIST
);
5636 * Is this context part of any course? If yes return course context.
5638 * @param bool $strict true means throw exception if not found, false means return false if not found
5639 * @return course_context context of the enclosing course, null if not found or exception
5641 public function get_course_context($strict = true) {
5643 throw new coding_exception('Context does not belong to any course.');
5650 * Returns sql necessary for purging of stale context instances.
5653 * @return string cleanup SQL
5655 protected static function get_cleanup_sql() {
5656 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5660 * Rebuild context paths and depths at context level.
5663 * @param bool $force
5666 protected static function build_paths($force) {
5667 throw new coding_exception('build_paths() method must be implemented in all context levels');
5671 * Create missing context instances at given level
5676 protected static function create_level_instances() {
5677 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5681 * Reset all cached permissions and definitions if the necessary.
5684 public function reload_if_dirty() {
5685 global $ACCESSLIB_PRIVATE, $USER;
5687 // Load dirty contexts list if needed
5689 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts
)) {
5690 // we do not load dirty flags in CLI and cron
5691 $ACCESSLIB_PRIVATE->dirtycontexts
= array();
5694 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts
)) {
5695 if (!isset($USER->access
['time'])) {
5696 // nothing was loaded yet, we do not need to check dirty contexts now
5699 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5700 $ACCESSLIB_PRIVATE->dirtycontexts
= get_cache_flags('accesslib/dirtycontexts', $USER->access
['time']-2);
5704 foreach ($ACCESSLIB_PRIVATE->dirtycontexts
as $path=>$unused) {
5705 if ($path === $this->_path
or strpos($this->_path
, $path.'/') === 0) {
5706 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5707 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5708 reload_all_capabilities();
5715 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5717 public function mark_dirty() {
5718 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5720 if (during_initial_install()) {
5724 // only if it is a non-empty string
5725 if (is_string($this->_path
) && $this->_path
!== '') {
5726 set_cache_flag('accesslib/dirtycontexts', $this->_path
, 1, time()+
$CFG->sessiontimeout
);
5727 if (isset($ACCESSLIB_PRIVATE->dirtycontexts
)) {
5728 $ACCESSLIB_PRIVATE->dirtycontexts
[$this->_path
] = 1;
5731 $ACCESSLIB_PRIVATE->dirtycontexts
= array($this->_path
=> 1);
5733 if (isset($USER->access
['time'])) {
5734 $ACCESSLIB_PRIVATE->dirtycontexts
= get_cache_flags('accesslib/dirtycontexts', $USER->access
['time']-2);
5736 $ACCESSLIB_PRIVATE->dirtycontexts
= array($this->_path
=> 1);
5738 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5747 * Context maintenance and helper methods.
5749 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5750 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5751 * level implementation from the rest of code, the code completion returns what developers need.
5753 * Thank you Tim Hunt for helping me with this nasty trick.
5755 * @package core_access
5757 * @copyright Petr Skoda {@link http://skodak.org}
5758 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5761 class context_helper
extends context
{
5764 * @var array An array mapping context levels to classes
5766 private static $alllevels;
5769 * Instance does not make sense here, only static use
5771 protected function __construct() {
5775 * Initialise context levels, call before using self::$alllevels.
5777 private static function init_levels() {
5780 if (isset(self
::$alllevels)) {
5783 self
::$alllevels = array(
5784 CONTEXT_SYSTEM
=> 'context_system',
5785 CONTEXT_USER
=> 'context_user',
5786 CONTEXT_COURSECAT
=> 'context_coursecat',
5787 CONTEXT_COURSE
=> 'context_course',
5788 CONTEXT_MODULE
=> 'context_module',
5789 CONTEXT_BLOCK
=> 'context_block',
5792 if (empty($CFG->custom_context_classes
)) {
5796 // Unsupported custom levels, use with care!!!
5797 foreach ($CFG->custom_context_classes
as $level => $classname) {
5798 self
::$alllevels[$level] = $classname;
5800 ksort(self
::$alllevels);
5804 * Returns a class name of the context level class
5807 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5808 * @return string class name of the context class
5810 public static function get_class_for_level($contextlevel) {
5811 self
::init_levels();
5812 if (isset(self
::$alllevels[$contextlevel])) {
5813 return self
::$alllevels[$contextlevel];
5815 throw new coding_exception('Invalid context level specified');
5820 * Returns a list of all context levels
5823 * @return array int=>string (level=>level class name)
5825 public static function get_all_levels() {
5826 self
::init_levels();
5827 return self
::$alllevels;
5831 * Remove stale contexts that belonged to deleted instances.
5832 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5837 public static function cleanup_instances() {
5839 self
::init_levels();
5842 foreach (self
::$alllevels as $level=>$classname) {
5843 $sqls[] = $classname::get_cleanup_sql();
5846 $sql = implode(" UNION ", $sqls);
5848 // it is probably better to use transactions, it might be faster too
5849 $transaction = $DB->start_delegated_transaction();
5851 $rs = $DB->get_recordset_sql($sql);
5852 foreach ($rs as $record) {
5853 $context = context
::create_instance_from_record($record);
5858 $transaction->allow_commit();
5862 * Create all context instances at the given level and above.
5865 * @param int $contextlevel null means all levels
5866 * @param bool $buildpaths
5869 public static function create_instances($contextlevel = null, $buildpaths = true) {
5870 self
::init_levels();
5871 foreach (self
::$alllevels as $level=>$classname) {
5872 if ($contextlevel and $level > $contextlevel) {
5873 // skip potential sub-contexts
5876 $classname::create_level_instances();
5878 $classname::build_paths(false);
5884 * Rebuild paths and depths in all context levels.
5887 * @param bool $force false means add missing only
5890 public static function build_all_paths($force = false) {
5891 self
::init_levels();
5892 foreach (self
::$alllevels as $classname) {
5893 $classname::build_paths($force);
5896 // reset static course cache - it might have incorrect cached data
5897 accesslib_clear_all_caches(true);
5901 * Resets the cache to remove all data.
5904 public static function reset_caches() {
5905 context
::reset_caches();
5909 * Returns all fields necessary for context preloading from user $rec.
5911 * This helps with performance when dealing with hundreds of contexts.
5914 * @param string $tablealias context table alias in the query
5915 * @return array (table.column=>alias, ...)
5917 public static function get_preload_record_columns($tablealias) {
5918 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5922 * Returns all fields necessary for context preloading from user $rec.
5924 * This helps with performance when dealing with hundreds of contexts.
5927 * @param string $tablealias context table alias in the query
5930 public static function get_preload_record_columns_sql($tablealias) {
5931 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5935 * Preloads context information from db record and strips the cached info.
5937 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5940 * @param stdClass $rec
5941 * @return void (modifies $rec)
5943 public static function preload_from_record(stdClass
$rec) {
5944 context
::preload_from_record($rec);
5948 * Preload all contexts instances from course.
5950 * To be used if you expect multiple queries for course activities...
5953 * @param int $courseid
5955 public static function preload_course($courseid) {
5956 // Users can call this multiple times without doing any harm
5957 if (isset(context
::$cache_preloaded[$courseid])) {
5960 $coursecontext = context_course
::instance($courseid);
5961 $coursecontext->get_child_contexts();
5963 context
::$cache_preloaded[$courseid] = true;
5967 * Delete context instance
5970 * @param int $contextlevel
5971 * @param int $instanceid
5974 public static function delete_instance($contextlevel, $instanceid) {
5977 // double check the context still exists
5978 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5979 $context = context
::create_instance_from_record($record);
5982 // we should try to purge the cache anyway
5987 * Returns the name of specified context level
5990 * @param int $contextlevel
5991 * @return string name of the context level
5993 public static function get_level_name($contextlevel) {
5994 $classname = context_helper
::get_class_for_level($contextlevel);
5995 return $classname::get_level_name();
6001 public function get_url() {
6007 public function get_capabilities() {
6013 * System context class
6015 * @package core_access
6017 * @copyright Petr Skoda {@link http://skodak.org}
6018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6021 class context_system
extends context
{
6023 * Please use context_system::instance() if you need the instance of context.
6025 * @param stdClass $record
6027 protected function __construct(stdClass
$record) {
6028 parent
::__construct($record);
6029 if ($record->contextlevel
!= CONTEXT_SYSTEM
) {
6030 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
6035 * Returns human readable context level name.
6038 * @return string the human readable context level name.
6040 public static function get_level_name() {
6041 return get_string('coresystem');
6045 * Returns human readable context identifier.
6047 * @param boolean $withprefix does not apply to system context
6048 * @param boolean $short does not apply to system context
6049 * @return string the human readable context name.
6051 public function get_context_name($withprefix = true, $short = false) {
6052 return self
::get_level_name();
6056 * Returns the most relevant URL for this context.
6058 * @return moodle_url
6060 public function get_url() {
6061 return new moodle_url('/');
6065 * Returns array of relevant context capability records.
6069 public function get_capabilities() {
6072 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6076 FROM {capabilities}";
6078 return $DB->get_records_sql($sql.' '.$sort, $params);
6082 * Create missing context instances at system context
6085 protected static function create_level_instances() {
6086 // nothing to do here, the system context is created automatically in installer
6091 * Returns system context instance.
6094 * @param int $instanceid
6095 * @param int $strictness
6096 * @param bool $cache
6097 * @return context_system context instance
6099 public static function instance($instanceid = 0, $strictness = MUST_EXIST
, $cache = true) {
6102 if ($instanceid != 0) {
6103 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
6106 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
6107 if (!isset(context
::$systemcontext)) {
6108 $record = new stdClass();
6109 $record->id
= SYSCONTEXTID
;
6110 $record->contextlevel
= CONTEXT_SYSTEM
;
6111 $record->instanceid
= 0;
6112 $record->path
= '/'.SYSCONTEXTID
;
6114 context
::$systemcontext = new context_system($record);
6116 return context
::$systemcontext;
6121 // We ignore the strictness completely because system context must exist except during install.
6122 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM
), '*', MUST_EXIST
);
6123 } catch (dml_exception
$e) {
6124 //table or record does not exist
6125 if (!during_initial_install()) {
6126 // do not mess with system context after install, it simply must exist
6133 $record = new stdClass();
6134 $record->contextlevel
= CONTEXT_SYSTEM
;
6135 $record->instanceid
= 0;
6137 $record->path
= null; //not known before insert
6140 if ($DB->count_records('context')) {
6141 // contexts already exist, this is very weird, system must be first!!!
6144 if (defined('SYSCONTEXTID')) {
6145 // this would happen only in unittest on sites that went through weird 1.7 upgrade
6146 $record->id
= SYSCONTEXTID
;
6147 $DB->import_record('context', $record);
6148 $DB->get_manager()->reset_sequence('context');
6150 $record->id
= $DB->insert_record('context', $record);
6152 } catch (dml_exception
$e) {
6153 // can not create context - table does not exist yet, sorry
6158 if ($record->instanceid
!= 0) {
6159 // this is very weird, somebody must be messing with context table
6160 debugging('Invalid system context detected');
6163 if ($record->depth
!= 1 or $record->path
!= '/'.$record->id
) {
6164 // fix path if necessary, initial install or path reset
6166 $record->path
= '/'.$record->id
;
6167 $DB->update_record('context', $record);
6170 if (!defined('SYSCONTEXTID')) {
6171 define('SYSCONTEXTID', $record->id
);
6174 context
::$systemcontext = new context_system($record);
6175 return context
::$systemcontext;
6179 * Returns all site contexts except the system context, DO NOT call on production servers!!
6181 * Contexts are not cached.
6185 public function get_child_contexts() {
6188 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
6190 // Just get all the contexts except for CONTEXT_SYSTEM level
6191 // and hope we don't OOM in the process - don't cache
6194 WHERE contextlevel > ".CONTEXT_SYSTEM
;
6195 $records = $DB->get_records_sql($sql);
6198 foreach ($records as $record) {
6199 $result[$record->id
] = context
::create_instance_from_record($record);
6206 * Returns sql necessary for purging of stale context instances.
6209 * @return string cleanup SQL
6211 protected static function get_cleanup_sql() {
6222 * Rebuild context paths and depths at system context level.
6225 * @param bool $force
6227 protected static function build_paths($force) {
6230 /* note: ignore $force here, we always do full test of system context */
6232 // exactly one record must exist
6233 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM
), '*', MUST_EXIST
);
6235 if ($record->instanceid
!= 0) {
6236 debugging('Invalid system context detected');
6239 if (defined('SYSCONTEXTID') and $record->id
!= SYSCONTEXTID
) {
6240 debugging('Invalid SYSCONTEXTID detected');
6243 if ($record->depth
!= 1 or $record->path
!= '/'.$record->id
) {
6244 // fix path if necessary, initial install or path reset
6246 $record->path
= '/'.$record->id
;
6247 $DB->update_record('context', $record);
6254 * User context class
6256 * @package core_access
6258 * @copyright Petr Skoda {@link http://skodak.org}
6259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6262 class context_user
extends context
{
6264 * Please use context_user::instance($userid) if you need the instance of context.
6265 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6267 * @param stdClass $record
6269 protected function __construct(stdClass
$record) {
6270 parent
::__construct($record);
6271 if ($record->contextlevel
!= CONTEXT_USER
) {
6272 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6277 * Returns human readable context level name.
6280 * @return string the human readable context level name.
6282 public static function get_level_name() {
6283 return get_string('user');
6287 * Returns human readable context identifier.
6289 * @param boolean $withprefix whether to prefix the name of the context with User
6290 * @param boolean $short does not apply to user context
6291 * @return string the human readable context name.
6293 public function get_context_name($withprefix = true, $short = false) {
6297 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid
, 'deleted'=>0))) {
6299 $name = get_string('user').': ';
6301 $name .= fullname($user);
6307 * Returns the most relevant URL for this context.
6309 * @return moodle_url
6311 public function get_url() {
6314 if ($COURSE->id
== SITEID
) {
6315 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid
));
6317 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid
, 'courseid'=>$COURSE->id
));
6323 * Returns array of relevant context capability records.
6327 public function get_capabilities() {
6330 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6332 $extracaps = array('moodle/grade:viewall');
6333 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED
, 'cap');
6336 WHERE contextlevel = ".CONTEXT_USER
."
6339 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6343 * Returns user context instance.
6346 * @param int $instanceid
6347 * @param int $strictness
6348 * @return context_user context instance
6350 public static function instance($instanceid, $strictness = MUST_EXIST
) {
6353 if ($context = context
::cache_get(CONTEXT_USER
, $instanceid)) {
6357 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER
, 'instanceid'=>$instanceid))) {
6358 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
6359 $record = context
::insert_context_record(CONTEXT_USER
, $user->id
, '/'.SYSCONTEXTID
, 0);
6364 $context = new context_user($record);
6365 context
::cache_add($context);
6373 * Create missing context instances at user context level
6376 protected static function create_level_instances() {
6379 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6380 SELECT ".CONTEXT_USER
.", u.id
6383 AND NOT EXISTS (SELECT 'x'
6385 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER
.")";
6390 * Returns sql necessary for purging of stale context instances.
6393 * @return string cleanup SQL
6395 protected static function get_cleanup_sql() {
6399 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6400 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER
."
6407 * Rebuild context paths and depths at user context level.
6410 * @param bool $force
6412 protected static function build_paths($force) {
6415 // First update normal users.
6416 $path = $DB->sql_concat('?', 'id');
6417 $pathstart = '/' . SYSCONTEXTID
. '/';
6418 $params = array($pathstart);
6421 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6422 $params[] = $pathstart;
6424 $where = "depth = 0 OR path IS NULL";
6427 $sql = "UPDATE {context}
6430 WHERE contextlevel = " . CONTEXT_USER
. "
6432 $DB->execute($sql, $params);
6438 * Course category context class
6440 * @package core_access
6442 * @copyright Petr Skoda {@link http://skodak.org}
6443 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6446 class context_coursecat
extends context
{
6448 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6449 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6451 * @param stdClass $record
6453 protected function __construct(stdClass
$record) {
6454 parent
::__construct($record);
6455 if ($record->contextlevel
!= CONTEXT_COURSECAT
) {
6456 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6461 * Returns human readable context level name.
6464 * @return string the human readable context level name.
6466 public static function get_level_name() {
6467 return get_string('category');
6471 * Returns human readable context identifier.
6473 * @param boolean $withprefix whether to prefix the name of the context with Category
6474 * @param boolean $short does not apply to course categories
6475 * @return string the human readable context name.
6477 public function get_context_name($withprefix = true, $short = false) {
6481 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid
))) {
6483 $name = get_string('category').': ';
6485 $name .= format_string($category->name
, true, array('context' => $this));
6491 * Returns the most relevant URL for this context.
6493 * @return moodle_url
6495 public function get_url() {
6496 return new moodle_url('/course/index.php', array('categoryid' => $this->_instanceid
));
6500 * Returns array of relevant context capability records.
6504 public function get_capabilities() {
6507 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6512 WHERE contextlevel IN (".CONTEXT_COURSECAT
.",".CONTEXT_COURSE
.",".CONTEXT_MODULE
.",".CONTEXT_BLOCK
.")";
6514 return $DB->get_records_sql($sql.' '.$sort, $params);
6518 * Returns course category context instance.
6521 * @param int $instanceid
6522 * @param int $strictness
6523 * @return context_coursecat context instance
6525 public static function instance($instanceid, $strictness = MUST_EXIST
) {
6528 if ($context = context
::cache_get(CONTEXT_COURSECAT
, $instanceid)) {
6532 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT
, 'instanceid'=>$instanceid))) {
6533 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
6534 if ($category->parent
) {
6535 $parentcontext = context_coursecat
::instance($category->parent
);
6536 $record = context
::insert_context_record(CONTEXT_COURSECAT
, $category->id
, $parentcontext->path
);
6538 $record = context
::insert_context_record(CONTEXT_COURSECAT
, $category->id
, '/'.SYSCONTEXTID
, 0);
6544 $context = new context_coursecat($record);
6545 context
::cache_add($context);
6553 * Returns immediate child contexts of category and all subcategories,
6554 * children of subcategories and courses are not returned.
6558 public function get_child_contexts() {
6561 $sql = "SELECT ctx.*
6563 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6564 $params = array($this->_path
.'/%', $this->depth+
1, CONTEXT_COURSECAT
);
6565 $records = $DB->get_records_sql($sql, $params);
6568 foreach ($records as $record) {
6569 $result[$record->id
] = context
::create_instance_from_record($record);
6576 * Create missing context instances at course category context level
6579 protected static function create_level_instances() {
6582 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6583 SELECT ".CONTEXT_COURSECAT
.", cc.id
6584 FROM {course_categories} cc
6585 WHERE NOT EXISTS (SELECT 'x'
6587 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT
.")";
6592 * Returns sql necessary for purging of stale context instances.
6595 * @return string cleanup SQL
6597 protected static function get_cleanup_sql() {
6601 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6602 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT
."
6609 * Rebuild context paths and depths at course category context level.
6612 * @param bool $force
6614 protected static function build_paths($force) {
6617 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT
." AND (depth = 0 OR path IS NULL)")) {
6619 $ctxemptyclause = $emptyclause = '';
6621 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6622 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6625 $base = '/'.SYSCONTEXTID
;
6627 // Normal top level categories
6628 $sql = "UPDATE {context}
6630 path=".$DB->sql_concat("'$base/'", 'id')."
6631 WHERE contextlevel=".CONTEXT_COURSECAT
."
6632 AND EXISTS (SELECT 'x'
6633 FROM {course_categories} cc
6634 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6638 // Deeper categories - one query per depthlevel
6639 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6640 for ($n=2; $n<=$maxdepth; $n++
) {
6641 $sql = "INSERT INTO {context_temp} (id, path, depth)
6642 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6644 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT
." AND cc.depth = $n)
6645 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT
.")
6646 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6648 $trans = $DB->start_delegated_transaction();
6649 $DB->delete_records('context_temp');
6651 context
::merge_context_temp_table();
6652 $DB->delete_records('context_temp');
6653 $trans->allow_commit();
6662 * Course context class
6664 * @package core_access
6666 * @copyright Petr Skoda {@link http://skodak.org}
6667 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6670 class context_course
extends context
{
6672 * Please use context_course::instance($courseid) if you need the instance of context.
6673 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6675 * @param stdClass $record
6677 protected function __construct(stdClass
$record) {
6678 parent
::__construct($record);
6679 if ($record->contextlevel
!= CONTEXT_COURSE
) {
6680 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6685 * Returns human readable context level name.
6688 * @return string the human readable context level name.
6690 public static function get_level_name() {
6691 return get_string('course');
6695 * Returns human readable context identifier.
6697 * @param boolean $withprefix whether to prefix the name of the context with Course
6698 * @param boolean $short whether to use the short name of the thing.
6699 * @return string the human readable context name.
6701 public function get_context_name($withprefix = true, $short = false) {
6705 if ($this->_instanceid
== SITEID
) {
6706 $name = get_string('frontpage', 'admin');
6708 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid
))) {
6710 $name = get_string('course').': ';
6713 $name .= format_string($course->shortname
, true, array('context' => $this));
6715 $name .= format_string(get_course_display_name_for_list($course));
6723 * Returns the most relevant URL for this context.
6725 * @return moodle_url
6727 public function get_url() {
6728 if ($this->_instanceid
!= SITEID
) {
6729 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid
));
6732 return new moodle_url('/');
6736 * Returns array of relevant context capability records.
6740 public function get_capabilities() {
6743 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6748 WHERE contextlevel IN (".CONTEXT_COURSE
.",".CONTEXT_MODULE
.",".CONTEXT_BLOCK
.")";
6750 return $DB->get_records_sql($sql.' '.$sort, $params);
6754 * Is this context part of any course? If yes return course context.
6756 * @param bool $strict true means throw exception if not found, false means return false if not found
6757 * @return course_context context of the enclosing course, null if not found or exception
6759 public function get_course_context($strict = true) {
6764 * Returns course context instance.
6767 * @param int $instanceid
6768 * @param int $strictness
6769 * @return context_course context instance
6771 public static function instance($instanceid, $strictness = MUST_EXIST
) {
6774 if ($context = context
::cache_get(CONTEXT_COURSE
, $instanceid)) {
6778 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE
, 'instanceid'=>$instanceid))) {
6779 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6780 if ($course->category
) {
6781 $parentcontext = context_coursecat
::instance($course->category
);
6782 $record = context
::insert_context_record(CONTEXT_COURSE
, $course->id
, $parentcontext->path
);
6784 $record = context
::insert_context_record(CONTEXT_COURSE
, $course->id
, '/'.SYSCONTEXTID
, 0);
6790 $context = new context_course($record);
6791 context
::cache_add($context);
6799 * Create missing context instances at course context level
6802 protected static function create_level_instances() {
6805 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6806 SELECT ".CONTEXT_COURSE
.", c.id
6808 WHERE NOT EXISTS (SELECT 'x'
6810 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE
.")";
6815 * Returns sql necessary for purging of stale context instances.
6818 * @return string cleanup SQL
6820 protected static function get_cleanup_sql() {
6824 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6825 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE
."
6832 * Rebuild context paths and depths at course context level.
6835 * @param bool $force
6837 protected static function build_paths($force) {
6840 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE
." AND (depth = 0 OR path IS NULL)")) {
6842 $ctxemptyclause = $emptyclause = '';
6844 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6845 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6848 $base = '/'.SYSCONTEXTID
;
6850 // Standard frontpage
6851 $sql = "UPDATE {context}
6853 path = ".$DB->sql_concat("'$base/'", 'id')."
6854 WHERE contextlevel = ".CONTEXT_COURSE
."
6855 AND EXISTS (SELECT 'x'
6857 WHERE c.id = {context}.instanceid AND c.category = 0)
6862 $sql = "INSERT INTO {context_temp} (id, path, depth)
6863 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6865 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE
." AND c.category <> 0)
6866 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT
.")
6867 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6869 $trans = $DB->start_delegated_transaction();
6870 $DB->delete_records('context_temp');
6872 context
::merge_context_temp_table();
6873 $DB->delete_records('context_temp');
6874 $trans->allow_commit();
6881 * Course module context class
6883 * @package core_access
6885 * @copyright Petr Skoda {@link http://skodak.org}
6886 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6889 class context_module
extends context
{
6891 * Please use context_module::instance($cmid) if you need the instance of context.
6892 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6894 * @param stdClass $record
6896 protected function __construct(stdClass
$record) {
6897 parent
::__construct($record);
6898 if ($record->contextlevel
!= CONTEXT_MODULE
) {
6899 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6904 * Returns human readable context level name.
6907 * @return string the human readable context level name.
6909 public static function get_level_name() {
6910 return get_string('activitymodule');
6914 * Returns human readable context identifier.
6916 * @param boolean $withprefix whether to prefix the name of the context with the
6917 * module name, e.g. Forum, Glossary, etc.
6918 * @param boolean $short does not apply to module context
6919 * @return string the human readable context name.
6921 public function get_context_name($withprefix = true, $short = false) {
6925 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6926 FROM {course_modules} cm
6927 JOIN {modules} md ON md.id = cm.module
6928 WHERE cm.id = ?", array($this->_instanceid
))) {
6929 if ($mod = $DB->get_record($cm->modname
, array('id' => $cm->instance
))) {
6931 $name = get_string('modulename', $cm->modname
).': ';
6933 $name .= format_string($mod->name
, true, array('context' => $this));
6940 * Returns the most relevant URL for this context.
6942 * @return moodle_url
6944 public function get_url() {
6947 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6948 FROM {course_modules} cm
6949 JOIN {modules} md ON md.id = cm.module
6950 WHERE cm.id = ?", array($this->_instanceid
))) {
6951 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid
));
6954 return new moodle_url('/');
6958 * Returns array of relevant context capability records.
6962 public function get_capabilities() {
6965 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6967 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid
));
6968 $module = $DB->get_record('modules', array('id'=>$cm->module
));
6971 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6972 if (file_exists($subpluginsfile)) {
6973 $subplugins = array(); // should be redefined in the file
6974 include($subpluginsfile);
6975 if (!empty($subplugins)) {
6976 foreach (array_keys($subplugins) as $subplugintype) {
6977 foreach (array_keys(core_component
::get_plugin_list($subplugintype)) as $subpluginname) {
6978 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6984 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6985 $extracaps = array();
6986 if (file_exists($modfile)) {
6987 include_once($modfile);
6988 $modfunction = $module->name
.'_get_extra_capabilities';
6989 if (function_exists($modfunction)) {
6990 $extracaps = $modfunction();
6994 $extracaps = array_merge($subcaps, $extracaps);
6996 list($extra, $params) = $DB->get_in_or_equal(
6997 $extracaps, SQL_PARAMS_NAMED
, 'cap0', true, '');
6998 if (!empty($extra)) {
6999 $extra = "OR name $extra";
7003 WHERE (contextlevel = ".CONTEXT_MODULE
."
7004 AND (component = :component OR component = 'moodle'))
7006 $params['component'] = "mod_$module->name";
7008 return $DB->get_records_sql($sql.' '.$sort, $params);
7012 * Is this context part of any course? If yes return course context.
7014 * @param bool $strict true means throw exception if not found, false means return false if not found
7015 * @return context_course context of the enclosing course, null if not found or exception
7017 public function get_course_context($strict = true) {
7018 return $this->get_parent_context();
7022 * Returns module context instance.
7025 * @param int $instanceid
7026 * @param int $strictness
7027 * @return context_module context instance
7029 public static function instance($instanceid, $strictness = MUST_EXIST
) {
7032 if ($context = context
::cache_get(CONTEXT_MODULE
, $instanceid)) {
7036 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE
, 'instanceid'=>$instanceid))) {
7037 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
7038 $parentcontext = context_course
::instance($cm->course
);
7039 $record = context
::insert_context_record(CONTEXT_MODULE
, $cm->id
, $parentcontext->path
);
7044 $context = new context_module($record);
7045 context
::cache_add($context);
7053 * Create missing context instances at module context level
7056 protected static function create_level_instances() {
7059 $sql = "INSERT INTO {context} (contextlevel, instanceid)
7060 SELECT ".CONTEXT_MODULE
.", cm.id
7061 FROM {course_modules} cm
7062 WHERE NOT EXISTS (SELECT 'x'
7064 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE
.")";
7069 * Returns sql necessary for purging of stale context instances.
7072 * @return string cleanup SQL
7074 protected static function get_cleanup_sql() {
7078 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
7079 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE
."
7086 * Rebuild context paths and depths at module context level.
7089 * @param bool $force
7091 protected static function build_paths($force) {
7094 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE
." AND (depth = 0 OR path IS NULL)")) {
7096 $ctxemptyclause = '';
7098 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7101 $sql = "INSERT INTO {context_temp} (id, path, depth)
7102 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7104 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE
.")
7105 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE
.")
7106 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
7108 $trans = $DB->start_delegated_transaction();
7109 $DB->delete_records('context_temp');
7111 context
::merge_context_temp_table();
7112 $DB->delete_records('context_temp');
7113 $trans->allow_commit();
7120 * Block context class
7122 * @package core_access
7124 * @copyright Petr Skoda {@link http://skodak.org}
7125 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7128 class context_block
extends context
{
7130 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
7131 * Alternatively if you know only the context id use context::instance_by_id($contextid)
7133 * @param stdClass $record
7135 protected function __construct(stdClass
$record) {
7136 parent
::__construct($record);
7137 if ($record->contextlevel
!= CONTEXT_BLOCK
) {
7138 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
7143 * Returns human readable context level name.
7146 * @return string the human readable context level name.
7148 public static function get_level_name() {
7149 return get_string('block');
7153 * Returns human readable context identifier.
7155 * @param boolean $withprefix whether to prefix the name of the context with Block
7156 * @param boolean $short does not apply to block context
7157 * @return string the human readable context name.
7159 public function get_context_name($withprefix = true, $short = false) {
7163 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid
))) {
7165 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
7166 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
7167 $blockname = "block_$blockinstance->blockname";
7168 if ($blockobject = new $blockname()) {
7170 $name = get_string('block').': ';
7172 $name .= $blockobject->title
;
7180 * Returns the most relevant URL for this context.
7182 * @return moodle_url
7184 public function get_url() {
7185 $parentcontexts = $this->get_parent_context();
7186 return $parentcontexts->get_url();
7190 * Returns array of relevant context capability records.
7194 public function get_capabilities() {
7197 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
7200 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid
));
7203 $extracaps = block_method_result($bi->blockname
, 'get_extra_capabilities');
7205 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED
, 'cap');
7206 $extra = "OR name $extra";
7211 WHERE (contextlevel = ".CONTEXT_BLOCK
."
7212 AND component = :component)
7214 $params['component'] = 'block_' . $bi->blockname
;
7216 return $DB->get_records_sql($sql.' '.$sort, $params);
7220 * Is this context part of any course? If yes return course context.
7222 * @param bool $strict true means throw exception if not found, false means return false if not found
7223 * @return course_context context of the enclosing course, null if not found or exception
7225 public function get_course_context($strict = true) {
7226 $parentcontext = $this->get_parent_context();
7227 return $parentcontext->get_course_context($strict);
7231 * Returns block context instance.
7234 * @param int $instanceid
7235 * @param int $strictness
7236 * @return context_block context instance
7238 public static function instance($instanceid, $strictness = MUST_EXIST
) {
7241 if ($context = context
::cache_get(CONTEXT_BLOCK
, $instanceid)) {
7245 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK
, 'instanceid'=>$instanceid))) {
7246 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
7247 $parentcontext = context
::instance_by_id($bi->parentcontextid
);
7248 $record = context
::insert_context_record(CONTEXT_BLOCK
, $bi->id
, $parentcontext->path
);
7253 $context = new context_block($record);
7254 context
::cache_add($context);
7262 * Block do not have child contexts...
7265 public function get_child_contexts() {
7270 * Create missing context instances at block context level
7273 protected static function create_level_instances() {
7276 $sql = "INSERT INTO {context} (contextlevel, instanceid)
7277 SELECT ".CONTEXT_BLOCK
.", bi.id
7278 FROM {block_instances} bi
7279 WHERE NOT EXISTS (SELECT 'x'
7281 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK
.")";
7286 * Returns sql necessary for purging of stale context instances.
7289 * @return string cleanup SQL
7291 protected static function get_cleanup_sql() {
7295 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7296 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK
."
7303 * Rebuild context paths and depths at block context level.
7306 * @param bool $force
7308 protected static function build_paths($force) {
7311 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK
." AND (depth = 0 OR path IS NULL)")) {
7313 $ctxemptyclause = '';
7315 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7318 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7319 $sql = "INSERT INTO {context_temp} (id, path, depth)
7320 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7322 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK
.")
7323 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7324 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7326 $trans = $DB->start_delegated_transaction();
7327 $DB->delete_records('context_temp');
7329 context
::merge_context_temp_table();
7330 $DB->delete_records('context_temp');
7331 $trans->allow_commit();
7337 // ============== DEPRECATED FUNCTIONS ==========================================
7338 // Old context related functions were deprecated in 2.0, it is recommended
7339 // to use context classes in new code. Old function can be used when
7340 // creating patches that are supposed to be backported to older stable branches.
7341 // These deprecated functions will not be removed in near future,
7342 // before removing devs will be warned with a debugging message first,
7343 // then we will add error message and only after that we can remove the functions
7347 * Runs get_records select on context table and returns the result
7348 * Does get_records_select on the context table, and returns the results ordered
7349 * by contextlevel, and then the natural sort order within each level.
7350 * for the purpose of $select, you need to know that the context table has been
7351 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7353 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7354 * @param array $params any parameters required by $select.
7355 * @return array the requested context records.
7357 function get_sorted_contexts($select, $params = array()) {
7359 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7363 $select = 'WHERE ' . $select;
7365 return $DB->get_records_sql("
7368 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER
. " AND u.id = ctx.instanceid
7369 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT
. " AND cat.id = ctx.instanceid
7370 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE
. " AND c.id = ctx.instanceid
7371 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE
. " AND cm.id = ctx.instanceid
7372 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK
. " AND bi.id = ctx.instanceid
7374 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7379 * Given context and array of users, returns array of users whose enrolment status is suspended,
7380 * or enrolment has expired or has not started. Also removes those users from the given array
7382 * @param context $context context in which suspended users should be extracted.
7383 * @param array $users list of users.
7384 * @param array $ignoreusers array of user ids to ignore, e.g. guest
7385 * @return array list of suspended users.
7387 function extract_suspended_users($context, &$users, $ignoreusers=array()) {
7390 // Get active enrolled users.
7391 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7392 $activeusers = $DB->get_records_sql($sql, $params);
7394 // Move suspended users to a separate array & remove from the initial one.
7396 if (sizeof($activeusers)) {
7397 foreach ($users as $userid => $user) {
7398 if (!array_key_exists($userid, $activeusers) && !in_array($userid, $ignoreusers)) {
7399 $susers[$userid] = $user;
7400 unset($users[$userid]);
7408 * Given context and array of users, returns array of user ids whose enrolment status is suspended,
7409 * or enrolment has expired or not started.
7411 * @param context $context context in which user enrolment is checked.
7412 * @return array list of suspended user id's.
7414 function get_suspended_userids($context){
7417 // Get all enrolled users.
7418 list($sql, $params) = get_enrolled_sql($context);
7419 $users = $DB->get_records_sql($sql, $params);
7421 // Get active enrolled users.
7422 list($sql, $params) = get_enrolled_sql($context, null, null, true);
7423 $activeusers = $DB->get_records_sql($sql, $params);
7426 if (sizeof($activeusers) != sizeof($users)) {
7427 foreach ($users as $userid => $user) {
7428 if (!array_key_exists($userid, $activeusers)) {
7429 $susers[$userid] = $userid;