Merge branch 'install_24_STABLE' of git://git.moodle.cz/moodle-install into MOODLE_24...
[moodle.git] / lib / accesslib.php
blob6bc53c252fcb4d2de9c9fc64bf3c802dc8320cde
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains functions for managing user access
20 * <b>Public API vs internals</b>
22 * General users probably only care about
24 * Context handling
25 * - context_course::instance($courseid), context_module::instance($cm->id), context_coursecat::instance($catid)
26 * - context::instance_by_id($contextid)
27 * - $context->get_parent_contexts();
28 * - $context->get_child_contexts();
30 * Whether the user can do something...
31 * - has_capability()
32 * - has_any_capability()
33 * - has_all_capabilities()
34 * - require_capability()
35 * - require_login() (from moodlelib)
36 * - is_enrolled()
37 * - is_viewing()
38 * - is_guest()
39 * - is_siteadmin()
40 * - isguestuser()
41 * - isloggedin()
43 * What courses has this user access to?
44 * - get_enrolled_users()
46 * What users can do X in this context?
47 * - get_enrolled_users() - at and bellow course context
48 * - get_users_by_capability() - above course context
50 * Modify roles
51 * - role_assign()
52 * - role_unassign()
53 * - role_unassign_all()
55 * Advanced - for internal use only
56 * - load_all_capabilities()
57 * - reload_all_capabilities()
58 * - has_capability_in_accessdata()
59 * - get_user_access_sitewide()
60 * - load_course_context()
61 * - load_role_access_by_context()
62 * - etc.
64 * <b>Name conventions</b>
66 * "ctx" means context
68 * <b>accessdata</b>
70 * Access control data is held in the "accessdata" array
71 * which - for the logged-in user, will be in $USER->access
73 * For other users can be generated and passed around (but may also be cached
74 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
76 * $accessdata is a multidimensional array, holding
77 * role assignments (RAs), role-capabilities-perm sets
78 * (role defs) and a list of courses we have loaded
79 * data for.
81 * Things are keyed on "contextpaths" (the path field of
82 * the context table) for fast walking up/down the tree.
83 * <code>
84 * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
85 * [$contextpath] = array($roleid=>$roleid)
86 * [$contextpath] = array($roleid=>$roleid)
87 * </code>
89 * Role definitions are stored like this
90 * (no cap merge is done - so it's compact)
92 * <code>
93 * $accessdata['rdef']["$contextpath:$roleid"]['mod/forum:viewpost'] = 1
94 * ['mod/forum:editallpost'] = -1
95 * ['mod/forum:startdiscussion'] = -1000
96 * </code>
98 * See how has_capability_in_accessdata() walks up the tree.
100 * First we only load rdef and ra down to the course level, but not below.
101 * This keeps accessdata small and compact. Below-the-course ra/rdef
102 * are loaded as needed. We keep track of which courses we have loaded ra/rdef in
103 * <code>
104 * $accessdata['loaded'] = array($courseid1=>1, $courseid2=>1)
105 * </code>
107 * <b>Stale accessdata</b>
109 * For the logged-in user, accessdata is long-lived.
111 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
112 * context paths affected by changes. Any check at-or-below
113 * a dirty context will trigger a transparent reload of accessdata.
115 * Changes at the system level will force the reload for everyone.
117 * <b>Default role caps</b>
118 * The default role assignment is not in the DB, so we
119 * add it manually to accessdata.
121 * This means that functions that work directly off the
122 * DB need to ensure that the default role caps
123 * are dealt with appropriately.
125 * @package core_access
126 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
130 defined('MOODLE_INTERNAL') || die();
132 /** No capability change */
133 define('CAP_INHERIT', 0);
134 /** Allow permission, overrides CAP_PREVENT defined in parent contexts */
135 define('CAP_ALLOW', 1);
136 /** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
137 define('CAP_PREVENT', -1);
138 /** Prohibit permission, overrides everything in current and child contexts */
139 define('CAP_PROHIBIT', -1000);
141 /** System context level - only one instance in every system */
142 define('CONTEXT_SYSTEM', 10);
143 /** User context level - one instance for each user describing what others can do to user */
144 define('CONTEXT_USER', 30);
145 /** Course category context level - one instance for each category */
146 define('CONTEXT_COURSECAT', 40);
147 /** Course context level - one instances for each course */
148 define('CONTEXT_COURSE', 50);
149 /** Course module context level - one instance for each course module */
150 define('CONTEXT_MODULE', 70);
152 * Block context level - one instance for each block, sticky blocks are tricky
153 * because ppl think they should be able to override them at lower contexts.
154 * Any other context level instance can be parent of block context.
156 define('CONTEXT_BLOCK', 80);
158 /** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
159 define('RISK_MANAGETRUST', 0x0001);
160 /** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
161 define('RISK_CONFIG', 0x0002);
162 /** Capability allows user to add scripted content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
163 define('RISK_XSS', 0x0004);
164 /** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
165 define('RISK_PERSONAL', 0x0008);
166 /** Capability allows users to add content others may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
167 define('RISK_SPAM', 0x0010);
168 /** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
169 define('RISK_DATALOSS', 0x0020);
171 /** rolename displays - the name as defined in the role definition, 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.
197 * @access private
198 * @global stdClass $ACCESSLIB_PRIVATE
199 * @name $ACCESSLIB_PRIVATE
201 global $ACCESSLIB_PRIVATE;
202 $ACCESSLIB_PRIVATE = new stdClass();
203 $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache, loaded from DB once per page
204 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
205 $ACCESSLIB_PRIVATE->rolepermissions = array(); // role permissions cache - helps a lot with mem usage
206 $ACCESSLIB_PRIVATE->capabilities = null; // detailed information about the capabilities
209 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
211 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
212 * accesslib's private caches. You need to do this before setting up test data,
213 * and also at the end of the tests.
215 * @access private
216 * @return void
218 function accesslib_clear_all_caches_for_unit_testing() {
219 global $USER;
220 if (!PHPUNIT_TEST) {
221 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
224 accesslib_clear_all_caches(true);
226 unset($USER->access);
230 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
232 * This reset does not touch global $USER.
234 * @access private
235 * @param bool $resetcontexts
236 * @return void
238 function accesslib_clear_all_caches($resetcontexts) {
239 global $ACCESSLIB_PRIVATE;
241 $ACCESSLIB_PRIVATE->dirtycontexts = null;
242 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
243 $ACCESSLIB_PRIVATE->rolepermissions = array();
244 $ACCESSLIB_PRIVATE->capabilities = null;
246 if ($resetcontexts) {
247 context_helper::reset_caches();
252 * Gets the accessdata for role "sitewide" (system down to course)
254 * @access private
255 * @param int $roleid
256 * @return array
258 function get_role_access($roleid) {
259 global $DB, $ACCESSLIB_PRIVATE;
261 /* Get it in 1 DB query...
262 * - relevant role caps at the root and down
263 * to the course level - but not below
266 //TODO: MUC - this could be cached in shared memory to speed up first page loading, web crawlers, etc.
268 $accessdata = get_empty_accessdata();
270 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
273 // Overrides for the role IN ANY CONTEXTS
274 // down to COURSE - not below -
276 $sql = "SELECT ctx.path,
277 rc.capability, rc.permission
278 FROM {context} ctx
279 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
280 LEFT JOIN {context} cctx
281 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
282 WHERE rc.roleid = ? AND cctx.id IS NULL";
283 $params = array($roleid);
285 // we need extra caching in CLI scripts and cron
286 $rs = $DB->get_recordset_sql($sql, $params);
287 foreach ($rs as $rd) {
288 $k = "{$rd->path}:{$roleid}";
289 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
291 $rs->close();
293 // share the role definitions
294 foreach ($accessdata['rdef'] as $k=>$unused) {
295 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
296 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
298 $accessdata['rdef_count']++;
299 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
302 return $accessdata;
306 * Get the default guest role, this is used for guest account,
307 * search engine spiders, etc.
309 * @return stdClass role record
311 function get_guest_role() {
312 global $CFG, $DB;
314 if (empty($CFG->guestroleid)) {
315 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
316 $guestrole = array_shift($roles); // Pick the first one
317 set_config('guestroleid', $guestrole->id);
318 return $guestrole;
319 } else {
320 debugging('Can not find any guest role!');
321 return false;
323 } else {
324 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
325 return $guestrole;
326 } else {
327 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
328 set_config('guestroleid', '');
329 return get_guest_role();
335 * Check whether a user has a particular capability in a given context.
337 * For example:
338 * $context = context_module::instance($cm->id);
339 * has_capability('mod/forum:replypost', $context)
341 * By default checks the capabilities of the current user, but you can pass a
342 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
344 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
345 * or capabilities with XSS, config or data loss risks.
347 * @category access
349 * @param string $capability the name of the capability to check. For example mod/forum:view
350 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
351 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
352 * @param boolean $doanything If false, ignores effect of admin role assignment
353 * @return boolean true if the user has this capability. Otherwise false.
355 function has_capability($capability, context $context, $user = null, $doanything = true) {
356 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
358 if (during_initial_install()) {
359 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
360 // we are in an installer - roles can not work yet
361 return true;
362 } else {
363 return false;
367 if (strpos($capability, 'moodle/legacy:') === 0) {
368 throw new coding_exception('Legacy capabilities can not be used any more!');
371 if (!is_bool($doanything)) {
372 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
375 // capability must exist
376 if (!$capinfo = get_capability_info($capability)) {
377 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
378 return false;
381 if (!isset($USER->id)) {
382 // should never happen
383 $USER->id = 0;
386 // make sure there is a real user specified
387 if ($user === null) {
388 $userid = $USER->id;
389 } else {
390 $userid = is_object($user) ? $user->id : $user;
393 // make sure forcelogin cuts off not-logged-in users if enabled
394 if (!empty($CFG->forcelogin) and $userid == 0) {
395 return false;
398 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
399 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
400 if (isguestuser($userid) or $userid == 0) {
401 return false;
405 // somehow make sure the user is not deleted and actually exists
406 if ($userid != 0) {
407 if ($userid == $USER->id and isset($USER->deleted)) {
408 // this prevents one query per page, it is a bit of cheating,
409 // but hopefully session is terminated properly once user is deleted
410 if ($USER->deleted) {
411 return false;
413 } else {
414 if (!context_user::instance($userid, IGNORE_MISSING)) {
415 // no user context == invalid userid
416 return false;
421 // context path/depth must be valid
422 if (empty($context->path) or $context->depth == 0) {
423 // this should not happen often, each upgrade tries to rebuild the context paths
424 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()');
425 if (is_siteadmin($userid)) {
426 return true;
427 } else {
428 return false;
432 // Find out if user is admin - it is not possible to override the doanything in any way
433 // and it is not possible to switch to admin role either.
434 if ($doanything) {
435 if (is_siteadmin($userid)) {
436 if ($userid != $USER->id) {
437 return true;
439 // make sure switchrole is not used in this context
440 if (empty($USER->access['rsw'])) {
441 return true;
443 $parts = explode('/', trim($context->path, '/'));
444 $path = '';
445 $switched = false;
446 foreach ($parts as $part) {
447 $path .= '/' . $part;
448 if (!empty($USER->access['rsw'][$path])) {
449 $switched = true;
450 break;
453 if (!$switched) {
454 return true;
456 //ok, admin switched role in this context, let's use normal access control rules
460 // Careful check for staleness...
461 $context->reload_if_dirty();
463 if ($USER->id == $userid) {
464 if (!isset($USER->access)) {
465 load_all_capabilities();
467 $access =& $USER->access;
469 } else {
470 // make sure user accessdata is really loaded
471 get_user_accessdata($userid, true);
472 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
476 // Load accessdata for below-the-course context if necessary,
477 // all contexts at and above all courses are already loaded
478 if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
479 load_course_context($userid, $coursecontext, $access);
482 return has_capability_in_accessdata($capability, $context, $access);
486 * Check if the user has any one of several capabilities from a list.
488 * This is just a utility method that calls has_capability in a loop. Try to put
489 * the capabilities that most users are likely to have first in the list for best
490 * performance.
492 * @category access
493 * @see has_capability()
495 * @param array $capabilities an array of capability names.
496 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
497 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
498 * @param boolean $doanything If false, ignore effect of admin role assignment
499 * @return boolean true if the user has any of these capabilities. Otherwise false.
501 function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
502 foreach ($capabilities as $capability) {
503 if (has_capability($capability, $context, $user, $doanything)) {
504 return true;
507 return false;
511 * Check if the user has all the capabilities in a list.
513 * This is just a utility method that calls has_capability in a loop. Try to put
514 * the capabilities that fewest users are likely to have first in the list for best
515 * performance.
517 * @category access
518 * @see has_capability()
520 * @param array $capabilities an array of capability names.
521 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
522 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
523 * @param boolean $doanything If false, ignore effect of admin role assignment
524 * @return boolean true if the user has all of these capabilities. Otherwise false.
526 function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
527 foreach ($capabilities as $capability) {
528 if (!has_capability($capability, $context, $user, $doanything)) {
529 return false;
532 return true;
536 * Check if the user is an admin at the site level.
538 * Please note that use of proper capabilities is always encouraged,
539 * this function is supposed to be used from core or for temporary hacks.
541 * @category access
543 * @param int|stdClass $user_or_id user id or user object
544 * @return bool true if user is one of the administrators, false otherwise
546 function is_siteadmin($user_or_id = null) {
547 global $CFG, $USER;
549 if ($user_or_id === null) {
550 $user_or_id = $USER;
553 if (empty($user_or_id)) {
554 return false;
556 if (!empty($user_or_id->id)) {
557 $userid = $user_or_id->id;
558 } else {
559 $userid = $user_or_id;
562 $siteadmins = explode(',', $CFG->siteadmins);
563 return in_array($userid, $siteadmins);
567 * Returns true if user has at least one role assign
568 * of 'coursecontact' role (is potentially listed in some course descriptions).
570 * @param int $userid
571 * @return bool
573 function has_coursecontact_role($userid) {
574 global $DB, $CFG;
576 if (empty($CFG->coursecontact)) {
577 return false;
579 $sql = "SELECT 1
580 FROM {role_assignments}
581 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
582 return $DB->record_exists_sql($sql, array('userid'=>$userid));
586 * Does the user have a capability to do something?
588 * Walk the accessdata array and return true/false.
589 * Deals with prohibits, role switching, aggregating
590 * capabilities, etc.
592 * The main feature of here is being FAST and with no
593 * side effects.
595 * Notes:
597 * Switch Role merges with default role
598 * ------------------------------------
599 * If you are a teacher in course X, you have at least
600 * teacher-in-X + defaultloggedinuser-sitewide. So in the
601 * course you'll have techer+defaultloggedinuser.
602 * We try to mimic that in switchrole.
604 * Permission evaluation
605 * ---------------------
606 * Originally there was an extremely complicated way
607 * to determine the user access that dealt with
608 * "locality" or role assignments and role overrides.
609 * Now we simply evaluate access for each role separately
610 * and then verify if user has at least one role with allow
611 * and at the same time no role with prohibit.
613 * @access private
614 * @param string $capability
615 * @param context $context
616 * @param array $accessdata
617 * @return bool
619 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
620 global $CFG;
622 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
623 $path = $context->path;
624 $paths = array($path);
625 while($path = rtrim($path, '0123456789')) {
626 $path = rtrim($path, '/');
627 if ($path === '') {
628 break;
630 $paths[] = $path;
633 $roles = array();
634 $switchedrole = false;
636 // Find out if role switched
637 if (!empty($accessdata['rsw'])) {
638 // From the bottom up...
639 foreach ($paths as $path) {
640 if (isset($accessdata['rsw'][$path])) {
641 // Found a switchrole assignment - check for that role _plus_ the default user role
642 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
643 $switchedrole = true;
644 break;
649 if (!$switchedrole) {
650 // get all users roles in this context and above
651 foreach ($paths as $path) {
652 if (isset($accessdata['ra'][$path])) {
653 foreach ($accessdata['ra'][$path] as $roleid) {
654 $roles[$roleid] = null;
660 // Now find out what access is given to each role, going bottom-->up direction
661 $allowed = false;
662 foreach ($roles as $roleid => $ignored) {
663 foreach ($paths as $path) {
664 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
665 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
666 if ($perm === CAP_PROHIBIT) {
667 // any CAP_PROHIBIT found means no permission for the user
668 return false;
670 if (is_null($roles[$roleid])) {
671 $roles[$roleid] = $perm;
675 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
676 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
679 return $allowed;
683 * A convenience function that tests has_capability, and displays an error if
684 * the user does not have that capability.
686 * NOTE before Moodle 2.0, this function attempted to make an appropriate
687 * require_login call before checking the capability. This is no longer the case.
688 * You must call require_login (or one of its variants) if you want to check the
689 * user is logged in, before you call this function.
691 * @see has_capability()
693 * @param string $capability the name of the capability to check. For example mod/forum:view
694 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
695 * @param int $userid A user id. By default (null) checks the permissions of the current user.
696 * @param bool $doanything If false, ignore effect of admin role assignment
697 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
698 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
699 * @return void terminates with an error if the user does not have the given capability.
701 function require_capability($capability, context $context, $userid = null, $doanything = true,
702 $errormessage = 'nopermissions', $stringfile = '') {
703 if (!has_capability($capability, $context, $userid, $doanything)) {
704 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
709 * Return a nested array showing role assignments
710 * all relevant role capabilities for the user at
711 * site/course_category/course levels
713 * We do _not_ delve deeper than courses because the number of
714 * overrides at the module/block levels can be HUGE.
716 * [ra] => [/path][roleid]=roleid
717 * [rdef] => [/path:roleid][capability]=permission
719 * @access private
720 * @param int $userid - the id of the user
721 * @return array access info array
723 function get_user_access_sitewide($userid) {
724 global $CFG, $DB, $ACCESSLIB_PRIVATE;
726 /* Get in a few cheap DB queries...
727 * - role assignments
728 * - relevant role caps
729 * - above and within this user's RAs
730 * - below this user's RAs - limited to course level
733 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
734 $raparents = array();
735 $accessdata = get_empty_accessdata();
737 // start with the default role
738 if (!empty($CFG->defaultuserroleid)) {
739 $syscontext = context_system::instance();
740 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
741 $raparents[$CFG->defaultuserroleid][$syscontext->id] = $syscontext->id;
744 // load the "default frontpage role"
745 if (!empty($CFG->defaultfrontpageroleid)) {
746 $frontpagecontext = context_course::instance(get_site()->id);
747 if ($frontpagecontext->path) {
748 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
749 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->id] = $frontpagecontext->id;
753 // preload every assigned role at and above course context
754 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
755 FROM {role_assignments} ra
756 JOIN {context} ctx
757 ON ctx.id = ra.contextid
758 LEFT JOIN {block_instances} bi
759 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
760 LEFT JOIN {context} bpctx
761 ON (bpctx.id = bi.parentcontextid)
762 WHERE ra.userid = :userid
763 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")";
764 $params = array('userid'=>$userid);
765 $rs = $DB->get_recordset_sql($sql, $params);
766 foreach ($rs as $ra) {
767 // RAs leafs are arrays to support multi-role assignments...
768 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
769 $raparents[$ra->roleid][$ra->contextid] = $ra->contextid;
771 $rs->close();
773 if (empty($raparents)) {
774 return $accessdata;
777 // now get overrides of interesting roles in all interesting child contexts
778 // hopefully we will not run out of SQL limits here,
779 // users would have to have very many roles at/above course context...
780 $sqls = array();
781 $params = array();
783 static $cp = 0;
784 foreach ($raparents as $roleid=>$ras) {
785 $cp++;
786 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED, 'c'.$cp.'_');
787 $params = array_merge($params, $cids);
788 $params['r'.$cp] = $roleid;
789 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
790 FROM {role_capabilities} rc
791 JOIN {context} ctx
792 ON (ctx.id = rc.contextid)
793 JOIN {context} pctx
794 ON (pctx.id $sqlcids
795 AND (ctx.id = pctx.id
796 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
797 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
798 LEFT JOIN {block_instances} bi
799 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
800 LEFT JOIN {context} bpctx
801 ON (bpctx.id = bi.parentcontextid)
802 WHERE rc.roleid = :r{$cp}
803 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")
807 // fixed capability order is necessary for rdef dedupe
808 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
810 foreach ($rs as $rd) {
811 $k = $rd->path.':'.$rd->roleid;
812 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
814 $rs->close();
816 // share the role definitions
817 foreach ($accessdata['rdef'] as $k=>$unused) {
818 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
819 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
821 $accessdata['rdef_count']++;
822 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
825 return $accessdata;
829 * Add to the access ctrl array the data needed by a user for a given course.
831 * This function injects all course related access info into the accessdata array.
833 * @access private
834 * @param int $userid the id of the user
835 * @param context_course $coursecontext course context
836 * @param array $accessdata accessdata array (modified)
837 * @return void modifies $accessdata parameter
839 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
840 global $DB, $CFG, $ACCESSLIB_PRIVATE;
842 if (empty($coursecontext->path)) {
843 // weird, this should not happen
844 return;
847 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
848 // already loaded, great!
849 return;
852 $roles = array();
854 if (empty($userid)) {
855 if (!empty($CFG->notloggedinroleid)) {
856 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
859 } else if (isguestuser($userid)) {
860 if ($guestrole = get_guest_role()) {
861 $roles[$guestrole->id] = $guestrole->id;
864 } else {
865 // Interesting role assignments at, above and below the course context
866 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
867 $params['userid'] = $userid;
868 $params['children'] = $coursecontext->path."/%";
869 $sql = "SELECT ra.*, ctx.path
870 FROM {role_assignments} ra
871 JOIN {context} ctx ON ra.contextid = ctx.id
872 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
873 $rs = $DB->get_recordset_sql($sql, $params);
875 // add missing role definitions
876 foreach ($rs as $ra) {
877 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
878 $roles[$ra->roleid] = $ra->roleid;
880 $rs->close();
882 // add the "default frontpage role" when on the frontpage
883 if (!empty($CFG->defaultfrontpageroleid)) {
884 $frontpagecontext = context_course::instance(get_site()->id);
885 if ($frontpagecontext->id == $coursecontext->id) {
886 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
890 // do not forget the default role
891 if (!empty($CFG->defaultuserroleid)) {
892 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
896 if (!$roles) {
897 // weird, default roles must be missing...
898 $accessdata['loaded'][$coursecontext->instanceid] = 1;
899 return;
902 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
903 $params = array('c'=>$coursecontext->id);
904 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
905 $params = array_merge($params, $rparams);
906 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
907 $params = array_merge($params, $rparams);
909 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
910 FROM {role_capabilities} rc
911 JOIN {context} ctx
912 ON (ctx.id = rc.contextid)
913 JOIN {context} cctx
914 ON (cctx.id = :c
915 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
916 WHERE rc.roleid $roleids
917 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
918 $rs = $DB->get_recordset_sql($sql, $params);
920 $newrdefs = array();
921 foreach ($rs as $rd) {
922 $k = $rd->path.':'.$rd->roleid;
923 if (isset($accessdata['rdef'][$k])) {
924 continue;
926 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
928 $rs->close();
930 // share new role definitions
931 foreach ($newrdefs as $k=>$unused) {
932 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
933 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
935 $accessdata['rdef_count']++;
936 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
939 $accessdata['loaded'][$coursecontext->instanceid] = 1;
941 // we want to deduplicate the USER->access from time to time, this looks like a good place,
942 // because we have to do it before the end of session
943 dedupe_user_access();
947 * Add to the access ctrl array the data needed by a role for a given context.
949 * The data is added in the rdef key.
950 * This role-centric function is useful for role_switching
951 * and temporary course roles.
953 * @access private
954 * @param int $roleid the id of the user
955 * @param context $context needs path!
956 * @param array $accessdata accessdata array (is modified)
957 * @return array
959 function load_role_access_by_context($roleid, context $context, &$accessdata) {
960 global $DB, $ACCESSLIB_PRIVATE;
962 /* Get the relevant rolecaps into rdef
963 * - relevant role caps
964 * - at ctx and above
965 * - below this ctx
968 if (empty($context->path)) {
969 // weird, this should not happen
970 return;
973 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
974 $params['roleid'] = $roleid;
975 $params['childpath'] = $context->path.'/%';
977 $sql = "SELECT ctx.path, rc.capability, rc.permission
978 FROM {role_capabilities} rc
979 JOIN {context} ctx ON (rc.contextid = ctx.id)
980 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
981 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
982 $rs = $DB->get_recordset_sql($sql, $params);
984 $newrdefs = array();
985 foreach ($rs as $rd) {
986 $k = $rd->path.':'.$roleid;
987 if (isset($accessdata['rdef'][$k])) {
988 continue;
990 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
992 $rs->close();
994 // share new role definitions
995 foreach ($newrdefs as $k=>$unused) {
996 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
997 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
999 $accessdata['rdef_count']++;
1000 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1005 * Returns empty accessdata structure.
1007 * @access private
1008 * @return array empt accessdata
1010 function get_empty_accessdata() {
1011 $accessdata = array(); // named list
1012 $accessdata['ra'] = array();
1013 $accessdata['rdef'] = array();
1014 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1015 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1016 $accessdata['loaded'] = array(); // loaded course contexts
1017 $accessdata['time'] = time();
1018 $accessdata['rsw'] = array();
1020 return $accessdata;
1024 * Get accessdata for a given user.
1026 * @access private
1027 * @param int $userid
1028 * @param bool $preloadonly true means do not return access array
1029 * @return array accessdata
1031 function get_user_accessdata($userid, $preloadonly=false) {
1032 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1034 if (!empty($USER->acces['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1035 // share rdef from USER session with rolepermissions cache in order to conserve memory
1036 foreach($USER->acces['rdef'] as $k=>$v) {
1037 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->acces['rdef'][$k];
1039 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->acces;
1042 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1043 if (empty($userid)) {
1044 if (!empty($CFG->notloggedinroleid)) {
1045 $accessdata = get_role_access($CFG->notloggedinroleid);
1046 } else {
1047 // weird
1048 return get_empty_accessdata();
1051 } else if (isguestuser($userid)) {
1052 if ($guestrole = get_guest_role()) {
1053 $accessdata = get_role_access($guestrole->id);
1054 } else {
1055 //weird
1056 return get_empty_accessdata();
1059 } else {
1060 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1063 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1066 if ($preloadonly) {
1067 return;
1068 } else {
1069 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1074 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1075 * this function looks for contexts with the same overrides and shares them.
1077 * @access private
1078 * @return void
1080 function dedupe_user_access() {
1081 global $USER;
1083 if (CLI_SCRIPT) {
1084 // no session in CLI --> no compression necessary
1085 return;
1088 if (empty($USER->access['rdef_count'])) {
1089 // weird, this should not happen
1090 return;
1093 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1094 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1095 // do not compress after each change, wait till there is more stuff to be done
1096 return;
1099 $hashmap = array();
1100 foreach ($USER->access['rdef'] as $k=>$def) {
1101 $hash = sha1(serialize($def));
1102 if (isset($hashmap[$hash])) {
1103 $USER->access['rdef'][$k] =& $hashmap[$hash];
1104 } else {
1105 $hashmap[$hash] =& $USER->access['rdef'][$k];
1109 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1113 * A convenience function to completely load all the capabilities
1114 * for the current user. It is called from has_capability() and functions change permissions.
1116 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1117 * @see check_enrolment_plugins()
1119 * @access private
1120 * @return void
1122 function load_all_capabilities() {
1123 global $USER;
1125 // roles not installed yet - we are in the middle of installation
1126 if (during_initial_install()) {
1127 return;
1130 if (!isset($USER->id)) {
1131 // this should not happen
1132 $USER->id = 0;
1135 unset($USER->access);
1136 $USER->access = get_user_accessdata($USER->id);
1138 // deduplicate the overrides to minimize session size
1139 dedupe_user_access();
1141 // Clear to force a refresh
1142 unset($USER->mycourses);
1144 // init/reset internal enrol caches - active course enrolments and temp access
1145 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1149 * A convenience function to completely reload all the capabilities
1150 * for the current user when roles have been updated in a relevant
1151 * context -- but PRESERVING switchroles and loginas.
1152 * This function resets all accesslib and context caches.
1154 * That is - completely transparent to the user.
1156 * Note: reloads $USER->access completely.
1158 * @access private
1159 * @return void
1161 function reload_all_capabilities() {
1162 global $USER, $DB, $ACCESSLIB_PRIVATE;
1164 // copy switchroles
1165 $sw = array();
1166 if (!empty($USER->access['rsw'])) {
1167 $sw = $USER->access['rsw'];
1170 accesslib_clear_all_caches(true);
1171 unset($USER->access);
1172 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1174 load_all_capabilities();
1176 foreach ($sw as $path => $roleid) {
1177 if ($record = $DB->get_record('context', array('path'=>$path))) {
1178 $context = context::instance_by_id($record->id);
1179 role_switch($roleid, $context);
1185 * Adds a temp role to current USER->access array.
1187 * Useful for the "temporary guest" access we grant to logged-in users.
1188 * This is useful for enrol plugins only.
1190 * @since 2.2
1191 * @param context_course $coursecontext
1192 * @param int $roleid
1193 * @return void
1195 function load_temp_course_role(context_course $coursecontext, $roleid) {
1196 global $USER, $SITE;
1198 if (empty($roleid)) {
1199 debugging('invalid role specified in load_temp_course_role()');
1200 return;
1203 if ($coursecontext->instanceid == $SITE->id) {
1204 debugging('Can not use temp roles on the frontpage');
1205 return;
1208 if (!isset($USER->access)) {
1209 load_all_capabilities();
1212 $coursecontext->reload_if_dirty();
1214 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1215 return;
1218 // load course stuff first
1219 load_course_context($USER->id, $coursecontext, $USER->access);
1221 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1223 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1227 * Removes any extra guest roles from current USER->access array.
1228 * This is useful for enrol plugins only.
1230 * @since 2.2
1231 * @param context_course $coursecontext
1232 * @return void
1234 function remove_temp_course_roles(context_course $coursecontext) {
1235 global $DB, $USER, $SITE;
1237 if ($coursecontext->instanceid == $SITE->id) {
1238 debugging('Can not use temp roles on the frontpage');
1239 return;
1242 if (empty($USER->access['ra'][$coursecontext->path])) {
1243 //no roles here, weird
1244 return;
1247 $sql = "SELECT DISTINCT ra.roleid AS id
1248 FROM {role_assignments} ra
1249 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1250 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1252 $USER->access['ra'][$coursecontext->path] = array();
1253 foreach($ras as $r) {
1254 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1259 * Returns array of all role archetypes.
1261 * @return array
1263 function get_role_archetypes() {
1264 return array(
1265 'manager' => 'manager',
1266 'coursecreator' => 'coursecreator',
1267 'editingteacher' => 'editingteacher',
1268 'teacher' => 'teacher',
1269 'student' => 'student',
1270 'guest' => 'guest',
1271 'user' => 'user',
1272 'frontpage' => 'frontpage'
1277 * Assign the defaults found in this capability definition to roles that have
1278 * the corresponding legacy capabilities assigned to them.
1280 * @param string $capability
1281 * @param array $legacyperms an array in the format (example):
1282 * 'guest' => CAP_PREVENT,
1283 * 'student' => CAP_ALLOW,
1284 * 'teacher' => CAP_ALLOW,
1285 * 'editingteacher' => CAP_ALLOW,
1286 * 'coursecreator' => CAP_ALLOW,
1287 * 'manager' => CAP_ALLOW
1288 * @return boolean success or failure.
1290 function assign_legacy_capabilities($capability, $legacyperms) {
1292 $archetypes = get_role_archetypes();
1294 foreach ($legacyperms as $type => $perm) {
1296 $systemcontext = context_system::instance();
1297 if ($type === 'admin') {
1298 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1299 $type = 'manager';
1302 if (!array_key_exists($type, $archetypes)) {
1303 print_error('invalidlegacy', '', '', $type);
1306 if ($roles = get_archetype_roles($type)) {
1307 foreach ($roles as $role) {
1308 // Assign a site level capability.
1309 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1310 return false;
1315 return true;
1319 * Verify capability risks.
1321 * @param stdClass $capability a capability - a row from the capabilities table.
1322 * @return boolean whether this capability is safe - that is, whether people with the
1323 * safeoverrides capability should be allowed to change it.
1325 function is_safe_capability($capability) {
1326 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1330 * Get the local override (if any) for a given capability in a role in a context
1332 * @param int $roleid
1333 * @param int $contextid
1334 * @param string $capability
1335 * @return stdClass local capability override
1337 function get_local_override($roleid, $contextid, $capability) {
1338 global $DB;
1339 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1343 * Returns context instance plus related course and cm instances
1345 * @param int $contextid
1346 * @return array of ($context, $course, $cm)
1348 function get_context_info_array($contextid) {
1349 global $DB;
1351 $context = context::instance_by_id($contextid, MUST_EXIST);
1352 $course = null;
1353 $cm = null;
1355 if ($context->contextlevel == CONTEXT_COURSE) {
1356 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1358 } else if ($context->contextlevel == CONTEXT_MODULE) {
1359 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1360 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1362 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1363 $parent = $context->get_parent_context();
1365 if ($parent->contextlevel == CONTEXT_COURSE) {
1366 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1367 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1368 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1369 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1373 return array($context, $course, $cm);
1377 * Function that creates a role
1379 * @param string $name role name
1380 * @param string $shortname role short name
1381 * @param string $description role description
1382 * @param string $archetype
1383 * @return int id or dml_exception
1385 function create_role($name, $shortname, $description, $archetype = '') {
1386 global $DB;
1388 if (strpos($archetype, 'moodle/legacy:') !== false) {
1389 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1392 // verify role archetype actually exists
1393 $archetypes = get_role_archetypes();
1394 if (empty($archetypes[$archetype])) {
1395 $archetype = '';
1398 // Insert the role record.
1399 $role = new stdClass();
1400 $role->name = $name;
1401 $role->shortname = $shortname;
1402 $role->description = $description;
1403 $role->archetype = $archetype;
1405 //find free sortorder number
1406 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1407 if (empty($role->sortorder)) {
1408 $role->sortorder = 1;
1410 $id = $DB->insert_record('role', $role);
1412 return $id;
1416 * Function that deletes a role and cleanups up after it
1418 * @param int $roleid id of role to delete
1419 * @return bool always true
1421 function delete_role($roleid) {
1422 global $DB;
1424 // first unssign all users
1425 role_unassign_all(array('roleid'=>$roleid));
1427 // cleanup all references to this role, ignore errors
1428 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1429 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1430 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1431 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1432 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1433 $DB->delete_records('role_names', array('roleid'=>$roleid));
1434 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1436 // finally delete the role itself
1437 // get this before the name is gone for logging
1438 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
1440 $DB->delete_records('role', array('id'=>$roleid));
1442 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
1444 return true;
1448 * Function to write context specific overrides, or default capabilities.
1450 * NOTE: use $context->mark_dirty() after this
1452 * @param string $capability string name
1453 * @param int $permission CAP_ constants
1454 * @param int $roleid role id
1455 * @param int|context $contextid context id
1456 * @param bool $overwrite
1457 * @return bool always true or exception
1459 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1460 global $USER, $DB;
1462 if ($contextid instanceof context) {
1463 $context = $contextid;
1464 } else {
1465 $context = context::instance_by_id($contextid);
1468 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1469 unassign_capability($capability, $roleid, $context->id);
1470 return true;
1473 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1475 if ($existing and !$overwrite) { // We want to keep whatever is there already
1476 return true;
1479 $cap = new stdClass();
1480 $cap->contextid = $context->id;
1481 $cap->roleid = $roleid;
1482 $cap->capability = $capability;
1483 $cap->permission = $permission;
1484 $cap->timemodified = time();
1485 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1487 if ($existing) {
1488 $cap->id = $existing->id;
1489 $DB->update_record('role_capabilities', $cap);
1490 } else {
1491 if ($DB->record_exists('context', array('id'=>$context->id))) {
1492 $DB->insert_record('role_capabilities', $cap);
1495 return true;
1499 * Unassign a capability from a role.
1501 * NOTE: use $context->mark_dirty() after this
1503 * @param string $capability the name of the capability
1504 * @param int $roleid the role id
1505 * @param int|context $contextid null means all contexts
1506 * @return boolean true or exception
1508 function unassign_capability($capability, $roleid, $contextid = null) {
1509 global $DB;
1511 if (!empty($contextid)) {
1512 if ($contextid instanceof context) {
1513 $context = $contextid;
1514 } else {
1515 $context = context::instance_by_id($contextid);
1517 // delete from context rel, if this is the last override in this context
1518 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1519 } else {
1520 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1522 return true;
1526 * Get the roles that have a given capability assigned to it
1528 * This function does not resolve the actual permission of the capability.
1529 * It just checks for permissions and overrides.
1530 * Use get_roles_with_cap_in_context() if resolution is required.
1532 * @param string $capability capability name (string)
1533 * @param string $permission optional, the permission defined for this capability
1534 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1535 * @param stdClass $context null means any
1536 * @return array of role records
1538 function get_roles_with_capability($capability, $permission = null, $context = null) {
1539 global $DB;
1541 if ($context) {
1542 $contexts = $context->get_parent_context_ids(true);
1543 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1544 $contextsql = "AND rc.contextid $insql";
1545 } else {
1546 $params = array();
1547 $contextsql = '';
1550 if ($permission) {
1551 $permissionsql = " AND rc.permission = :permission";
1552 $params['permission'] = $permission;
1553 } else {
1554 $permissionsql = '';
1557 $sql = "SELECT r.*
1558 FROM {role} r
1559 WHERE r.id IN (SELECT rc.roleid
1560 FROM {role_capabilities} rc
1561 WHERE rc.capability = :capname
1562 $contextsql
1563 $permissionsql)";
1564 $params['capname'] = $capability;
1567 return $DB->get_records_sql($sql, $params);
1571 * This function makes a role-assignment (a role for a user in a particular context)
1573 * @param int $roleid the role of the id
1574 * @param int $userid userid
1575 * @param int|context $contextid id of the context
1576 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1577 * @param int $itemid id of enrolment/auth plugin
1578 * @param string $timemodified defaults to current time
1579 * @return int new/existing id of the assignment
1581 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1582 global $USER, $DB;
1584 // first of all detect if somebody is using old style parameters
1585 if ($contextid === 0 or is_numeric($component)) {
1586 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1589 // now validate all parameters
1590 if (empty($roleid)) {
1591 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1594 if (empty($userid)) {
1595 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1598 if ($itemid) {
1599 if (strpos($component, '_') === false) {
1600 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1602 } else {
1603 $itemid = 0;
1604 if ($component !== '' and strpos($component, '_') === false) {
1605 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1609 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1610 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1613 if ($contextid instanceof context) {
1614 $context = $contextid;
1615 } else {
1616 $context = context::instance_by_id($contextid, MUST_EXIST);
1619 if (!$timemodified) {
1620 $timemodified = time();
1623 // Check for existing entry
1624 // TODO: Revisit this sql_empty() use once Oracle bindings are improved. MDL-29765
1625 $component = ($component === '') ? $DB->sql_empty() : $component;
1626 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1628 if ($ras) {
1629 // role already assigned - this should not happen
1630 if (count($ras) > 1) {
1631 // very weird - remove all duplicates!
1632 $ra = array_shift($ras);
1633 foreach ($ras as $r) {
1634 $DB->delete_records('role_assignments', array('id'=>$r->id));
1636 } else {
1637 $ra = reset($ras);
1640 // actually there is no need to update, reset anything or trigger any event, so just return
1641 return $ra->id;
1644 // Create a new entry
1645 $ra = new stdClass();
1646 $ra->roleid = $roleid;
1647 $ra->contextid = $context->id;
1648 $ra->userid = $userid;
1649 $ra->component = $component;
1650 $ra->itemid = $itemid;
1651 $ra->timemodified = $timemodified;
1652 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1654 $ra->id = $DB->insert_record('role_assignments', $ra);
1656 // mark context as dirty - again expensive, but needed
1657 $context->mark_dirty();
1659 if (!empty($USER->id) && $USER->id == $userid) {
1660 // If the user is the current user, then do full reload of capabilities too.
1661 reload_all_capabilities();
1664 events_trigger('role_assigned', $ra);
1666 return $ra->id;
1670 * Removes one role assignment
1672 * @param int $roleid
1673 * @param int $userid
1674 * @param int|context $contextid
1675 * @param string $component
1676 * @param int $itemid
1677 * @return void
1679 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1680 // first make sure the params make sense
1681 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1682 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1685 if ($itemid) {
1686 if (strpos($component, '_') === false) {
1687 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1689 } else {
1690 $itemid = 0;
1691 if ($component !== '' and strpos($component, '_') === false) {
1692 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1696 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1700 * Removes multiple role assignments, parameters may contain:
1701 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1703 * @param array $params role assignment parameters
1704 * @param bool $subcontexts unassign in subcontexts too
1705 * @param bool $includemanual include manual role assignments too
1706 * @return void
1708 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1709 global $USER, $CFG, $DB;
1711 if (!$params) {
1712 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1715 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1716 foreach ($params as $key=>$value) {
1717 if (!in_array($key, $allowed)) {
1718 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1722 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1723 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1726 if ($includemanual) {
1727 if (!isset($params['component']) or $params['component'] === '') {
1728 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1732 if ($subcontexts) {
1733 if (empty($params['contextid'])) {
1734 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1738 // TODO: Revisit this sql_empty() use once Oracle bindings are improved. MDL-29765
1739 if (isset($params['component'])) {
1740 $params['component'] = ($params['component'] === '') ? $DB->sql_empty() : $params['component'];
1742 $ras = $DB->get_records('role_assignments', $params);
1743 foreach($ras as $ra) {
1744 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1745 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1746 // this is a bit expensive but necessary
1747 $context->mark_dirty();
1748 // If the user is the current user, then do full reload of capabilities too.
1749 if (!empty($USER->id) && $USER->id == $ra->userid) {
1750 reload_all_capabilities();
1753 events_trigger('role_unassigned', $ra);
1755 unset($ras);
1757 // process subcontexts
1758 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1759 if ($params['contextid'] instanceof context) {
1760 $context = $params['contextid'];
1761 } else {
1762 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1765 if ($context) {
1766 $contexts = $context->get_child_contexts();
1767 $mparams = $params;
1768 foreach($contexts as $context) {
1769 $mparams['contextid'] = $context->id;
1770 $ras = $DB->get_records('role_assignments', $mparams);
1771 foreach($ras as $ra) {
1772 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1773 // this is a bit expensive but necessary
1774 $context->mark_dirty();
1775 // If the user is the current user, then do full reload of capabilities too.
1776 if (!empty($USER->id) && $USER->id == $ra->userid) {
1777 reload_all_capabilities();
1779 events_trigger('role_unassigned', $ra);
1785 // do this once more for all manual role assignments
1786 if ($includemanual) {
1787 $params['component'] = '';
1788 role_unassign_all($params, $subcontexts, false);
1793 * Determines if a user is currently logged in
1795 * @category access
1797 * @return bool
1799 function isloggedin() {
1800 global $USER;
1802 return (!empty($USER->id));
1806 * Determines if a user is logged in as real guest user with username 'guest'.
1808 * @category access
1810 * @param int|object $user mixed user object or id, $USER if not specified
1811 * @return bool true if user is the real guest user, false if not logged in or other user
1813 function isguestuser($user = null) {
1814 global $USER, $DB, $CFG;
1816 // make sure we have the user id cached in config table, because we are going to use it a lot
1817 if (empty($CFG->siteguest)) {
1818 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1819 // guest does not exist yet, weird
1820 return false;
1822 set_config('siteguest', $guestid);
1824 if ($user === null) {
1825 $user = $USER;
1828 if ($user === null) {
1829 // happens when setting the $USER
1830 return false;
1832 } else if (is_numeric($user)) {
1833 return ($CFG->siteguest == $user);
1835 } else if (is_object($user)) {
1836 if (empty($user->id)) {
1837 return false; // not logged in means is not be guest
1838 } else {
1839 return ($CFG->siteguest == $user->id);
1842 } else {
1843 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1848 * Does user have a (temporary or real) guest access to course?
1850 * @category access
1852 * @param context $context
1853 * @param stdClass|int $user
1854 * @return bool
1856 function is_guest(context $context, $user = null) {
1857 global $USER;
1859 // first find the course context
1860 $coursecontext = $context->get_course_context();
1862 // make sure there is a real user specified
1863 if ($user === null) {
1864 $userid = isset($USER->id) ? $USER->id : 0;
1865 } else {
1866 $userid = is_object($user) ? $user->id : $user;
1869 if (isguestuser($userid)) {
1870 // can not inspect or be enrolled
1871 return true;
1874 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1875 // viewing users appear out of nowhere, they are neither guests nor participants
1876 return false;
1879 // consider only real active enrolments here
1880 if (is_enrolled($coursecontext, $user, '', true)) {
1881 return false;
1884 return true;
1888 * Returns true if the user has moodle/course:view capability in the course,
1889 * this is intended for admins, managers (aka small admins), inspectors, etc.
1891 * @category access
1893 * @param context $context
1894 * @param int|stdClass $user if null $USER is used
1895 * @param string $withcapability extra capability name
1896 * @return bool
1898 function is_viewing(context $context, $user = null, $withcapability = '') {
1899 // first find the course context
1900 $coursecontext = $context->get_course_context();
1902 if (isguestuser($user)) {
1903 // can not inspect
1904 return false;
1907 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1908 // admins are allowed to inspect courses
1909 return false;
1912 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1913 // site admins always have the capability, but the enrolment above blocks
1914 return false;
1917 return true;
1921 * Returns true if user is enrolled (is participating) in course
1922 * this is intended for students and teachers.
1924 * Since 2.2 the result for active enrolments and current user are cached.
1926 * @package core_enrol
1927 * @category access
1929 * @param context $context
1930 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
1931 * @param string $withcapability extra capability name
1932 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1933 * @return bool
1935 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1936 global $USER, $DB;
1938 // first find the course context
1939 $coursecontext = $context->get_course_context();
1941 // make sure there is a real user specified
1942 if ($user === null) {
1943 $userid = isset($USER->id) ? $USER->id : 0;
1944 } else {
1945 $userid = is_object($user) ? $user->id : $user;
1948 if (empty($userid)) {
1949 // not-logged-in!
1950 return false;
1951 } else if (isguestuser($userid)) {
1952 // guest account can not be enrolled anywhere
1953 return false;
1956 if ($coursecontext->instanceid == SITEID) {
1957 // everybody participates on frontpage
1958 } else {
1959 // try cached info first - the enrolled flag is set only when active enrolment present
1960 if ($USER->id == $userid) {
1961 $coursecontext->reload_if_dirty();
1962 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1963 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1964 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1965 return false;
1967 return true;
1972 if ($onlyactive) {
1973 // look for active enrolments only
1974 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1976 if ($until === false) {
1977 return false;
1980 if ($USER->id == $userid) {
1981 if ($until == 0) {
1982 $until = ENROL_MAX_TIMESTAMP;
1984 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1985 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1986 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1987 remove_temp_course_roles($coursecontext);
1991 } else {
1992 // any enrolment is good for us here, even outdated, disabled or inactive
1993 $sql = "SELECT 'x'
1994 FROM {user_enrolments} ue
1995 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1996 JOIN {user} u ON u.id = ue.userid
1997 WHERE ue.userid = :userid AND u.deleted = 0";
1998 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
1999 if (!$DB->record_exists_sql($sql, $params)) {
2000 return false;
2005 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2006 return false;
2009 return true;
2013 * Returns true if the user is able to access the course.
2015 * This function is in no way, shape, or form a substitute for require_login.
2016 * It should only be used in circumstances where it is not possible to call require_login
2017 * such as the navigation.
2019 * This function checks many of the methods of access to a course such as the view
2020 * capability, enrollments, and guest access. It also makes use of the cache
2021 * generated by require_login for guest access.
2023 * The flags within the $USER object that are used here should NEVER be used outside
2024 * of this function can_access_course and require_login. Doing so WILL break future
2025 * versions.
2027 * @param stdClass $course record
2028 * @param stdClass|int|null $user user record or id, current user if null
2029 * @param string $withcapability Check for this capability as well.
2030 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2031 * @return boolean Returns true if the user is able to access the course
2033 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
2034 global $DB, $USER;
2036 // this function originally accepted $coursecontext parameter
2037 if ($course instanceof context) {
2038 if ($course instanceof context_course) {
2039 debugging('deprecated context parameter, please use $course record');
2040 $coursecontext = $course;
2041 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2042 } else {
2043 debugging('Invalid context parameter, please use $course record');
2044 return false;
2046 } else {
2047 $coursecontext = context_course::instance($course->id);
2050 if (!isset($USER->id)) {
2051 // should never happen
2052 $USER->id = 0;
2055 // make sure there is a user specified
2056 if ($user === null) {
2057 $userid = $USER->id;
2058 } else {
2059 $userid = is_object($user) ? $user->id : $user;
2061 unset($user);
2063 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2064 return false;
2067 if ($userid == $USER->id) {
2068 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2069 // the fact that somebody switched role means they can access the course no matter to what role they switched
2070 return true;
2074 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2075 return false;
2078 if (is_viewing($coursecontext, $userid)) {
2079 return true;
2082 if ($userid != $USER->id) {
2083 // for performance reasons we do not verify temporary guest access for other users, sorry...
2084 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2087 // === from here we deal only with $USER ===
2089 $coursecontext->reload_if_dirty();
2091 if (isset($USER->enrol['enrolled'][$course->id])) {
2092 if ($USER->enrol['enrolled'][$course->id] > time()) {
2093 return true;
2096 if (isset($USER->enrol['tempguest'][$course->id])) {
2097 if ($USER->enrol['tempguest'][$course->id] > time()) {
2098 return true;
2102 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2103 return true;
2106 // if not enrolled try to gain temporary guest access
2107 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2108 $enrols = enrol_get_plugins(true);
2109 foreach($instances as $instance) {
2110 if (!isset($enrols[$instance->enrol])) {
2111 continue;
2113 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2114 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2115 if ($until !== false and $until > time()) {
2116 $USER->enrol['tempguest'][$course->id] = $until;
2117 return true;
2120 if (isset($USER->enrol['tempguest'][$course->id])) {
2121 unset($USER->enrol['tempguest'][$course->id]);
2122 remove_temp_course_roles($coursecontext);
2125 return false;
2129 * Returns array with sql code and parameters returning all ids
2130 * of users enrolled into course.
2132 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2134 * @package core_enrol
2135 * @category access
2137 * @param context $context
2138 * @param string $withcapability
2139 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2140 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2141 * @return array list($sql, $params)
2143 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2144 global $DB, $CFG;
2146 // use unique prefix just in case somebody makes some SQL magic with the result
2147 static $i = 0;
2148 $i++;
2149 $prefix = 'eu'.$i.'_';
2151 // first find the course context
2152 $coursecontext = $context->get_course_context();
2154 $isfrontpage = ($coursecontext->instanceid == SITEID);
2156 $joins = array();
2157 $wheres = array();
2158 $params = array();
2160 list($contextids, $contextpaths) = get_context_info_list($context);
2162 // get all relevant capability info for all roles
2163 if ($withcapability) {
2164 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2165 $cparams['cap'] = $withcapability;
2167 $defs = array();
2168 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2169 FROM {role_capabilities} rc
2170 JOIN {context} ctx on rc.contextid = ctx.id
2171 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2172 $rcs = $DB->get_records_sql($sql, $cparams);
2173 foreach ($rcs as $rc) {
2174 $defs[$rc->path][$rc->roleid] = $rc->permission;
2177 $access = array();
2178 if (!empty($defs)) {
2179 foreach ($contextpaths as $path) {
2180 if (empty($defs[$path])) {
2181 continue;
2183 foreach($defs[$path] as $roleid => $perm) {
2184 if ($perm == CAP_PROHIBIT) {
2185 $access[$roleid] = CAP_PROHIBIT;
2186 continue;
2188 if (!isset($access[$roleid])) {
2189 $access[$roleid] = (int)$perm;
2195 unset($defs);
2197 // make lists of roles that are needed and prohibited
2198 $needed = array(); // one of these is enough
2199 $prohibited = array(); // must not have any of these
2200 foreach ($access as $roleid => $perm) {
2201 if ($perm == CAP_PROHIBIT) {
2202 unset($needed[$roleid]);
2203 $prohibited[$roleid] = true;
2204 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2205 $needed[$roleid] = true;
2209 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2210 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2212 $nobody = false;
2214 if ($isfrontpage) {
2215 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2216 $nobody = true;
2217 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2218 // everybody not having prohibit has the capability
2219 $needed = array();
2220 } else if (empty($needed)) {
2221 $nobody = true;
2223 } else {
2224 if (!empty($prohibited[$defaultuserroleid])) {
2225 $nobody = true;
2226 } else if (!empty($needed[$defaultuserroleid])) {
2227 // everybody not having prohibit has the capability
2228 $needed = array();
2229 } else if (empty($needed)) {
2230 $nobody = true;
2234 if ($nobody) {
2235 // nobody can match so return some SQL that does not return any results
2236 $wheres[] = "1 = 2";
2238 } else {
2240 if ($needed) {
2241 $ctxids = implode(',', $contextids);
2242 $roleids = implode(',', array_keys($needed));
2243 $joins[] = "JOIN {role_assignments} {$prefix}ra3 ON ({$prefix}ra3.userid = {$prefix}u.id AND {$prefix}ra3.roleid IN ($roleids) AND {$prefix}ra3.contextid IN ($ctxids))";
2246 if ($prohibited) {
2247 $ctxids = implode(',', $contextids);
2248 $roleids = implode(',', array_keys($prohibited));
2249 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4 ON ({$prefix}ra4.userid = {$prefix}u.id AND {$prefix}ra4.roleid IN ($roleids) AND {$prefix}ra4.contextid IN ($ctxids))";
2250 $wheres[] = "{$prefix}ra4.id IS NULL";
2253 if ($groupid) {
2254 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2255 $params["{$prefix}gmid"] = $groupid;
2259 } else {
2260 if ($groupid) {
2261 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2262 $params["{$prefix}gmid"] = $groupid;
2266 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2267 $params["{$prefix}guestid"] = $CFG->siteguest;
2269 if ($isfrontpage) {
2270 // all users are "enrolled" on the frontpage
2271 } else {
2272 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2273 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2274 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2276 if ($onlyactive) {
2277 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2278 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2279 $now = round(time(), -2); // rounding helps caching in DB
2280 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2281 $prefix.'active'=>ENROL_USER_ACTIVE,
2282 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2286 $joins = implode("\n", $joins);
2287 $wheres = "WHERE ".implode(" AND ", $wheres);
2289 $sql = "SELECT DISTINCT {$prefix}u.id
2290 FROM {user} {$prefix}u
2291 $joins
2292 $wheres";
2294 return array($sql, $params);
2298 * Returns list of users enrolled into course.
2300 * @package core_enrol
2301 * @category access
2303 * @param context $context
2304 * @param string $withcapability
2305 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2306 * @param string $userfields requested user record fields
2307 * @param string $orderby
2308 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2309 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2310 * @return array of user records
2312 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null, $limitfrom = 0, $limitnum = 0) {
2313 global $DB;
2315 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2316 $sql = "SELECT $userfields
2317 FROM {user} u
2318 JOIN ($esql) je ON je.id = u.id
2319 WHERE u.deleted = 0";
2321 if ($orderby) {
2322 $sql = "$sql ORDER BY $orderby";
2323 } else {
2324 list($sort, $sortparams) = users_order_by_sql('u');
2325 $sql = "$sql ORDER BY $sort";
2326 $params = array_merge($params, $sortparams);
2329 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2333 * Counts list of users enrolled into course (as per above function)
2335 * @package core_enrol
2336 * @category access
2338 * @param context $context
2339 * @param string $withcapability
2340 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2341 * @return array of user records
2343 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0) {
2344 global $DB;
2346 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2347 $sql = "SELECT count(u.id)
2348 FROM {user} u
2349 JOIN ($esql) je ON je.id = u.id
2350 WHERE u.deleted = 0";
2352 return $DB->count_records_sql($sql, $params);
2356 * Loads the capability definitions for the component (from file).
2358 * Loads the capability definitions for the component (from file). If no
2359 * capabilities are defined for the component, we simply return an empty array.
2361 * @access private
2362 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2363 * @return array array of capabilities
2365 function load_capability_def($component) {
2366 $defpath = get_component_directory($component).'/db/access.php';
2368 $capabilities = array();
2369 if (file_exists($defpath)) {
2370 require($defpath);
2371 if (!empty(${$component.'_capabilities'})) {
2372 // BC capability array name
2373 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2374 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2375 $capabilities = ${$component.'_capabilities'};
2379 return $capabilities;
2383 * Gets the capabilities that have been cached in the database for this component.
2385 * @access private
2386 * @param string $component - examples: 'moodle', 'mod_forum'
2387 * @return array array of capabilities
2389 function get_cached_capabilities($component = 'moodle') {
2390 global $DB;
2391 return $DB->get_records('capabilities', array('component'=>$component));
2395 * Returns default capabilities for given role archetype.
2397 * @param string $archetype role archetype
2398 * @return array
2400 function get_default_capabilities($archetype) {
2401 global $DB;
2403 if (!$archetype) {
2404 return array();
2407 $alldefs = array();
2408 $defaults = array();
2409 $components = array();
2410 $allcaps = $DB->get_records('capabilities');
2412 foreach ($allcaps as $cap) {
2413 if (!in_array($cap->component, $components)) {
2414 $components[] = $cap->component;
2415 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2418 foreach($alldefs as $name=>$def) {
2419 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2420 if (isset($def['archetypes'])) {
2421 if (isset($def['archetypes'][$archetype])) {
2422 $defaults[$name] = $def['archetypes'][$archetype];
2424 // 'legacy' is for backward compatibility with 1.9 access.php
2425 } else {
2426 if (isset($def['legacy'][$archetype])) {
2427 $defaults[$name] = $def['legacy'][$archetype];
2432 return $defaults;
2436 * Reset role capabilities to default according to selected role archetype.
2437 * If no archetype selected, removes all capabilities.
2439 * @param int $roleid
2440 * @return void
2442 function reset_role_capabilities($roleid) {
2443 global $DB;
2445 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2446 $defaultcaps = get_default_capabilities($role->archetype);
2448 $systemcontext = context_system::instance();
2450 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2452 foreach($defaultcaps as $cap=>$permission) {
2453 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2458 * Updates the capabilities table with the component capability definitions.
2459 * If no parameters are given, the function updates the core moodle
2460 * capabilities.
2462 * Note that the absence of the db/access.php capabilities definition file
2463 * will cause any stored capabilities for the component to be removed from
2464 * the database.
2466 * @access private
2467 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2468 * @return boolean true if success, exception in case of any problems
2470 function update_capabilities($component = 'moodle') {
2471 global $DB, $OUTPUT;
2473 $storedcaps = array();
2475 $filecaps = load_capability_def($component);
2476 foreach($filecaps as $capname=>$unused) {
2477 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2478 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2482 $cachedcaps = get_cached_capabilities($component);
2483 if ($cachedcaps) {
2484 foreach ($cachedcaps as $cachedcap) {
2485 array_push($storedcaps, $cachedcap->name);
2486 // update risk bitmasks and context levels in existing capabilities if needed
2487 if (array_key_exists($cachedcap->name, $filecaps)) {
2488 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2489 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2491 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2492 $updatecap = new stdClass();
2493 $updatecap->id = $cachedcap->id;
2494 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2495 $DB->update_record('capabilities', $updatecap);
2497 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2498 $updatecap = new stdClass();
2499 $updatecap->id = $cachedcap->id;
2500 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2501 $DB->update_record('capabilities', $updatecap);
2504 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2505 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2507 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2508 $updatecap = new stdClass();
2509 $updatecap->id = $cachedcap->id;
2510 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2511 $DB->update_record('capabilities', $updatecap);
2517 // Are there new capabilities in the file definition?
2518 $newcaps = array();
2520 foreach ($filecaps as $filecap => $def) {
2521 if (!$storedcaps ||
2522 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2523 if (!array_key_exists('riskbitmask', $def)) {
2524 $def['riskbitmask'] = 0; // no risk if not specified
2526 $newcaps[$filecap] = $def;
2529 // Add new capabilities to the stored definition.
2530 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
2531 foreach ($newcaps as $capname => $capdef) {
2532 $capability = new stdClass();
2533 $capability->name = $capname;
2534 $capability->captype = $capdef['captype'];
2535 $capability->contextlevel = $capdef['contextlevel'];
2536 $capability->component = $component;
2537 $capability->riskbitmask = $capdef['riskbitmask'];
2539 $DB->insert_record('capabilities', $capability, false);
2541 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
2542 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2543 foreach ($rolecapabilities as $rolecapability){
2544 //assign_capability will update rather than insert if capability exists
2545 if (!assign_capability($capname, $rolecapability->permission,
2546 $rolecapability->roleid, $rolecapability->contextid, true)){
2547 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2551 // we ignore archetype key if we have cloned permissions
2552 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2553 assign_legacy_capabilities($capname, $capdef['archetypes']);
2554 // 'legacy' is for backward compatibility with 1.9 access.php
2555 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2556 assign_legacy_capabilities($capname, $capdef['legacy']);
2559 // Are there any capabilities that have been removed from the file
2560 // definition that we need to delete from the stored capabilities and
2561 // role assignments?
2562 capabilities_cleanup($component, $filecaps);
2564 // reset static caches
2565 accesslib_clear_all_caches(false);
2567 return true;
2571 * Deletes cached capabilities that are no longer needed by the component.
2572 * Also unassigns these capabilities from any roles that have them.
2574 * @access private
2575 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2576 * @param array $newcapdef array of the new capability definitions that will be
2577 * compared with the cached capabilities
2578 * @return int number of deprecated capabilities that have been removed
2580 function capabilities_cleanup($component, $newcapdef = null) {
2581 global $DB;
2583 $removedcount = 0;
2585 if ($cachedcaps = get_cached_capabilities($component)) {
2586 foreach ($cachedcaps as $cachedcap) {
2587 if (empty($newcapdef) ||
2588 array_key_exists($cachedcap->name, $newcapdef) === false) {
2590 // Remove from capabilities cache.
2591 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2592 $removedcount++;
2593 // Delete from roles.
2594 if ($roles = get_roles_with_capability($cachedcap->name)) {
2595 foreach($roles as $role) {
2596 if (!unassign_capability($cachedcap->name, $role->id)) {
2597 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2601 } // End if.
2604 return $removedcount;
2608 * Returns an array of all the known types of risk
2609 * The array keys can be used, for example as CSS class names, or in calls to
2610 * print_risk_icon. The values are the corresponding RISK_ constants.
2612 * @return array all the known types of risk.
2614 function get_all_risks() {
2615 return array(
2616 'riskmanagetrust' => RISK_MANAGETRUST,
2617 'riskconfig' => RISK_CONFIG,
2618 'riskxss' => RISK_XSS,
2619 'riskpersonal' => RISK_PERSONAL,
2620 'riskspam' => RISK_SPAM,
2621 'riskdataloss' => RISK_DATALOSS,
2626 * Return a link to moodle docs for a given capability name
2628 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
2629 * @return string the human-readable capability name as a link to Moodle Docs.
2631 function get_capability_docs_link($capability) {
2632 $url = get_docs_url('Capabilities/' . $capability->name);
2633 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2637 * This function pulls out all the resolved capabilities (overrides and
2638 * defaults) of a role used in capability overrides in contexts at a given
2639 * context.
2641 * @param int $roleid
2642 * @param context $context
2643 * @param string $cap capability, optional, defaults to ''
2644 * @return array Array of capabilities
2646 function role_context_capabilities($roleid, context $context, $cap = '') {
2647 global $DB;
2649 $contexts = $context->get_parent_context_ids(true);
2650 $contexts = '('.implode(',', $contexts).')';
2652 $params = array($roleid);
2654 if ($cap) {
2655 $search = " AND rc.capability = ? ";
2656 $params[] = $cap;
2657 } else {
2658 $search = '';
2661 $sql = "SELECT rc.*
2662 FROM {role_capabilities} rc, {context} c
2663 WHERE rc.contextid in $contexts
2664 AND rc.roleid = ?
2665 AND rc.contextid = c.id $search
2666 ORDER BY c.contextlevel DESC, rc.capability DESC";
2668 $capabilities = array();
2670 if ($records = $DB->get_records_sql($sql, $params)) {
2671 // We are traversing via reverse order.
2672 foreach ($records as $record) {
2673 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2674 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2675 $capabilities[$record->capability] = $record->permission;
2679 return $capabilities;
2683 * Constructs array with contextids as first parameter and context paths,
2684 * in both cases bottom top including self.
2686 * @access private
2687 * @param context $context
2688 * @return array
2690 function get_context_info_list(context $context) {
2691 $contextids = explode('/', ltrim($context->path, '/'));
2692 $contextpaths = array();
2693 $contextids2 = $contextids;
2694 while ($contextids2) {
2695 $contextpaths[] = '/' . implode('/', $contextids2);
2696 array_pop($contextids2);
2698 return array($contextids, $contextpaths);
2702 * Check if context is the front page context or a context inside it
2704 * Returns true if this context is the front page context, or a context inside it,
2705 * otherwise false.
2707 * @param context $context a context object.
2708 * @return bool
2710 function is_inside_frontpage(context $context) {
2711 $frontpagecontext = context_course::instance(SITEID);
2712 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2716 * Returns capability information (cached)
2718 * @param string $capabilityname
2719 * @return stdClass or null if capability not found
2721 function get_capability_info($capabilityname) {
2722 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2724 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2726 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2727 $ACCESSLIB_PRIVATE->capabilities = array();
2728 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2729 foreach ($caps as $cap) {
2730 $capname = $cap->name;
2731 unset($cap->id);
2732 unset($cap->name);
2733 $cap->riskbitmask = (int)$cap->riskbitmask;
2734 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2738 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2742 * Returns the human-readable, translated version of the capability.
2743 * Basically a big switch statement.
2745 * @param string $capabilityname e.g. mod/choice:readresponses
2746 * @return string
2748 function get_capability_string($capabilityname) {
2750 // Typical capability name is 'plugintype/pluginname:capabilityname'
2751 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2753 if ($type === 'moodle') {
2754 $component = 'core_role';
2755 } else if ($type === 'quizreport') {
2756 //ugly hack!!
2757 $component = 'quiz_'.$name;
2758 } else {
2759 $component = $type.'_'.$name;
2762 $stringname = $name.':'.$capname;
2764 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2765 return get_string($stringname, $component);
2768 $dir = get_component_directory($component);
2769 if (!file_exists($dir)) {
2770 // plugin broken or does not exist, do not bother with printing of debug message
2771 return $capabilityname.' ???';
2774 // something is wrong in plugin, better print debug
2775 return get_string($stringname, $component);
2779 * This gets the mod/block/course/core etc strings.
2781 * @param string $component
2782 * @param int $contextlevel
2783 * @return string|bool String is success, false if failed
2785 function get_component_string($component, $contextlevel) {
2787 if ($component === 'moodle' or $component === 'core') {
2788 switch ($contextlevel) {
2789 // TODO: this should probably use context level names instead
2790 case CONTEXT_SYSTEM: return get_string('coresystem');
2791 case CONTEXT_USER: return get_string('users');
2792 case CONTEXT_COURSECAT: return get_string('categories');
2793 case CONTEXT_COURSE: return get_string('course');
2794 case CONTEXT_MODULE: return get_string('activities');
2795 case CONTEXT_BLOCK: return get_string('block');
2796 default: print_error('unknowncontext');
2800 list($type, $name) = normalize_component($component);
2801 $dir = get_plugin_directory($type, $name);
2802 if (!file_exists($dir)) {
2803 // plugin not installed, bad luck, there is no way to find the name
2804 return $component.' ???';
2807 switch ($type) {
2808 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2809 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2810 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2811 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2812 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2813 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2814 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2815 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2816 case 'mod':
2817 if (get_string_manager()->string_exists('pluginname', $component)) {
2818 return get_string('activity').': '.get_string('pluginname', $component);
2819 } else {
2820 return get_string('activity').': '.get_string('modulename', $component);
2822 default: return get_string('pluginname', $component);
2827 * Gets the list of roles assigned to this context and up (parents)
2828 * from the list of roles that are visible on user profile page
2829 * and participants page.
2831 * @param context $context
2832 * @return array
2834 function get_profile_roles(context $context) {
2835 global $CFG, $DB;
2837 if (empty($CFG->profileroles)) {
2838 return array();
2841 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2842 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2843 $params = array_merge($params, $cparams);
2845 if ($coursecontext = $context->get_course_context(false)) {
2846 $params['coursecontext'] = $coursecontext->id;
2847 } else {
2848 $params['coursecontext'] = 0;
2851 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2852 FROM {role_assignments} ra, {role} r
2853 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2854 WHERE r.id = ra.roleid
2855 AND ra.contextid $contextlist
2856 AND r.id $rallowed
2857 ORDER BY r.sortorder ASC";
2859 return $DB->get_records_sql($sql, $params);
2863 * Gets the list of roles assigned to this context and up (parents)
2865 * @param context $context
2866 * @return array
2868 function get_roles_used_in_context(context $context) {
2869 global $DB;
2871 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2873 if ($coursecontext = $context->get_course_context(false)) {
2874 $params['coursecontext'] = $coursecontext->id;
2875 } else {
2876 $params['coursecontext'] = 0;
2879 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2880 FROM {role_assignments} ra, {role} r
2881 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2882 WHERE r.id = ra.roleid
2883 AND ra.contextid $contextlist
2884 ORDER BY r.sortorder ASC";
2886 return $DB->get_records_sql($sql, $params);
2890 * This function is used to print roles column in user profile page.
2891 * It is using the CFG->profileroles to limit the list to only interesting roles.
2892 * (The permission tab has full details of user role assignments.)
2894 * @param int $userid
2895 * @param int $courseid
2896 * @return string
2898 function get_user_roles_in_course($userid, $courseid) {
2899 global $CFG, $DB;
2901 if (empty($CFG->profileroles)) {
2902 return '';
2905 if ($courseid == SITEID) {
2906 $context = context_system::instance();
2907 } else {
2908 $context = context_course::instance($courseid);
2911 if (empty($CFG->profileroles)) {
2912 return array();
2915 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2916 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2917 $params = array_merge($params, $cparams);
2919 if ($coursecontext = $context->get_course_context(false)) {
2920 $params['coursecontext'] = $coursecontext->id;
2921 } else {
2922 $params['coursecontext'] = 0;
2925 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
2926 FROM {role_assignments} ra, {role} r
2927 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2928 WHERE r.id = ra.roleid
2929 AND ra.contextid $contextlist
2930 AND r.id $rallowed
2931 AND ra.userid = :userid
2932 ORDER BY r.sortorder ASC";
2933 $params['userid'] = $userid;
2935 $rolestring = '';
2937 if ($roles = $DB->get_records_sql($sql, $params)) {
2938 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
2940 foreach ($rolenames as $roleid => $rolename) {
2941 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
2943 $rolestring = implode(',', $rolenames);
2946 return $rolestring;
2950 * Checks if a user can assign users to a particular role in this context
2952 * @param context $context
2953 * @param int $targetroleid - the id of the role you want to assign users to
2954 * @return boolean
2956 function user_can_assign(context $context, $targetroleid) {
2957 global $DB;
2959 // First check to see if the user is a site administrator.
2960 if (is_siteadmin()) {
2961 return true;
2964 // Check if user has override capability.
2965 // If not return false.
2966 if (!has_capability('moodle/role:assign', $context)) {
2967 return false;
2969 // pull out all active roles of this user from this context(or above)
2970 if ($userroles = get_user_roles($context)) {
2971 foreach ($userroles as $userrole) {
2972 // if any in the role_allow_override table, then it's ok
2973 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2974 return true;
2979 return false;
2983 * Returns all site roles in correct sort order.
2985 * @param context $context optional context for course role name aliases
2986 * @return array of role records with optional coursealias property
2988 function get_all_roles(context $context = null) {
2989 global $DB;
2991 if (!$context or !$coursecontext = $context->get_course_context(false)) {
2992 $coursecontext = null;
2995 if ($coursecontext) {
2996 $sql = "SELECT r.*, rn.name AS coursealias
2997 FROM {role} r
2998 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
2999 ORDER BY r.sortorder ASC";
3000 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
3002 } else {
3003 return $DB->get_records('role', array(), 'sortorder ASC');
3008 * Returns roles of a specified archetype
3010 * @param string $archetype
3011 * @return array of full role records
3013 function get_archetype_roles($archetype) {
3014 global $DB;
3015 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
3019 * Gets all the user roles assigned in this context, or higher contexts
3020 * this is mainly used when checking if a user can assign a role, or overriding a role
3021 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3022 * allow_override tables
3024 * @param context $context
3025 * @param int $userid
3026 * @param bool $checkparentcontexts defaults to true
3027 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3028 * @return array
3030 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3031 global $USER, $DB;
3033 if (empty($userid)) {
3034 if (empty($USER->id)) {
3035 return array();
3037 $userid = $USER->id;
3040 if ($checkparentcontexts) {
3041 $contextids = $context->get_parent_context_ids();
3042 } else {
3043 $contextids = array();
3045 $contextids[] = $context->id;
3047 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3049 array_unshift($params, $userid);
3051 $sql = "SELECT ra.*, r.name, r.shortname
3052 FROM {role_assignments} ra, {role} r, {context} c
3053 WHERE ra.userid = ?
3054 AND ra.roleid = r.id
3055 AND ra.contextid = c.id
3056 AND ra.contextid $contextids
3057 ORDER BY $order";
3059 return $DB->get_records_sql($sql ,$params);
3063 * Like get_user_roles, but adds in the authenticated user role, and the front
3064 * page roles, if applicable.
3066 * @param context $context the context.
3067 * @param int $userid optional. Defaults to $USER->id
3068 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3070 function get_user_roles_with_special(context $context, $userid = 0) {
3071 global $CFG, $USER;
3073 if (empty($userid)) {
3074 if (empty($USER->id)) {
3075 return array();
3077 $userid = $USER->id;
3080 $ras = get_user_roles($context, $userid);
3082 // Add front-page role if relevant.
3083 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3084 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3085 is_inside_frontpage($context);
3086 if ($defaultfrontpageroleid && $isfrontpage) {
3087 $frontpagecontext = context_course::instance(SITEID);
3088 $ra = new stdClass();
3089 $ra->userid = $userid;
3090 $ra->contextid = $frontpagecontext->id;
3091 $ra->roleid = $defaultfrontpageroleid;
3092 $ras[] = $ra;
3095 // Add authenticated user role if relevant.
3096 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3097 if ($defaultuserroleid && !isguestuser($userid)) {
3098 $systemcontext = context_system::instance();
3099 $ra = new stdClass();
3100 $ra->userid = $userid;
3101 $ra->contextid = $systemcontext->id;
3102 $ra->roleid = $defaultuserroleid;
3103 $ras[] = $ra;
3106 return $ras;
3110 * Creates a record in the role_allow_override table
3112 * @param int $sroleid source roleid
3113 * @param int $troleid target roleid
3114 * @return void
3116 function allow_override($sroleid, $troleid) {
3117 global $DB;
3119 $record = new stdClass();
3120 $record->roleid = $sroleid;
3121 $record->allowoverride = $troleid;
3122 $DB->insert_record('role_allow_override', $record);
3126 * Creates a record in the role_allow_assign table
3128 * @param int $fromroleid source roleid
3129 * @param int $targetroleid target roleid
3130 * @return void
3132 function allow_assign($fromroleid, $targetroleid) {
3133 global $DB;
3135 $record = new stdClass();
3136 $record->roleid = $fromroleid;
3137 $record->allowassign = $targetroleid;
3138 $DB->insert_record('role_allow_assign', $record);
3142 * Creates a record in the role_allow_switch table
3144 * @param int $fromroleid source roleid
3145 * @param int $targetroleid target roleid
3146 * @return void
3148 function allow_switch($fromroleid, $targetroleid) {
3149 global $DB;
3151 $record = new stdClass();
3152 $record->roleid = $fromroleid;
3153 $record->allowswitch = $targetroleid;
3154 $DB->insert_record('role_allow_switch', $record);
3158 * Gets a list of roles that this user can assign in this context
3160 * @param context $context the context.
3161 * @param int $rolenamedisplay the type of role name to display. One of the
3162 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3163 * @param bool $withusercounts if true, count the number of users with each role.
3164 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3165 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3166 * if $withusercounts is true, returns a list of three arrays,
3167 * $rolenames, $rolecounts, and $nameswithcounts.
3169 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3170 global $USER, $DB;
3172 // make sure there is a real user specified
3173 if ($user === null) {
3174 $userid = isset($USER->id) ? $USER->id : 0;
3175 } else {
3176 $userid = is_object($user) ? $user->id : $user;
3179 if (!has_capability('moodle/role:assign', $context, $userid)) {
3180 if ($withusercounts) {
3181 return array(array(), array(), array());
3182 } else {
3183 return array();
3187 $params = array();
3188 $extrafields = '';
3190 if ($withusercounts) {
3191 $extrafields = ', (SELECT count(u.id)
3192 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3193 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3194 ) AS usercount';
3195 $params['conid'] = $context->id;
3198 if (is_siteadmin($userid)) {
3199 // show all roles allowed in this context to admins
3200 $assignrestriction = "";
3201 } else {
3202 $parents = $context->get_parent_context_ids(true);
3203 $contexts = implode(',' , $parents);
3204 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3205 FROM {role_allow_assign} raa
3206 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3207 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3208 ) ar ON ar.id = r.id";
3209 $params['userid'] = $userid;
3211 $params['contextlevel'] = $context->contextlevel;
3213 if ($coursecontext = $context->get_course_context(false)) {
3214 $params['coursecontext'] = $coursecontext->id;
3215 } else {
3216 $params['coursecontext'] = 0; // no course aliases
3217 $coursecontext = null;
3219 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
3220 FROM {role} r
3221 $assignrestriction
3222 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3223 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3224 ORDER BY r.sortorder ASC";
3225 $roles = $DB->get_records_sql($sql, $params);
3227 $rolenames = role_fix_names($roles, $coursecontext, $rolenamedisplay, true);
3229 if (!$withusercounts) {
3230 return $rolenames;
3233 $rolecounts = array();
3234 $nameswithcounts = array();
3235 foreach ($roles as $role) {
3236 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3237 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3239 return array($rolenames, $rolecounts, $nameswithcounts);
3243 * Gets a list of roles that this user can switch to in a context
3245 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3246 * This function just process the contents of the role_allow_switch table. You also need to
3247 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3249 * @param context $context a context.
3250 * @return array an array $roleid => $rolename.
3252 function get_switchable_roles(context $context) {
3253 global $USER, $DB;
3255 $params = array();
3256 $extrajoins = '';
3257 $extrawhere = '';
3258 if (!is_siteadmin()) {
3259 // Admins are allowed to switch to any role with.
3260 // Others are subject to the additional constraint that the switch-to role must be allowed by
3261 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3262 $parents = $context->get_parent_context_ids(true);
3263 $contexts = implode(',' , $parents);
3265 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3266 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3267 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3268 $params['userid'] = $USER->id;
3271 if ($coursecontext = $context->get_course_context(false)) {
3272 $params['coursecontext'] = $coursecontext->id;
3273 } else {
3274 $params['coursecontext'] = 0; // no course aliases
3275 $coursecontext = null;
3278 $query = "
3279 SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3280 FROM (SELECT DISTINCT rc.roleid
3281 FROM {role_capabilities} rc
3282 $extrajoins
3283 $extrawhere) idlist
3284 JOIN {role} r ON r.id = idlist.roleid
3285 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3286 ORDER BY r.sortorder";
3287 $roles = $DB->get_records_sql($query, $params);
3289 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
3293 * Gets a list of roles that this user can override in this context.
3295 * @param context $context the context.
3296 * @param int $rolenamedisplay the type of role name to display. One of the
3297 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3298 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3299 * @return array if $withcounts is false, then an array $roleid => $rolename.
3300 * if $withusercounts is true, returns a list of three arrays,
3301 * $rolenames, $rolecounts, and $nameswithcounts.
3303 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3304 global $USER, $DB;
3306 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3307 if ($withcounts) {
3308 return array(array(), array(), array());
3309 } else {
3310 return array();
3314 $parents = $context->get_parent_context_ids(true);
3315 $contexts = implode(',' , $parents);
3317 $params = array();
3318 $extrafields = '';
3320 $params['userid'] = $USER->id;
3321 if ($withcounts) {
3322 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3323 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3324 $params['conid'] = $context->id;
3327 if ($coursecontext = $context->get_course_context(false)) {
3328 $params['coursecontext'] = $coursecontext->id;
3329 } else {
3330 $params['coursecontext'] = 0; // no course aliases
3331 $coursecontext = null;
3334 if (is_siteadmin()) {
3335 // show all roles to admins
3336 $roles = $DB->get_records_sql("
3337 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3338 FROM {role} ro
3339 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3340 ORDER BY ro.sortorder ASC", $params);
3342 } else {
3343 $roles = $DB->get_records_sql("
3344 SELECT ro.id, ro.name, ro.shortname, rn.name AS coursealias $extrafields
3345 FROM {role} ro
3346 JOIN (SELECT DISTINCT r.id
3347 FROM {role} r
3348 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3349 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3350 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3351 ) inline_view ON ro.id = inline_view.id
3352 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = ro.id)
3353 ORDER BY ro.sortorder ASC", $params);
3356 $rolenames = role_fix_names($roles, $context, $rolenamedisplay, true);
3358 if (!$withcounts) {
3359 return $rolenames;
3362 $rolecounts = array();
3363 $nameswithcounts = array();
3364 foreach ($roles as $role) {
3365 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3366 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3368 return array($rolenames, $rolecounts, $nameswithcounts);
3372 * Create a role menu suitable for default role selection in enrol plugins.
3374 * @package core_enrol
3376 * @param context $context
3377 * @param int $addroleid current or default role - always added to list
3378 * @return array roleid=>localised role name
3380 function get_default_enrol_roles(context $context, $addroleid = null) {
3381 global $DB;
3383 $params = array('contextlevel'=>CONTEXT_COURSE);
3385 if ($coursecontext = $context->get_course_context(false)) {
3386 $params['coursecontext'] = $coursecontext->id;
3387 } else {
3388 $params['coursecontext'] = 0; // no course names
3389 $coursecontext = null;
3392 if ($addroleid) {
3393 $addrole = "OR r.id = :addroleid";
3394 $params['addroleid'] = $addroleid;
3395 } else {
3396 $addrole = "";
3399 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias
3400 FROM {role} r
3401 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3402 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3403 WHERE rcl.id IS NOT NULL $addrole
3404 ORDER BY sortorder DESC";
3406 $roles = $DB->get_records_sql($sql, $params);
3408 return role_fix_names($roles, $context, ROLENAME_BOTH, true);
3412 * Return context levels where this role is assignable.
3414 * @param integer $roleid the id of a role.
3415 * @return array list of the context levels at which this role may be assigned.
3417 function get_role_contextlevels($roleid) {
3418 global $DB;
3419 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3420 'contextlevel', 'id,contextlevel');
3424 * Return roles suitable for assignment at the specified context level.
3426 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3428 * @param integer $contextlevel a contextlevel.
3429 * @return array list of role ids that are assignable at this context level.
3431 function get_roles_for_contextlevels($contextlevel) {
3432 global $DB;
3433 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3434 '', 'id,roleid');
3438 * Returns default context levels where roles can be assigned.
3440 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3441 * from the array returned by get_role_archetypes();
3442 * @return array list of the context levels at which this type of role may be assigned by default.
3444 function get_default_contextlevels($rolearchetype) {
3445 static $defaults = array(
3446 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3447 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3448 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3449 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3450 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3451 'guest' => array(),
3452 'user' => array(),
3453 'frontpage' => array());
3455 if (isset($defaults[$rolearchetype])) {
3456 return $defaults[$rolearchetype];
3457 } else {
3458 return array();
3463 * Set the context levels at which a particular role can be assigned.
3464 * Throws exceptions in case of error.
3466 * @param integer $roleid the id of a role.
3467 * @param array $contextlevels the context levels at which this role should be assignable,
3468 * duplicate levels are removed.
3469 * @return void
3471 function set_role_contextlevels($roleid, array $contextlevels) {
3472 global $DB;
3473 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3474 $rcl = new stdClass();
3475 $rcl->roleid = $roleid;
3476 $contextlevels = array_unique($contextlevels);
3477 foreach ($contextlevels as $level) {
3478 $rcl->contextlevel = $level;
3479 $DB->insert_record('role_context_levels', $rcl, false, true);
3484 * Who has this capability in this context?
3486 * This can be a very expensive call - use sparingly and keep
3487 * the results if you are going to need them again soon.
3489 * Note if $fields is empty this function attempts to get u.*
3490 * which can get rather large - and has a serious perf impact
3491 * on some DBs.
3493 * @param context $context
3494 * @param string|array $capability - capability name(s)
3495 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3496 * @param string $sort - the sort order. Default is lastaccess time.
3497 * @param mixed $limitfrom - number of records to skip (offset)
3498 * @param mixed $limitnum - number of records to fetch
3499 * @param string|array $groups - single group or array of groups - only return
3500 * users who are in one of these group(s).
3501 * @param string|array $exceptions - list of users to exclude, comma separated or array
3502 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3503 * @param bool $view_ignored - use get_enrolled_sql() instead
3504 * @param bool $useviewallgroups if $groups is set the return users who
3505 * have capability both $capability and moodle/site:accessallgroups
3506 * in this context, as well as users who have $capability and who are
3507 * in $groups.
3508 * @return array of user records
3510 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3511 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3512 global $CFG, $DB;
3514 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3515 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3517 $ctxids = trim($context->path, '/');
3518 $ctxids = str_replace('/', ',', $ctxids);
3520 // Context is the frontpage
3521 $iscoursepage = false; // coursepage other than fp
3522 $isfrontpage = false;
3523 if ($context->contextlevel == CONTEXT_COURSE) {
3524 if ($context->instanceid == SITEID) {
3525 $isfrontpage = true;
3526 } else {
3527 $iscoursepage = true;
3530 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3532 $caps = (array)$capability;
3534 // construct list of context paths bottom-->top
3535 list($contextids, $paths) = get_context_info_list($context);
3537 // we need to find out all roles that have these capabilities either in definition or in overrides
3538 $defs = array();
3539 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3540 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3541 $params = array_merge($params, $params2);
3542 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3543 FROM {role_capabilities} rc
3544 JOIN {context} ctx on rc.contextid = ctx.id
3545 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3547 $rcs = $DB->get_records_sql($sql, $params);
3548 foreach ($rcs as $rc) {
3549 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3552 // go through the permissions bottom-->top direction to evaluate the current permission,
3553 // first one wins (prohibit is an exception that always wins)
3554 $access = array();
3555 foreach ($caps as $cap) {
3556 foreach ($paths as $path) {
3557 if (empty($defs[$cap][$path])) {
3558 continue;
3560 foreach($defs[$cap][$path] as $roleid => $perm) {
3561 if ($perm == CAP_PROHIBIT) {
3562 $access[$cap][$roleid] = CAP_PROHIBIT;
3563 continue;
3565 if (!isset($access[$cap][$roleid])) {
3566 $access[$cap][$roleid] = (int)$perm;
3572 // make lists of roles that are needed and prohibited in this context
3573 $needed = array(); // one of these is enough
3574 $prohibited = array(); // must not have any of these
3575 foreach ($caps as $cap) {
3576 if (empty($access[$cap])) {
3577 continue;
3579 foreach ($access[$cap] as $roleid => $perm) {
3580 if ($perm == CAP_PROHIBIT) {
3581 unset($needed[$cap][$roleid]);
3582 $prohibited[$cap][$roleid] = true;
3583 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3584 $needed[$cap][$roleid] = true;
3587 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3588 // easy, nobody has the permission
3589 unset($needed[$cap]);
3590 unset($prohibited[$cap]);
3591 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3592 // everybody is disqualified on the frontpage
3593 unset($needed[$cap]);
3594 unset($prohibited[$cap]);
3596 if (empty($prohibited[$cap])) {
3597 unset($prohibited[$cap]);
3601 if (empty($needed)) {
3602 // there can not be anybody if no roles match this request
3603 return array();
3606 if (empty($prohibited)) {
3607 // we can compact the needed roles
3608 $n = array();
3609 foreach ($needed as $cap) {
3610 foreach ($cap as $roleid=>$unused) {
3611 $n[$roleid] = true;
3614 $needed = array('any'=>$n);
3615 unset($n);
3618 // ***** Set up default fields ******
3619 if (empty($fields)) {
3620 if ($iscoursepage) {
3621 $fields = 'u.*, ul.timeaccess AS lastaccess';
3622 } else {
3623 $fields = 'u.*';
3625 } else {
3626 if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3627 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3631 // Set up default sort
3632 if (empty($sort)) { // default to course lastaccess or just lastaccess
3633 if ($iscoursepage) {
3634 $sort = 'ul.timeaccess';
3635 } else {
3636 $sort = 'u.lastaccess';
3640 // Prepare query clauses
3641 $wherecond = array();
3642 $params = array();
3643 $joins = array();
3645 // User lastaccess JOIN
3646 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3647 // user_lastaccess is not required MDL-13810
3648 } else {
3649 if ($iscoursepage) {
3650 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3651 } else {
3652 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3656 // We never return deleted users or guest account.
3657 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3658 $params['guestid'] = $CFG->siteguest;
3660 // Groups
3661 if ($groups) {
3662 $groups = (array)$groups;
3663 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3664 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3665 $params = array_merge($params, $grpparams);
3667 if ($useviewallgroups) {
3668 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3669 if (!empty($viewallgroupsusers)) {
3670 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3671 } else {
3672 $wherecond[] = "($grouptest)";
3674 } else {
3675 $wherecond[] = "($grouptest)";
3679 // User exceptions
3680 if (!empty($exceptions)) {
3681 $exceptions = (array)$exceptions;
3682 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3683 $params = array_merge($params, $exparams);
3684 $wherecond[] = "u.id $exsql";
3687 // now add the needed and prohibited roles conditions as joins
3688 if (!empty($needed['any'])) {
3689 // simple case - there are no prohibits involved
3690 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3691 // everybody
3692 } else {
3693 $joins[] = "JOIN (SELECT DISTINCT userid
3694 FROM {role_assignments}
3695 WHERE contextid IN ($ctxids)
3696 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3697 ) ra ON ra.userid = u.id";
3699 } else {
3700 $unions = array();
3701 $everybody = false;
3702 foreach ($needed as $cap=>$unused) {
3703 if (empty($prohibited[$cap])) {
3704 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3705 $everybody = true;
3706 break;
3707 } else {
3708 $unions[] = "SELECT userid
3709 FROM {role_assignments}
3710 WHERE contextid IN ($ctxids)
3711 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3713 } else {
3714 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3715 // nobody can have this cap because it is prevented in default roles
3716 continue;
3718 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3719 // everybody except the prohibitted - hiding does not matter
3720 $unions[] = "SELECT id AS userid
3721 FROM {user}
3722 WHERE id NOT IN (SELECT userid
3723 FROM {role_assignments}
3724 WHERE contextid IN ($ctxids)
3725 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3727 } else {
3728 $unions[] = "SELECT userid
3729 FROM {role_assignments}
3730 WHERE contextid IN ($ctxids)
3731 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3732 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3736 if (!$everybody) {
3737 if ($unions) {
3738 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3739 } else {
3740 // only prohibits found - nobody can be matched
3741 $wherecond[] = "1 = 2";
3746 // Collect WHERE conditions and needed joins
3747 $where = implode(' AND ', $wherecond);
3748 if ($where !== '') {
3749 $where = 'WHERE ' . $where;
3751 $joins = implode("\n", $joins);
3753 // Ok, let's get the users!
3754 $sql = "SELECT $fields
3755 FROM {user} u
3756 $joins
3757 $where
3758 ORDER BY $sort";
3760 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3764 * Re-sort a users array based on a sorting policy
3766 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3767 * based on a sorting policy. This is to support the odd practice of
3768 * sorting teachers by 'authority', where authority was "lowest id of the role
3769 * assignment".
3771 * Will execute 1 database query. Only suitable for small numbers of users, as it
3772 * uses an u.id IN() clause.
3774 * Notes about the sorting criteria.
3776 * As a default, we cannot rely on role.sortorder because then
3777 * admins/coursecreators will always win. That is why the sane
3778 * rule "is locality matters most", with sortorder as 2nd
3779 * consideration.
3781 * If you want role.sortorder, use the 'sortorder' policy, and
3782 * name explicitly what roles you want to cover. It's probably
3783 * a good idea to see what roles have the capabilities you want
3784 * (array_diff() them against roiles that have 'can-do-anything'
3785 * to weed out admin-ish roles. Or fetch a list of roles from
3786 * variables like $CFG->coursecontact .
3788 * @param array $users Users array, keyed on userid
3789 * @param context $context
3790 * @param array $roles ids of the roles to include, optional
3791 * @param string $sortpolicy defaults to locality, more about
3792 * @return array sorted copy of the array
3794 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3795 global $DB;
3797 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3798 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3799 if (empty($roles)) {
3800 $roleswhere = '';
3801 } else {
3802 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3805 $sql = "SELECT ra.userid
3806 FROM {role_assignments} ra
3807 JOIN {role} r
3808 ON ra.roleid=r.id
3809 JOIN {context} ctx
3810 ON ra.contextid=ctx.id
3811 WHERE $userswhere
3812 $contextwhere
3813 $roleswhere";
3815 // Default 'locality' policy -- read PHPDoc notes
3816 // about sort policies...
3817 $orderby = 'ORDER BY '
3818 .'ctx.depth DESC, ' /* locality wins */
3819 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3820 .'ra.id'; /* role assignment order tie-breaker */
3821 if ($sortpolicy === 'sortorder') {
3822 $orderby = 'ORDER BY '
3823 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3824 .'ra.id'; /* role assignment order tie-breaker */
3827 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3828 $sortedusers = array();
3829 $seen = array();
3831 foreach ($sortedids as $id) {
3832 // Avoid duplicates
3833 if (isset($seen[$id])) {
3834 continue;
3836 $seen[$id] = true;
3838 // assign
3839 $sortedusers[$id] = $users[$id];
3841 return $sortedusers;
3845 * Gets all the users assigned this role in this context or higher
3847 * @param int $roleid (can also be an array of ints!)
3848 * @param context $context
3849 * @param bool $parent if true, get list of users assigned in higher context too
3850 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3851 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
3852 * null => use default sort from users_order_by_sql.
3853 * @param bool $gethidden_ignored use enrolments instead
3854 * @param string $group defaults to ''
3855 * @param mixed $limitfrom defaults to ''
3856 * @param mixed $limitnum defaults to ''
3857 * @param string $extrawheretest defaults to ''
3858 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
3859 * @return array
3861 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3862 $sort = null, $gethidden_ignored = null, $group = '',
3863 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
3864 global $DB;
3866 if (empty($fields)) {
3867 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3868 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
3869 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3870 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
3871 'r.shortname AS roleshortname, rn.name AS rolecoursealias';
3874 $parentcontexts = '';
3875 if ($parent) {
3876 $parentcontexts = substr($context->path, 1); // kill leading slash
3877 $parentcontexts = str_replace('/', ',', $parentcontexts);
3878 if ($parentcontexts !== '') {
3879 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3883 if ($roleid) {
3884 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
3885 $roleselect = "AND ra.roleid $rids";
3886 } else {
3887 $params = array();
3888 $roleselect = '';
3891 if ($coursecontext = $context->get_course_context(false)) {
3892 $params['coursecontext'] = $coursecontext->id;
3893 } else {
3894 $params['coursecontext'] = 0;
3897 if ($group) {
3898 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3899 $groupselect = " AND gm.groupid = :groupid ";
3900 $params['groupid'] = $group;
3901 } else {
3902 $groupjoin = '';
3903 $groupselect = '';
3906 $params['contextid'] = $context->id;
3908 if ($extrawheretest) {
3909 $extrawheretest = ' AND ' . $extrawheretest;
3912 if ($whereorsortparams) {
3913 $params = array_merge($params, $whereparams);
3916 if (!$sort) {
3917 list($sort, $sortparams) = users_order_by_sql('u');
3918 $params = array_merge($params, $sortparams);
3921 $sql = "SELECT DISTINCT $fields, ra.roleid
3922 FROM {role_assignments} ra
3923 JOIN {user} u ON u.id = ra.userid
3924 JOIN {role} r ON ra.roleid = r.id
3925 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3926 $groupjoin
3927 WHERE (ra.contextid = :contextid $parentcontexts)
3928 $roleselect
3929 $groupselect
3930 $extrawheretest
3931 ORDER BY $sort"; // join now so that we can just use fullname() later
3933 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3937 * Counts all the users assigned this role in this context or higher
3939 * @param int|array $roleid either int or an array of ints
3940 * @param context $context
3941 * @param bool $parent if true, get list of users assigned in higher context too
3942 * @return int Returns the result count
3944 function count_role_users($roleid, context $context, $parent = false) {
3945 global $DB;
3947 if ($parent) {
3948 if ($contexts = $context->get_parent_context_ids()) {
3949 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3950 } else {
3951 $parentcontexts = '';
3953 } else {
3954 $parentcontexts = '';
3957 if ($roleid) {
3958 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3959 $roleselect = "AND r.roleid $rids";
3960 } else {
3961 $params = array();
3962 $roleselect = '';
3965 array_unshift($params, $context->id);
3967 $sql = "SELECT COUNT(u.id)
3968 FROM {role_assignments} r
3969 JOIN {user} u ON u.id = r.userid
3970 WHERE (r.contextid = ? $parentcontexts)
3971 $roleselect
3972 AND u.deleted = 0";
3974 return $DB->count_records_sql($sql, $params);
3978 * This function gets the list of courses that this user has a particular capability in.
3979 * It is still not very efficient.
3981 * @param string $capability Capability in question
3982 * @param int $userid User ID or null for current user
3983 * @param bool $doanything True if 'doanything' is permitted (default)
3984 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3985 * otherwise use a comma-separated list of the fields you require, not including id
3986 * @param string $orderby If set, use a comma-separated list of fields from course
3987 * table with sql modifiers (DESC) if needed
3988 * @return array Array of courses, may have zero entries. Or false if query failed.
3990 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
3991 global $DB;
3993 // Convert fields list and ordering
3994 $fieldlist = '';
3995 if ($fieldsexceptid) {
3996 $fields = explode(',', $fieldsexceptid);
3997 foreach($fields as $field) {
3998 $fieldlist .= ',c.'.$field;
4001 if ($orderby) {
4002 $fields = explode(',', $orderby);
4003 $orderby = '';
4004 foreach($fields as $field) {
4005 if ($orderby) {
4006 $orderby .= ',';
4008 $orderby .= 'c.'.$field;
4010 $orderby = 'ORDER BY '.$orderby;
4013 // Obtain a list of everything relevant about all courses including context.
4014 // Note the result can be used directly as a context (we are going to), the course
4015 // fields are just appended.
4017 $contextpreload = context_helper::get_preload_record_columns_sql('x');
4019 $courses = array();
4020 $rs = $DB->get_recordset_sql("SELECT c.id $fieldlist, $contextpreload
4021 FROM {course} c
4022 JOIN {context} x ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
4023 $orderby");
4024 // Check capability for each course in turn
4025 foreach ($rs as $course) {
4026 context_helper::preload_from_record($course);
4027 $context = context_course::instance($course->id);
4028 if (has_capability($capability, $context, $userid, $doanything)) {
4029 // We've got the capability. Make the record look like a course record
4030 // and store it
4031 $courses[] = $course;
4034 $rs->close();
4035 return empty($courses) ? false : $courses;
4039 * This function finds the roles assigned directly to this context only
4040 * i.e. no roles in parent contexts
4042 * @param context $context
4043 * @return array
4045 function get_roles_on_exact_context(context $context) {
4046 global $DB;
4048 return $DB->get_records_sql("SELECT r.*
4049 FROM {role_assignments} ra, {role} r
4050 WHERE ra.roleid = r.id AND ra.contextid = ?",
4051 array($context->id));
4055 * Switches the current user to another role for the current session and only
4056 * in the given context.
4058 * The caller *must* check
4059 * - that this op is allowed
4060 * - that the requested role can be switched to in this context (use get_switchable_roles)
4061 * - that the requested role is NOT $CFG->defaultuserroleid
4063 * To "unswitch" pass 0 as the roleid.
4065 * This function *will* modify $USER->access - beware
4067 * @param integer $roleid the role to switch to.
4068 * @param context $context the context in which to perform the switch.
4069 * @return bool success or failure.
4071 function role_switch($roleid, context $context) {
4072 global $USER;
4075 // Plan of action
4077 // - Add the ghost RA to $USER->access
4078 // as $USER->access['rsw'][$path] = $roleid
4080 // - Make sure $USER->access['rdef'] has the roledefs
4081 // it needs to honour the switcherole
4083 // Roledefs will get loaded "deep" here - down to the last child
4084 // context. Note that
4086 // - When visiting subcontexts, our selective accessdata loading
4087 // will still work fine - though those ra/rdefs will be ignored
4088 // appropriately while the switch is in place
4090 // - If a switcherole happens at a category with tons of courses
4091 // (that have many overrides for switched-to role), the session
4092 // will get... quite large. Sometimes you just can't win.
4094 // To un-switch just unset($USER->access['rsw'][$path])
4096 // Note: it is not possible to switch to roles that do not have course:view
4098 if (!isset($USER->access)) {
4099 load_all_capabilities();
4103 // Add the switch RA
4104 if ($roleid == 0) {
4105 unset($USER->access['rsw'][$context->path]);
4106 return true;
4109 $USER->access['rsw'][$context->path] = $roleid;
4111 // Load roledefs
4112 load_role_access_by_context($roleid, $context, $USER->access);
4114 return true;
4118 * Checks if the user has switched roles within the given course.
4120 * Note: You can only switch roles within the course, hence it takes a course id
4121 * rather than a context. On that note Petr volunteered to implement this across
4122 * all other contexts, all requests for this should be forwarded to him ;)
4124 * @param int $courseid The id of the course to check
4125 * @return bool True if the user has switched roles within the course.
4127 function is_role_switched($courseid) {
4128 global $USER;
4129 $context = context_course::instance($courseid, MUST_EXIST);
4130 return (!empty($USER->access['rsw'][$context->path]));
4134 * Get any role that has an override on exact context
4136 * @param context $context The context to check
4137 * @return array An array of roles
4139 function get_roles_with_override_on_context(context $context) {
4140 global $DB;
4142 return $DB->get_records_sql("SELECT r.*
4143 FROM {role_capabilities} rc, {role} r
4144 WHERE rc.roleid = r.id AND rc.contextid = ?",
4145 array($context->id));
4149 * Get all capabilities for this role on this context (overrides)
4151 * @param stdClass $role
4152 * @param context $context
4153 * @return array
4155 function get_capabilities_from_role_on_context($role, context $context) {
4156 global $DB;
4158 return $DB->get_records_sql("SELECT *
4159 FROM {role_capabilities}
4160 WHERE contextid = ? AND roleid = ?",
4161 array($context->id, $role->id));
4165 * Find out which roles has assignment on this context
4167 * @param context $context
4168 * @return array
4171 function get_roles_with_assignment_on_context(context $context) {
4172 global $DB;
4174 return $DB->get_records_sql("SELECT r.*
4175 FROM {role_assignments} ra, {role} r
4176 WHERE ra.roleid = r.id AND ra.contextid = ?",
4177 array($context->id));
4181 * Find all user assignment of users for this role, on this context
4183 * @param stdClass $role
4184 * @param context $context
4185 * @return array
4187 function get_users_from_role_on_context($role, context $context) {
4188 global $DB;
4190 return $DB->get_records_sql("SELECT *
4191 FROM {role_assignments}
4192 WHERE contextid = ? AND roleid = ?",
4193 array($context->id, $role->id));
4197 * Simple function returning a boolean true if user has roles
4198 * in context or parent contexts, otherwise false.
4200 * @param int $userid
4201 * @param int $roleid
4202 * @param int $contextid empty means any context
4203 * @return bool
4205 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4206 global $DB;
4208 if ($contextid) {
4209 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4210 return false;
4212 $parents = $context->get_parent_context_ids(true);
4213 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4214 $params['userid'] = $userid;
4215 $params['roleid'] = $roleid;
4217 $sql = "SELECT COUNT(ra.id)
4218 FROM {role_assignments} ra
4219 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4221 $count = $DB->get_field_sql($sql, $params);
4222 return ($count > 0);
4224 } else {
4225 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4230 * Get role name or alias if exists and format the text.
4232 * @param stdClass $role role object
4233 * - optional 'coursealias' property should be included for performance reasons if course context used
4234 * - description property is not required here
4235 * @param context|bool $context empty means system context
4236 * @param int $rolenamedisplay type of role name
4237 * @return string localised role name or course role name alias
4239 function role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS) {
4240 global $DB;
4242 if ($rolenamedisplay == ROLENAME_SHORT) {
4243 return $role->shortname;
4246 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4247 $coursecontext = null;
4250 if ($coursecontext and !property_exists($role, 'coursealias') and ($rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH or $rolenamedisplay == ROLENAME_ALIAS_RAW)) {
4251 $role = clone($role); // Do not modify parameters.
4252 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4253 $role->coursealias = $r->name;
4254 } else {
4255 $role->coursealias = null;
4259 if ($rolenamedisplay == ROLENAME_ALIAS_RAW) {
4260 if ($coursecontext) {
4261 return $role->coursealias;
4262 } else {
4263 return null;
4267 if (trim($role->name) !== '') {
4268 // For filtering always use context where was the thing defined - system for roles here.
4269 $original = format_string($role->name, true, array('context'=>context_system::instance()));
4271 } else {
4272 // Empty role->name means we want to see localised role name based on shortname,
4273 // only default roles are supposed to be localised.
4274 switch ($role->shortname) {
4275 case 'manager': $original = get_string('manager', 'role'); break;
4276 case 'coursecreator': $original = get_string('coursecreators'); break;
4277 case 'editingteacher': $original = get_string('defaultcourseteacher'); break;
4278 case 'teacher': $original = get_string('noneditingteacher'); break;
4279 case 'student': $original = get_string('defaultcoursestudent'); break;
4280 case 'guest': $original = get_string('guest'); break;
4281 case 'user': $original = get_string('authenticateduser'); break;
4282 case 'frontpage': $original = get_string('frontpageuser', 'role'); break;
4283 // We should not get here, the role UI should require the name for custom roles!
4284 default: $original = $role->shortname; break;
4288 if ($rolenamedisplay == ROLENAME_ORIGINAL) {
4289 return $original;
4292 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4293 return "$original ($role->shortname)";
4296 if ($rolenamedisplay == ROLENAME_ALIAS) {
4297 if ($coursecontext and trim($role->coursealias) !== '') {
4298 return format_string($role->coursealias, true, array('context'=>$coursecontext));
4299 } else {
4300 return $original;
4304 if ($rolenamedisplay == ROLENAME_BOTH) {
4305 if ($coursecontext and trim($role->coursealias) !== '') {
4306 return format_string($role->coursealias, true, array('context'=>$coursecontext)) . " ($original)";
4307 } else {
4308 return $original;
4312 throw new coding_exception('Invalid $rolenamedisplay parameter specified in role_get_name()');
4316 * Returns localised role description if available.
4317 * If the name is empty it tries to find the default role name using
4318 * hardcoded list of default role names or other methods in the future.
4320 * @param stdClass $role
4321 * @return string localised role name
4323 function role_get_description(stdClass $role) {
4324 if (!html_is_blank($role->description)) {
4325 return format_text($role->description, FORMAT_HTML, array('context'=>context_system::instance()));
4328 switch ($role->shortname) {
4329 case 'manager': return get_string('managerdescription', 'role');
4330 case 'coursecreator': return get_string('coursecreatorsdescription');
4331 case 'editingteacher': return get_string('defaultcourseteacherdescription');
4332 case 'teacher': return get_string('noneditingteacherdescription');
4333 case 'student': return get_string('defaultcoursestudentdescription');
4334 case 'guest': return get_string('guestdescription');
4335 case 'user': return get_string('authenticateduserdescription');
4336 case 'frontpage': return get_string('frontpageuserdescription', 'role');
4337 default: return '';
4342 * Get all the localised role names for a context.
4343 * @param context $context the context
4344 * @param array of role objects with a ->localname field containing the context-specific role name.
4346 function role_get_names(context $context) {
4347 return role_fix_names(get_all_roles(), $context);
4351 * Prepare list of roles for display, apply aliases and format text
4353 * @param array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
4354 * @param context|bool $context a context
4355 * @param int $rolenamedisplay
4356 * @param bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
4357 * @return array Array of context-specific role names, or role objects with a ->localname field added.
4359 function role_fix_names($roleoptions, $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null) {
4360 global $DB;
4362 if (empty($roleoptions)) {
4363 return array();
4366 if (!$context or !$coursecontext = $context->get_course_context(false)) {
4367 $coursecontext = null;
4370 // We usually need all role columns...
4371 $first = reset($roleoptions);
4372 if ($returnmenu === null) {
4373 $returnmenu = !is_object($first);
4376 if (!is_object($first) or !property_exists($first, 'shortname')) {
4377 $allroles = get_all_roles($context);
4378 foreach ($roleoptions as $rid => $unused) {
4379 $roleoptions[$rid] = $allroles[$rid];
4383 // Inject coursealias if necessary.
4384 if ($coursecontext and ($rolenamedisplay == ROLENAME_ALIAS_RAW or $rolenamedisplay == ROLENAME_ALIAS or $rolenamedisplay == ROLENAME_BOTH)) {
4385 $first = reset($roleoptions);
4386 if (!property_exists($first, 'coursealias')) {
4387 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4388 foreach ($aliasnames as $alias) {
4389 if (isset($roleoptions[$alias->roleid])) {
4390 $roleoptions[$alias->roleid]->coursealias = $alias->name;
4396 // Add localname property.
4397 foreach ($roleoptions as $rid => $role) {
4398 $roleoptions[$rid]->localname = role_get_name($role, $coursecontext, $rolenamedisplay);
4401 if (!$returnmenu) {
4402 return $roleoptions;
4405 $menu = array();
4406 foreach ($roleoptions as $rid => $role) {
4407 $menu[$rid] = $role->localname;
4410 return $menu;
4414 * Aids in detecting if a new line is required when reading a new capability
4416 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4417 * when we read in a new capability.
4418 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4419 * but when we are in grade, all reports/import/export capabilities should be together
4421 * @param string $cap component string a
4422 * @param string $comp component string b
4423 * @param int $contextlevel
4424 * @return bool whether 2 component are in different "sections"
4426 function component_level_changed($cap, $comp, $contextlevel) {
4428 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4429 $compsa = explode('/', $cap->component);
4430 $compsb = explode('/', $comp);
4432 // list of system reports
4433 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4434 return false;
4437 // we are in gradebook, still
4438 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4439 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4440 return false;
4443 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4444 return false;
4448 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4452 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4453 * and return an array of roleids in order.
4455 * @param array $allroles array of roles, as returned by get_all_roles();
4456 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4458 function fix_role_sortorder($allroles) {
4459 global $DB;
4461 $rolesort = array();
4462 $i = 0;
4463 foreach ($allroles as $role) {
4464 $rolesort[$i] = $role->id;
4465 if ($role->sortorder != $i) {
4466 $r = new stdClass();
4467 $r->id = $role->id;
4468 $r->sortorder = $i;
4469 $DB->update_record('role', $r);
4470 $allroles[$role->id]->sortorder = $i;
4472 $i++;
4474 return $rolesort;
4478 * Switch the sort order of two roles (used in admin/roles/manage.php).
4480 * @param stdClass $first The first role. Actually, only ->sortorder is used.
4481 * @param stdClass $second The second role. Actually, only ->sortorder is used.
4482 * @return boolean success or failure
4484 function switch_roles($first, $second) {
4485 global $DB;
4486 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4487 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4488 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4489 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4490 return $result;
4494 * Duplicates all the base definitions of a role
4496 * @param stdClass $sourcerole role to copy from
4497 * @param int $targetrole id of role to copy to
4499 function role_cap_duplicate($sourcerole, $targetrole) {
4500 global $DB;
4502 $systemcontext = context_system::instance();
4503 $caps = $DB->get_records_sql("SELECT *
4504 FROM {role_capabilities}
4505 WHERE roleid = ? AND contextid = ?",
4506 array($sourcerole->id, $systemcontext->id));
4507 // adding capabilities
4508 foreach ($caps as $cap) {
4509 unset($cap->id);
4510 $cap->roleid = $targetrole;
4511 $DB->insert_record('role_capabilities', $cap);
4516 * Returns two lists, this can be used to find out if user has capability.
4517 * Having any needed role and no forbidden role in this context means
4518 * user has this capability in this context.
4519 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4521 * @param stdClass $context
4522 * @param string $capability
4523 * @return array($neededroles, $forbiddenroles)
4525 function get_roles_with_cap_in_context($context, $capability) {
4526 global $DB;
4528 $ctxids = trim($context->path, '/'); // kill leading slash
4529 $ctxids = str_replace('/', ',', $ctxids);
4531 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4532 FROM {role_capabilities} rc
4533 JOIN {context} ctx ON ctx.id = rc.contextid
4534 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4535 ORDER BY rc.roleid ASC, ctx.depth DESC";
4536 $params = array('cap'=>$capability);
4538 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4539 // no cap definitions --> no capability
4540 return array(array(), array());
4543 $forbidden = array();
4544 $needed = array();
4545 foreach($capdefs as $def) {
4546 if (isset($forbidden[$def->roleid])) {
4547 continue;
4549 if ($def->permission == CAP_PROHIBIT) {
4550 $forbidden[$def->roleid] = $def->roleid;
4551 unset($needed[$def->roleid]);
4552 continue;
4554 if (!isset($needed[$def->roleid])) {
4555 if ($def->permission == CAP_ALLOW) {
4556 $needed[$def->roleid] = true;
4557 } else if ($def->permission == CAP_PREVENT) {
4558 $needed[$def->roleid] = false;
4562 unset($capdefs);
4564 // remove all those roles not allowing
4565 foreach($needed as $key=>$value) {
4566 if (!$value) {
4567 unset($needed[$key]);
4568 } else {
4569 $needed[$key] = $key;
4573 return array($needed, $forbidden);
4577 * Returns an array of role IDs that have ALL of the the supplied capabilities
4578 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4580 * @param stdClass $context
4581 * @param array $capabilities An array of capabilities
4582 * @return array of roles with all of the required capabilities
4584 function get_roles_with_caps_in_context($context, $capabilities) {
4585 $neededarr = array();
4586 $forbiddenarr = array();
4587 foreach($capabilities as $caprequired) {
4588 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4591 $rolesthatcanrate = array();
4592 if (!empty($neededarr)) {
4593 foreach ($neededarr as $needed) {
4594 if (empty($rolesthatcanrate)) {
4595 $rolesthatcanrate = $needed;
4596 } else {
4597 //only want roles that have all caps
4598 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4602 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4603 foreach ($forbiddenarr as $forbidden) {
4604 //remove any roles that are forbidden any of the caps
4605 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4608 return $rolesthatcanrate;
4612 * Returns an array of role names that have ALL of the the supplied capabilities
4613 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4615 * @param stdClass $context
4616 * @param array $capabilities An array of capabilities
4617 * @return array of roles with all of the required capabilities
4619 function get_role_names_with_caps_in_context($context, $capabilities) {
4620 global $DB;
4622 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4623 $allroles = $DB->get_records('role', null, 'sortorder DESC');
4625 $roles = array();
4626 foreach ($rolesthatcanrate as $r) {
4627 $roles[$r] = $allroles[$r];
4630 return role_fix_names($roles, $context, ROLENAME_ALIAS, true);
4634 * This function verifies the prohibit comes from this context
4635 * and there are no more prohibits in parent contexts.
4637 * @param int $roleid
4638 * @param context $context
4639 * @param string $capability name
4640 * @return bool
4642 function prohibit_is_removable($roleid, context $context, $capability) {
4643 global $DB;
4645 $ctxids = trim($context->path, '/'); // kill leading slash
4646 $ctxids = str_replace('/', ',', $ctxids);
4648 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4650 $sql = "SELECT ctx.id
4651 FROM {role_capabilities} rc
4652 JOIN {context} ctx ON ctx.id = rc.contextid
4653 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4654 ORDER BY ctx.depth DESC";
4656 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4657 // no prohibits == nothing to remove
4658 return true;
4661 if (count($prohibits) > 1) {
4662 // more prohibits can not be removed
4663 return false;
4666 return !empty($prohibits[$context->id]);
4670 * More user friendly role permission changing,
4671 * it should produce as few overrides as possible.
4673 * @param int $roleid
4674 * @param stdClass $context
4675 * @param string $capname capability name
4676 * @param int $permission
4677 * @return void
4679 function role_change_permission($roleid, $context, $capname, $permission) {
4680 global $DB;
4682 if ($permission == CAP_INHERIT) {
4683 unassign_capability($capname, $roleid, $context->id);
4684 $context->mark_dirty();
4685 return;
4688 $ctxids = trim($context->path, '/'); // kill leading slash
4689 $ctxids = str_replace('/', ',', $ctxids);
4691 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4693 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4694 FROM {role_capabilities} rc
4695 JOIN {context} ctx ON ctx.id = rc.contextid
4696 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4697 ORDER BY ctx.depth DESC";
4699 if ($existing = $DB->get_records_sql($sql, $params)) {
4700 foreach($existing as $e) {
4701 if ($e->permission == CAP_PROHIBIT) {
4702 // prohibit can not be overridden, no point in changing anything
4703 return;
4706 $lowest = array_shift($existing);
4707 if ($lowest->permission == $permission) {
4708 // permission already set in this context or parent - nothing to do
4709 return;
4711 if ($existing) {
4712 $parent = array_shift($existing);
4713 if ($parent->permission == $permission) {
4714 // permission already set in parent context or parent - just unset in this context
4715 // we do this because we want as few overrides as possible for performance reasons
4716 unassign_capability($capname, $roleid, $context->id);
4717 $context->mark_dirty();
4718 return;
4722 } else {
4723 if ($permission == CAP_PREVENT) {
4724 // nothing means role does not have permission
4725 return;
4729 // assign the needed capability
4730 assign_capability($capname, $permission, $roleid, $context->id, true);
4732 // force cap reloading
4733 $context->mark_dirty();
4738 * Basic moodle context abstraction class.
4740 * Google confirms that no other important framework is using "context" class,
4741 * we could use something else like mcontext or moodle_context, but we need to type
4742 * this very often which would be annoying and it would take too much space...
4744 * This class is derived from stdClass for backwards compatibility with
4745 * odl $context record that was returned from DML $DB->get_record()
4747 * @package core_access
4748 * @category access
4749 * @copyright Petr Skoda {@link http://skodak.org}
4750 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4751 * @since 2.2
4753 * @property-read int $id context id
4754 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4755 * @property-read int $instanceid id of related instance in each context
4756 * @property-read string $path path to context, starts with system context
4757 * @property-read int $depth
4759 abstract class context extends stdClass implements IteratorAggregate {
4762 * The context id
4763 * Can be accessed publicly through $context->id
4764 * @var int
4766 protected $_id;
4769 * The context level
4770 * Can be accessed publicly through $context->contextlevel
4771 * @var int One of CONTEXT_* e.g. CONTEXT_COURSE, CONTEXT_MODULE
4773 protected $_contextlevel;
4776 * Id of the item this context is related to e.g. COURSE_CONTEXT => course.id
4777 * Can be accessed publicly through $context->instanceid
4778 * @var int
4780 protected $_instanceid;
4783 * The path to the context always starting from the system context
4784 * Can be accessed publicly through $context->path
4785 * @var string
4787 protected $_path;
4790 * The depth of the context in relation to parent contexts
4791 * Can be accessed publicly through $context->depth
4792 * @var int
4794 protected $_depth;
4797 * @var array Context caching info
4799 private static $cache_contextsbyid = array();
4802 * @var array Context caching info
4804 private static $cache_contexts = array();
4807 * Context count
4808 * Why do we do count contexts? Because count($array) is horribly slow for large arrays
4809 * @var int
4811 protected static $cache_count = 0;
4814 * @var array Context caching info
4816 protected static $cache_preloaded = array();
4819 * @var context_system The system context once initialised
4821 protected static $systemcontext = null;
4824 * Resets the cache to remove all data.
4825 * @static
4827 protected static function reset_caches() {
4828 self::$cache_contextsbyid = array();
4829 self::$cache_contexts = array();
4830 self::$cache_count = 0;
4831 self::$cache_preloaded = array();
4833 self::$systemcontext = null;
4837 * Adds a context to the cache. If the cache is full, discards a batch of
4838 * older entries.
4840 * @static
4841 * @param context $context New context to add
4842 * @return void
4844 protected static function cache_add(context $context) {
4845 if (isset(self::$cache_contextsbyid[$context->id])) {
4846 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4847 return;
4850 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4851 $i = 0;
4852 foreach(self::$cache_contextsbyid as $ctx) {
4853 $i++;
4854 if ($i <= 100) {
4855 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4856 continue;
4858 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4859 // we remove oldest third of the contexts to make room for more contexts
4860 break;
4862 unset(self::$cache_contextsbyid[$ctx->id]);
4863 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4864 self::$cache_count--;
4868 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4869 self::$cache_contextsbyid[$context->id] = $context;
4870 self::$cache_count++;
4874 * Removes a context from the cache.
4876 * @static
4877 * @param context $context Context object to remove
4878 * @return void
4880 protected static function cache_remove(context $context) {
4881 if (!isset(self::$cache_contextsbyid[$context->id])) {
4882 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4883 return;
4885 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4886 unset(self::$cache_contextsbyid[$context->id]);
4888 self::$cache_count--;
4890 if (self::$cache_count < 0) {
4891 self::$cache_count = 0;
4896 * Gets a context from the cache.
4898 * @static
4899 * @param int $contextlevel Context level
4900 * @param int $instance Instance ID
4901 * @return context|bool Context or false if not in cache
4903 protected static function cache_get($contextlevel, $instance) {
4904 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4905 return self::$cache_contexts[$contextlevel][$instance];
4907 return false;
4911 * Gets a context from the cache based on its id.
4913 * @static
4914 * @param int $id Context ID
4915 * @return context|bool Context or false if not in cache
4917 protected static function cache_get_by_id($id) {
4918 if (isset(self::$cache_contextsbyid[$id])) {
4919 return self::$cache_contextsbyid[$id];
4921 return false;
4925 * Preloads context information from db record and strips the cached info.
4927 * @static
4928 * @param stdClass $rec
4929 * @return void (modifies $rec)
4931 protected static function preload_from_record(stdClass $rec) {
4932 if (empty($rec->ctxid) or empty($rec->ctxlevel) or empty($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4933 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4934 return;
4937 // note: in PHP5 the objects are passed by reference, no need to return $rec
4938 $record = new stdClass();
4939 $record->id = $rec->ctxid; unset($rec->ctxid);
4940 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4941 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4942 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4943 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4945 return context::create_instance_from_record($record);
4949 // ====== magic methods =======
4952 * Magic setter method, we do not want anybody to modify properties from the outside
4953 * @param string $name
4954 * @param mixed $value
4956 public function __set($name, $value) {
4957 debugging('Can not change context instance properties!');
4961 * Magic method getter, redirects to read only values.
4962 * @param string $name
4963 * @return mixed
4965 public function __get($name) {
4966 switch ($name) {
4967 case 'id': return $this->_id;
4968 case 'contextlevel': return $this->_contextlevel;
4969 case 'instanceid': return $this->_instanceid;
4970 case 'path': return $this->_path;
4971 case 'depth': return $this->_depth;
4973 default:
4974 debugging('Invalid context property accessed! '.$name);
4975 return null;
4980 * Full support for isset on our magic read only properties.
4981 * @param string $name
4982 * @return bool
4984 public function __isset($name) {
4985 switch ($name) {
4986 case 'id': return isset($this->_id);
4987 case 'contextlevel': return isset($this->_contextlevel);
4988 case 'instanceid': return isset($this->_instanceid);
4989 case 'path': return isset($this->_path);
4990 case 'depth': return isset($this->_depth);
4992 default: return false;
4998 * ALl properties are read only, sorry.
4999 * @param string $name
5001 public function __unset($name) {
5002 debugging('Can not unset context instance properties!');
5005 // ====== implementing method from interface IteratorAggregate ======
5008 * Create an iterator because magic vars can't be seen by 'foreach'.
5010 * Now we can convert context object to array using convert_to_array(),
5011 * and feed it properly to json_encode().
5013 public function getIterator() {
5014 $ret = array(
5015 'id' => $this->id,
5016 'contextlevel' => $this->contextlevel,
5017 'instanceid' => $this->instanceid,
5018 'path' => $this->path,
5019 'depth' => $this->depth
5021 return new ArrayIterator($ret);
5024 // ====== general context methods ======
5027 * Constructor is protected so that devs are forced to
5028 * use context_xxx::instance() or context::instance_by_id().
5030 * @param stdClass $record
5032 protected function __construct(stdClass $record) {
5033 $this->_id = $record->id;
5034 $this->_contextlevel = (int)$record->contextlevel;
5035 $this->_instanceid = $record->instanceid;
5036 $this->_path = $record->path;
5037 $this->_depth = $record->depth;
5041 * This function is also used to work around 'protected' keyword problems in context_helper.
5042 * @static
5043 * @param stdClass $record
5044 * @return context instance
5046 protected static function create_instance_from_record(stdClass $record) {
5047 $classname = context_helper::get_class_for_level($record->contextlevel);
5049 if ($context = context::cache_get_by_id($record->id)) {
5050 return $context;
5053 $context = new $classname($record);
5054 context::cache_add($context);
5056 return $context;
5060 * Copy prepared new contexts from temp table to context table,
5061 * we do this in db specific way for perf reasons only.
5062 * @static
5064 protected static function merge_context_temp_table() {
5065 global $DB;
5067 /* MDL-11347:
5068 * - mysql does not allow to use FROM in UPDATE statements
5069 * - using two tables after UPDATE works in mysql, but might give unexpected
5070 * results in pg 8 (depends on configuration)
5071 * - using table alias in UPDATE does not work in pg < 8.2
5073 * Different code for each database - mostly for performance reasons
5076 $dbfamily = $DB->get_dbfamily();
5077 if ($dbfamily == 'mysql') {
5078 $updatesql = "UPDATE {context} ct, {context_temp} temp
5079 SET ct.path = temp.path,
5080 ct.depth = temp.depth
5081 WHERE ct.id = temp.id";
5082 } else if ($dbfamily == 'oracle') {
5083 $updatesql = "UPDATE {context} ct
5084 SET (ct.path, ct.depth) =
5085 (SELECT temp.path, temp.depth
5086 FROM {context_temp} temp
5087 WHERE temp.id=ct.id)
5088 WHERE EXISTS (SELECT 'x'
5089 FROM {context_temp} temp
5090 WHERE temp.id = ct.id)";
5091 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5092 $updatesql = "UPDATE {context}
5093 SET path = temp.path,
5094 depth = temp.depth
5095 FROM {context_temp} temp
5096 WHERE temp.id={context}.id";
5097 } else {
5098 // sqlite and others
5099 $updatesql = "UPDATE {context}
5100 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5101 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5102 WHERE id IN (SELECT id FROM {context_temp})";
5105 $DB->execute($updatesql);
5109 * Get a context instance as an object, from a given context id.
5111 * @static
5112 * @param int $id context id
5113 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
5114 * MUST_EXIST means throw exception if no record found
5115 * @return context|bool the context object or false if not found
5117 public static function instance_by_id($id, $strictness = MUST_EXIST) {
5118 global $DB;
5120 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
5121 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
5122 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
5125 if ($id == SYSCONTEXTID) {
5126 return context_system::instance(0, $strictness);
5129 if (is_array($id) or is_object($id) or empty($id)) {
5130 throw new coding_exception('Invalid context id specified context::instance_by_id()');
5133 if ($context = context::cache_get_by_id($id)) {
5134 return $context;
5137 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
5138 return context::create_instance_from_record($record);
5141 return false;
5145 * Update context info after moving context in the tree structure.
5147 * @param context $newparent
5148 * @return void
5150 public function update_moved(context $newparent) {
5151 global $DB;
5153 $frompath = $this->_path;
5154 $newpath = $newparent->path . '/' . $this->_id;
5156 $trans = $DB->start_delegated_transaction();
5158 $this->mark_dirty();
5160 $setdepth = '';
5161 if (($newparent->depth +1) != $this->_depth) {
5162 $diff = $newparent->depth - $this->_depth + 1;
5163 $setdepth = ", depth = depth + $diff";
5165 $sql = "UPDATE {context}
5166 SET path = ?
5167 $setdepth
5168 WHERE id = ?";
5169 $params = array($newpath, $this->_id);
5170 $DB->execute($sql, $params);
5172 $this->_path = $newpath;
5173 $this->_depth = $newparent->depth + 1;
5175 $sql = "UPDATE {context}
5176 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5177 $setdepth
5178 WHERE path LIKE ?";
5179 $params = array($newpath, "{$frompath}/%");
5180 $DB->execute($sql, $params);
5182 $this->mark_dirty();
5184 context::reset_caches();
5186 $trans->allow_commit();
5190 * Remove all context path info and optionally rebuild it.
5192 * @param bool $rebuild
5193 * @return void
5195 public function reset_paths($rebuild = true) {
5196 global $DB;
5198 if ($this->_path) {
5199 $this->mark_dirty();
5201 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
5202 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
5203 if ($this->_contextlevel != CONTEXT_SYSTEM) {
5204 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
5205 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
5206 $this->_depth = 0;
5207 $this->_path = null;
5210 if ($rebuild) {
5211 context_helper::build_all_paths(false);
5214 context::reset_caches();
5218 * Delete all data linked to content, do not delete the context record itself
5220 public function delete_content() {
5221 global $CFG, $DB;
5223 blocks_delete_all_for_context($this->_id);
5224 filter_delete_all_for_context($this->_id);
5226 require_once($CFG->dirroot . '/comment/lib.php');
5227 comment::delete_comments(array('contextid'=>$this->_id));
5229 require_once($CFG->dirroot.'/rating/lib.php');
5230 $delopt = new stdclass();
5231 $delopt->contextid = $this->_id;
5232 $rm = new rating_manager();
5233 $rm->delete_ratings($delopt);
5235 // delete all files attached to this context
5236 $fs = get_file_storage();
5237 $fs->delete_area_files($this->_id);
5239 // delete all advanced grading data attached to this context
5240 require_once($CFG->dirroot.'/grade/grading/lib.php');
5241 grading_manager::delete_all_for_context($this->_id);
5243 // now delete stuff from role related tables, role_unassign_all
5244 // and unenrol should be called earlier to do proper cleanup
5245 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
5246 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
5247 $DB->delete_records('role_names', array('contextid'=>$this->_id));
5251 * Delete the context content and the context record itself
5253 public function delete() {
5254 global $DB;
5256 // double check the context still exists
5257 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
5258 context::cache_remove($this);
5259 return;
5262 $this->delete_content();
5263 $DB->delete_records('context', array('id'=>$this->_id));
5264 // purge static context cache if entry present
5265 context::cache_remove($this);
5267 // do not mark dirty contexts if parents unknown
5268 if (!is_null($this->_path) and $this->_depth > 0) {
5269 $this->mark_dirty();
5273 // ====== context level related methods ======
5276 * Utility method for context creation
5278 * @static
5279 * @param int $contextlevel
5280 * @param int $instanceid
5281 * @param string $parentpath
5282 * @return stdClass context record
5284 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
5285 global $DB;
5287 $record = new stdClass();
5288 $record->contextlevel = $contextlevel;
5289 $record->instanceid = $instanceid;
5290 $record->depth = 0;
5291 $record->path = null; //not known before insert
5293 $record->id = $DB->insert_record('context', $record);
5295 // now add path if known - it can be added later
5296 if (!is_null($parentpath)) {
5297 $record->path = $parentpath.'/'.$record->id;
5298 $record->depth = substr_count($record->path, '/');
5299 $DB->update_record('context', $record);
5302 return $record;
5306 * Returns human readable context identifier.
5308 * @param boolean $withprefix whether to prefix the name of the context with the
5309 * type of context, e.g. User, Course, Forum, etc.
5310 * @param boolean $short whether to use the short name of the thing. Only applies
5311 * to course contexts
5312 * @return string the human readable context name.
5314 public function get_context_name($withprefix = true, $short = false) {
5315 // must be implemented in all context levels
5316 throw new coding_exception('can not get name of abstract context');
5320 * Returns the most relevant URL for this context.
5322 * @return moodle_url
5324 public abstract function get_url();
5327 * Returns array of relevant context capability records.
5329 * @return array
5331 public abstract function get_capabilities();
5334 * Recursive function which, given a context, find all its children context ids.
5336 * For course category contexts it will return immediate children and all subcategory contexts.
5337 * It will NOT recurse into courses or subcategories categories.
5338 * If you want to do that, call it on the returned courses/categories.
5340 * When called for a course context, it will return the modules and blocks
5341 * displayed in the course page and blocks displayed on the module pages.
5343 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5344 * contexts ;-)
5346 * @return array Array of child records
5348 public function get_child_contexts() {
5349 global $DB;
5351 $sql = "SELECT ctx.*
5352 FROM {context} ctx
5353 WHERE ctx.path LIKE ?";
5354 $params = array($this->_path.'/%');
5355 $records = $DB->get_records_sql($sql, $params);
5357 $result = array();
5358 foreach ($records as $record) {
5359 $result[$record->id] = context::create_instance_from_record($record);
5362 return $result;
5366 * Returns parent contexts of this context in reversed order, i.e. parent first,
5367 * then grand parent, etc.
5369 * @param bool $includeself tre means include self too
5370 * @return array of context instances
5372 public function get_parent_contexts($includeself = false) {
5373 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5374 return array();
5377 $result = array();
5378 foreach ($contextids as $contextid) {
5379 $parent = context::instance_by_id($contextid, MUST_EXIST);
5380 $result[$parent->id] = $parent;
5383 return $result;
5387 * Returns parent contexts of this context in reversed order, i.e. parent first,
5388 * then grand parent, etc.
5390 * @param bool $includeself tre means include self too
5391 * @return array of context ids
5393 public function get_parent_context_ids($includeself = false) {
5394 if (empty($this->_path)) {
5395 return array();
5398 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5399 $parentcontexts = explode('/', $parentcontexts);
5400 if (!$includeself) {
5401 array_pop($parentcontexts); // and remove its own id
5404 return array_reverse($parentcontexts);
5408 * Returns parent context
5410 * @return context
5412 public function get_parent_context() {
5413 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5414 return false;
5417 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5418 $parentcontexts = explode('/', $parentcontexts);
5419 array_pop($parentcontexts); // self
5420 $contextid = array_pop($parentcontexts); // immediate parent
5422 return context::instance_by_id($contextid, MUST_EXIST);
5426 * Is this context part of any course? If yes return course context.
5428 * @param bool $strict true means throw exception if not found, false means return false if not found
5429 * @return course_context context of the enclosing course, null if not found or exception
5431 public function get_course_context($strict = true) {
5432 if ($strict) {
5433 throw new coding_exception('Context does not belong to any course.');
5434 } else {
5435 return false;
5440 * Returns sql necessary for purging of stale context instances.
5442 * @static
5443 * @return string cleanup SQL
5445 protected static function get_cleanup_sql() {
5446 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5450 * Rebuild context paths and depths at context level.
5452 * @static
5453 * @param bool $force
5454 * @return void
5456 protected static function build_paths($force) {
5457 throw new coding_exception('build_paths() method must be implemented in all context levels');
5461 * Create missing context instances at given level
5463 * @static
5464 * @return void
5466 protected static function create_level_instances() {
5467 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5471 * Reset all cached permissions and definitions if the necessary.
5472 * @return void
5474 public function reload_if_dirty() {
5475 global $ACCESSLIB_PRIVATE, $USER;
5477 // Load dirty contexts list if needed
5478 if (CLI_SCRIPT) {
5479 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5480 // we do not load dirty flags in CLI and cron
5481 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5483 } else {
5484 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5485 if (!isset($USER->access['time'])) {
5486 // nothing was loaded yet, we do not need to check dirty contexts now
5487 return;
5489 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5490 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5494 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5495 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5496 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5497 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5498 reload_all_capabilities();
5499 break;
5505 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5507 public function mark_dirty() {
5508 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5510 if (during_initial_install()) {
5511 return;
5514 // only if it is a non-empty string
5515 if (is_string($this->_path) && $this->_path !== '') {
5516 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5517 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5518 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5519 } else {
5520 if (CLI_SCRIPT) {
5521 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5522 } else {
5523 if (isset($USER->access['time'])) {
5524 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5525 } else {
5526 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5528 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5537 * Context maintenance and helper methods.
5539 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5540 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5541 * level implementation from the rest of code, the code completion returns what developers need.
5543 * Thank you Tim Hunt for helping me with this nasty trick.
5545 * @package core_access
5546 * @category access
5547 * @copyright Petr Skoda {@link http://skodak.org}
5548 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5549 * @since 2.2
5551 class context_helper extends context {
5554 * @var array An array mapping context levels to classes
5556 private static $alllevels = array(
5557 CONTEXT_SYSTEM => 'context_system',
5558 CONTEXT_USER => 'context_user',
5559 CONTEXT_COURSECAT => 'context_coursecat',
5560 CONTEXT_COURSE => 'context_course',
5561 CONTEXT_MODULE => 'context_module',
5562 CONTEXT_BLOCK => 'context_block',
5566 * Instance does not make sense here, only static use
5568 protected function __construct() {
5572 * Returns a class name of the context level class
5574 * @static
5575 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5576 * @return string class name of the context class
5578 public static function get_class_for_level($contextlevel) {
5579 if (isset(self::$alllevels[$contextlevel])) {
5580 return self::$alllevels[$contextlevel];
5581 } else {
5582 throw new coding_exception('Invalid context level specified');
5587 * Returns a list of all context levels
5589 * @static
5590 * @return array int=>string (level=>level class name)
5592 public static function get_all_levels() {
5593 return self::$alllevels;
5597 * Remove stale contexts that belonged to deleted instances.
5598 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5600 * @static
5601 * @return void
5603 public static function cleanup_instances() {
5604 global $DB;
5605 $sqls = array();
5606 foreach (self::$alllevels as $level=>$classname) {
5607 $sqls[] = $classname::get_cleanup_sql();
5610 $sql = implode(" UNION ", $sqls);
5612 // it is probably better to use transactions, it might be faster too
5613 $transaction = $DB->start_delegated_transaction();
5615 $rs = $DB->get_recordset_sql($sql);
5616 foreach ($rs as $record) {
5617 $context = context::create_instance_from_record($record);
5618 $context->delete();
5620 $rs->close();
5622 $transaction->allow_commit();
5626 * Create all context instances at the given level and above.
5628 * @static
5629 * @param int $contextlevel null means all levels
5630 * @param bool $buildpaths
5631 * @return void
5633 public static function create_instances($contextlevel = null, $buildpaths = true) {
5634 foreach (self::$alllevels as $level=>$classname) {
5635 if ($contextlevel and $level > $contextlevel) {
5636 // skip potential sub-contexts
5637 continue;
5639 $classname::create_level_instances();
5640 if ($buildpaths) {
5641 $classname::build_paths(false);
5647 * Rebuild paths and depths in all context levels.
5649 * @static
5650 * @param bool $force false means add missing only
5651 * @return void
5653 public static function build_all_paths($force = false) {
5654 foreach (self::$alllevels as $classname) {
5655 $classname::build_paths($force);
5658 // reset static course cache - it might have incorrect cached data
5659 accesslib_clear_all_caches(true);
5663 * Resets the cache to remove all data.
5664 * @static
5666 public static function reset_caches() {
5667 context::reset_caches();
5671 * Returns all fields necessary for context preloading from user $rec.
5673 * This helps with performance when dealing with hundreds of contexts.
5675 * @static
5676 * @param string $tablealias context table alias in the query
5677 * @return array (table.column=>alias, ...)
5679 public static function get_preload_record_columns($tablealias) {
5680 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5684 * Returns all fields necessary for context preloading from user $rec.
5686 * This helps with performance when dealing with hundreds of contexts.
5688 * @static
5689 * @param string $tablealias context table alias in the query
5690 * @return string
5692 public static function get_preload_record_columns_sql($tablealias) {
5693 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5697 * Preloads context information from db record and strips the cached info.
5699 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5701 * @static
5702 * @param stdClass $rec
5703 * @return void (modifies $rec)
5705 public static function preload_from_record(stdClass $rec) {
5706 context::preload_from_record($rec);
5710 * Preload all contexts instances from course.
5712 * To be used if you expect multiple queries for course activities...
5714 * @static
5715 * @param int $courseid
5717 public static function preload_course($courseid) {
5718 // Users can call this multiple times without doing any harm
5719 if (isset(context::$cache_preloaded[$courseid])) {
5720 return;
5722 $coursecontext = context_course::instance($courseid);
5723 $coursecontext->get_child_contexts();
5725 context::$cache_preloaded[$courseid] = true;
5729 * Delete context instance
5731 * @static
5732 * @param int $contextlevel
5733 * @param int $instanceid
5734 * @return void
5736 public static function delete_instance($contextlevel, $instanceid) {
5737 global $DB;
5739 // double check the context still exists
5740 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5741 $context = context::create_instance_from_record($record);
5742 $context->delete();
5743 } else {
5744 // we should try to purge the cache anyway
5749 * Returns the name of specified context level
5751 * @static
5752 * @param int $contextlevel
5753 * @return string name of the context level
5755 public static function get_level_name($contextlevel) {
5756 $classname = context_helper::get_class_for_level($contextlevel);
5757 return $classname::get_level_name();
5761 * not used
5763 public function get_url() {
5767 * not used
5769 public function get_capabilities() {
5775 * System context class
5777 * @package core_access
5778 * @category access
5779 * @copyright Petr Skoda {@link http://skodak.org}
5780 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5781 * @since 2.2
5783 class context_system extends context {
5785 * Please use context_system::instance() if you need the instance of context.
5787 * @param stdClass $record
5789 protected function __construct(stdClass $record) {
5790 parent::__construct($record);
5791 if ($record->contextlevel != CONTEXT_SYSTEM) {
5792 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5797 * Returns human readable context level name.
5799 * @static
5800 * @return string the human readable context level name.
5802 public static function get_level_name() {
5803 return get_string('coresystem');
5807 * Returns human readable context identifier.
5809 * @param boolean $withprefix does not apply to system context
5810 * @param boolean $short does not apply to system context
5811 * @return string the human readable context name.
5813 public function get_context_name($withprefix = true, $short = false) {
5814 return self::get_level_name();
5818 * Returns the most relevant URL for this context.
5820 * @return moodle_url
5822 public function get_url() {
5823 return new moodle_url('/');
5827 * Returns array of relevant context capability records.
5829 * @return array
5831 public function get_capabilities() {
5832 global $DB;
5834 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5836 $params = array();
5837 $sql = "SELECT *
5838 FROM {capabilities}";
5840 return $DB->get_records_sql($sql.' '.$sort, $params);
5844 * Create missing context instances at system context
5845 * @static
5847 protected static function create_level_instances() {
5848 // nothing to do here, the system context is created automatically in installer
5849 self::instance(0);
5853 * Returns system context instance.
5855 * @static
5856 * @param int $instanceid
5857 * @param int $strictness
5858 * @param bool $cache
5859 * @return context_system context instance
5861 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5862 global $DB;
5864 if ($instanceid != 0) {
5865 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5868 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5869 if (!isset(context::$systemcontext)) {
5870 $record = new stdClass();
5871 $record->id = SYSCONTEXTID;
5872 $record->contextlevel = CONTEXT_SYSTEM;
5873 $record->instanceid = 0;
5874 $record->path = '/'.SYSCONTEXTID;
5875 $record->depth = 1;
5876 context::$systemcontext = new context_system($record);
5878 return context::$systemcontext;
5882 try {
5883 // we ignore the strictness completely because system context must except except during install
5884 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5885 } catch (dml_exception $e) {
5886 //table or record does not exist
5887 if (!during_initial_install()) {
5888 // do not mess with system context after install, it simply must exist
5889 throw $e;
5891 $record = null;
5894 if (!$record) {
5895 $record = new stdClass();
5896 $record->contextlevel = CONTEXT_SYSTEM;
5897 $record->instanceid = 0;
5898 $record->depth = 1;
5899 $record->path = null; //not known before insert
5901 try {
5902 if ($DB->count_records('context')) {
5903 // contexts already exist, this is very weird, system must be first!!!
5904 return null;
5906 if (defined('SYSCONTEXTID')) {
5907 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5908 $record->id = SYSCONTEXTID;
5909 $DB->import_record('context', $record);
5910 $DB->get_manager()->reset_sequence('context');
5911 } else {
5912 $record->id = $DB->insert_record('context', $record);
5914 } catch (dml_exception $e) {
5915 // can not create context - table does not exist yet, sorry
5916 return null;
5920 if ($record->instanceid != 0) {
5921 // this is very weird, somebody must be messing with context table
5922 debugging('Invalid system context detected');
5925 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5926 // fix path if necessary, initial install or path reset
5927 $record->depth = 1;
5928 $record->path = '/'.$record->id;
5929 $DB->update_record('context', $record);
5932 if (!defined('SYSCONTEXTID')) {
5933 define('SYSCONTEXTID', $record->id);
5936 context::$systemcontext = new context_system($record);
5937 return context::$systemcontext;
5941 * Returns all site contexts except the system context, DO NOT call on production servers!!
5943 * Contexts are not cached.
5945 * @return array
5947 public function get_child_contexts() {
5948 global $DB;
5950 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5952 // Just get all the contexts except for CONTEXT_SYSTEM level
5953 // and hope we don't OOM in the process - don't cache
5954 $sql = "SELECT c.*
5955 FROM {context} c
5956 WHERE contextlevel > ".CONTEXT_SYSTEM;
5957 $records = $DB->get_records_sql($sql);
5959 $result = array();
5960 foreach ($records as $record) {
5961 $result[$record->id] = context::create_instance_from_record($record);
5964 return $result;
5968 * Returns sql necessary for purging of stale context instances.
5970 * @static
5971 * @return string cleanup SQL
5973 protected static function get_cleanup_sql() {
5974 $sql = "
5975 SELECT c.*
5976 FROM {context} c
5977 WHERE 1=2
5980 return $sql;
5984 * Rebuild context paths and depths at system context level.
5986 * @static
5987 * @param bool $force
5989 protected static function build_paths($force) {
5990 global $DB;
5992 /* note: ignore $force here, we always do full test of system context */
5994 // exactly one record must exist
5995 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5997 if ($record->instanceid != 0) {
5998 debugging('Invalid system context detected');
6001 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
6002 debugging('Invalid SYSCONTEXTID detected');
6005 if ($record->depth != 1 or $record->path != '/'.$record->id) {
6006 // fix path if necessary, initial install or path reset
6007 $record->depth = 1;
6008 $record->path = '/'.$record->id;
6009 $DB->update_record('context', $record);
6016 * User context class
6018 * @package core_access
6019 * @category access
6020 * @copyright Petr Skoda {@link http://skodak.org}
6021 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6022 * @since 2.2
6024 class context_user extends context {
6026 * Please use context_user::instance($userid) if you need the instance of context.
6027 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6029 * @param stdClass $record
6031 protected function __construct(stdClass $record) {
6032 parent::__construct($record);
6033 if ($record->contextlevel != CONTEXT_USER) {
6034 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
6039 * Returns human readable context level name.
6041 * @static
6042 * @return string the human readable context level name.
6044 public static function get_level_name() {
6045 return get_string('user');
6049 * Returns human readable context identifier.
6051 * @param boolean $withprefix whether to prefix the name of the context with User
6052 * @param boolean $short does not apply to user context
6053 * @return string the human readable context name.
6055 public function get_context_name($withprefix = true, $short = false) {
6056 global $DB;
6058 $name = '';
6059 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
6060 if ($withprefix){
6061 $name = get_string('user').': ';
6063 $name .= fullname($user);
6065 return $name;
6069 * Returns the most relevant URL for this context.
6071 * @return moodle_url
6073 public function get_url() {
6074 global $COURSE;
6076 if ($COURSE->id == SITEID) {
6077 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
6078 } else {
6079 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
6081 return $url;
6085 * Returns array of relevant context capability records.
6087 * @return array
6089 public function get_capabilities() {
6090 global $DB;
6092 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6094 $extracaps = array('moodle/grade:viewall');
6095 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6096 $sql = "SELECT *
6097 FROM {capabilities}
6098 WHERE contextlevel = ".CONTEXT_USER."
6099 OR name $extra";
6101 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
6105 * Returns user context instance.
6107 * @static
6108 * @param int $instanceid
6109 * @param int $strictness
6110 * @return context_user context instance
6112 public static function instance($instanceid, $strictness = MUST_EXIST) {
6113 global $DB;
6115 if ($context = context::cache_get(CONTEXT_USER, $instanceid)) {
6116 return $context;
6119 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER, 'instanceid'=>$instanceid))) {
6120 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
6121 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
6125 if ($record) {
6126 $context = new context_user($record);
6127 context::cache_add($context);
6128 return $context;
6131 return false;
6135 * Create missing context instances at user context level
6136 * @static
6138 protected static function create_level_instances() {
6139 global $DB;
6141 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6142 SELECT ".CONTEXT_USER.", u.id
6143 FROM {user} u
6144 WHERE u.deleted = 0
6145 AND NOT EXISTS (SELECT 'x'
6146 FROM {context} cx
6147 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
6148 $DB->execute($sql);
6152 * Returns sql necessary for purging of stale context instances.
6154 * @static
6155 * @return string cleanup SQL
6157 protected static function get_cleanup_sql() {
6158 $sql = "
6159 SELECT c.*
6160 FROM {context} c
6161 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
6162 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
6165 return $sql;
6169 * Rebuild context paths and depths at user context level.
6171 * @static
6172 * @param bool $force
6174 protected static function build_paths($force) {
6175 global $DB;
6177 // First update normal users.
6178 $path = $DB->sql_concat('?', 'id');
6179 $pathstart = '/' . SYSCONTEXTID . '/';
6180 $params = array($pathstart);
6182 if ($force) {
6183 $where = "depth <> 2 OR path IS NULL OR path <> ({$path})";
6184 $params[] = $pathstart;
6185 } else {
6186 $where = "depth = 0 OR path IS NULL";
6189 $sql = "UPDATE {context}
6190 SET depth = 2,
6191 path = {$path}
6192 WHERE contextlevel = " . CONTEXT_USER . "
6193 AND ($where)";
6194 $DB->execute($sql, $params);
6200 * Course category context class
6202 * @package core_access
6203 * @category access
6204 * @copyright Petr Skoda {@link http://skodak.org}
6205 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6206 * @since 2.2
6208 class context_coursecat extends context {
6210 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
6211 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6213 * @param stdClass $record
6215 protected function __construct(stdClass $record) {
6216 parent::__construct($record);
6217 if ($record->contextlevel != CONTEXT_COURSECAT) {
6218 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
6223 * Returns human readable context level name.
6225 * @static
6226 * @return string the human readable context level name.
6228 public static function get_level_name() {
6229 return get_string('category');
6233 * Returns human readable context identifier.
6235 * @param boolean $withprefix whether to prefix the name of the context with Category
6236 * @param boolean $short does not apply to course categories
6237 * @return string the human readable context name.
6239 public function get_context_name($withprefix = true, $short = false) {
6240 global $DB;
6242 $name = '';
6243 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
6244 if ($withprefix){
6245 $name = get_string('category').': ';
6247 $name .= format_string($category->name, true, array('context' => $this));
6249 return $name;
6253 * Returns the most relevant URL for this context.
6255 * @return moodle_url
6257 public function get_url() {
6258 return new moodle_url('/course/category.php', array('id'=>$this->_instanceid));
6262 * Returns array of relevant context capability records.
6264 * @return array
6266 public function get_capabilities() {
6267 global $DB;
6269 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6271 $params = array();
6272 $sql = "SELECT *
6273 FROM {capabilities}
6274 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6276 return $DB->get_records_sql($sql.' '.$sort, $params);
6280 * Returns course category context instance.
6282 * @static
6283 * @param int $instanceid
6284 * @param int $strictness
6285 * @return context_coursecat context instance
6287 public static function instance($instanceid, $strictness = MUST_EXIST) {
6288 global $DB;
6290 if ($context = context::cache_get(CONTEXT_COURSECAT, $instanceid)) {
6291 return $context;
6294 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT, 'instanceid'=>$instanceid))) {
6295 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
6296 if ($category->parent) {
6297 $parentcontext = context_coursecat::instance($category->parent);
6298 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
6299 } else {
6300 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
6305 if ($record) {
6306 $context = new context_coursecat($record);
6307 context::cache_add($context);
6308 return $context;
6311 return false;
6315 * Returns immediate child contexts of category and all subcategories,
6316 * children of subcategories and courses are not returned.
6318 * @return array
6320 public function get_child_contexts() {
6321 global $DB;
6323 $sql = "SELECT ctx.*
6324 FROM {context} ctx
6325 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
6326 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
6327 $records = $DB->get_records_sql($sql, $params);
6329 $result = array();
6330 foreach ($records as $record) {
6331 $result[$record->id] = context::create_instance_from_record($record);
6334 return $result;
6338 * Create missing context instances at course category context level
6339 * @static
6341 protected static function create_level_instances() {
6342 global $DB;
6344 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6345 SELECT ".CONTEXT_COURSECAT.", cc.id
6346 FROM {course_categories} cc
6347 WHERE NOT EXISTS (SELECT 'x'
6348 FROM {context} cx
6349 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
6350 $DB->execute($sql);
6354 * Returns sql necessary for purging of stale context instances.
6356 * @static
6357 * @return string cleanup SQL
6359 protected static function get_cleanup_sql() {
6360 $sql = "
6361 SELECT c.*
6362 FROM {context} c
6363 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6364 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6367 return $sql;
6371 * Rebuild context paths and depths at course category context level.
6373 * @static
6374 * @param bool $force
6376 protected static function build_paths($force) {
6377 global $DB;
6379 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6380 if ($force) {
6381 $ctxemptyclause = $emptyclause = '';
6382 } else {
6383 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6384 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6387 $base = '/'.SYSCONTEXTID;
6389 // Normal top level categories
6390 $sql = "UPDATE {context}
6391 SET depth=2,
6392 path=".$DB->sql_concat("'$base/'", 'id')."
6393 WHERE contextlevel=".CONTEXT_COURSECAT."
6394 AND EXISTS (SELECT 'x'
6395 FROM {course_categories} cc
6396 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6397 $emptyclause";
6398 $DB->execute($sql);
6400 // Deeper categories - one query per depthlevel
6401 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6402 for ($n=2; $n<=$maxdepth; $n++) {
6403 $sql = "INSERT INTO {context_temp} (id, path, depth)
6404 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6405 FROM {context} ctx
6406 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6407 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6408 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6409 $ctxemptyclause";
6410 $trans = $DB->start_delegated_transaction();
6411 $DB->delete_records('context_temp');
6412 $DB->execute($sql);
6413 context::merge_context_temp_table();
6414 $DB->delete_records('context_temp');
6415 $trans->allow_commit();
6424 * Course context class
6426 * @package core_access
6427 * @category access
6428 * @copyright Petr Skoda {@link http://skodak.org}
6429 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6430 * @since 2.2
6432 class context_course extends context {
6434 * Please use context_course::instance($courseid) if you need the instance of context.
6435 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6437 * @param stdClass $record
6439 protected function __construct(stdClass $record) {
6440 parent::__construct($record);
6441 if ($record->contextlevel != CONTEXT_COURSE) {
6442 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6447 * Returns human readable context level name.
6449 * @static
6450 * @return string the human readable context level name.
6452 public static function get_level_name() {
6453 return get_string('course');
6457 * Returns human readable context identifier.
6459 * @param boolean $withprefix whether to prefix the name of the context with Course
6460 * @param boolean $short whether to use the short name of the thing.
6461 * @return string the human readable context name.
6463 public function get_context_name($withprefix = true, $short = false) {
6464 global $DB;
6466 $name = '';
6467 if ($this->_instanceid == SITEID) {
6468 $name = get_string('frontpage', 'admin');
6469 } else {
6470 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6471 if ($withprefix){
6472 $name = get_string('course').': ';
6474 if ($short){
6475 $name .= format_string($course->shortname, true, array('context' => $this));
6476 } else {
6477 $name .= format_string(get_course_display_name_for_list($course));
6481 return $name;
6485 * Returns the most relevant URL for this context.
6487 * @return moodle_url
6489 public function get_url() {
6490 if ($this->_instanceid != SITEID) {
6491 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6494 return new moodle_url('/');
6498 * Returns array of relevant context capability records.
6500 * @return array
6502 public function get_capabilities() {
6503 global $DB;
6505 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6507 $params = array();
6508 $sql = "SELECT *
6509 FROM {capabilities}
6510 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6512 return $DB->get_records_sql($sql.' '.$sort, $params);
6516 * Is this context part of any course? If yes return course context.
6518 * @param bool $strict true means throw exception if not found, false means return false if not found
6519 * @return course_context context of the enclosing course, null if not found or exception
6521 public function get_course_context($strict = true) {
6522 return $this;
6526 * Returns course context instance.
6528 * @static
6529 * @param int $instanceid
6530 * @param int $strictness
6531 * @return context_course context instance
6533 public static function instance($instanceid, $strictness = MUST_EXIST) {
6534 global $DB;
6536 if ($context = context::cache_get(CONTEXT_COURSE, $instanceid)) {
6537 return $context;
6540 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$instanceid))) {
6541 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6542 if ($course->category) {
6543 $parentcontext = context_coursecat::instance($course->category);
6544 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6545 } else {
6546 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6551 if ($record) {
6552 $context = new context_course($record);
6553 context::cache_add($context);
6554 return $context;
6557 return false;
6561 * Create missing context instances at course context level
6562 * @static
6564 protected static function create_level_instances() {
6565 global $DB;
6567 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6568 SELECT ".CONTEXT_COURSE.", c.id
6569 FROM {course} c
6570 WHERE NOT EXISTS (SELECT 'x'
6571 FROM {context} cx
6572 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6573 $DB->execute($sql);
6577 * Returns sql necessary for purging of stale context instances.
6579 * @static
6580 * @return string cleanup SQL
6582 protected static function get_cleanup_sql() {
6583 $sql = "
6584 SELECT c.*
6585 FROM {context} c
6586 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6587 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6590 return $sql;
6594 * Rebuild context paths and depths at course context level.
6596 * @static
6597 * @param bool $force
6599 protected static function build_paths($force) {
6600 global $DB;
6602 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6603 if ($force) {
6604 $ctxemptyclause = $emptyclause = '';
6605 } else {
6606 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6607 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6610 $base = '/'.SYSCONTEXTID;
6612 // Standard frontpage
6613 $sql = "UPDATE {context}
6614 SET depth = 2,
6615 path = ".$DB->sql_concat("'$base/'", 'id')."
6616 WHERE contextlevel = ".CONTEXT_COURSE."
6617 AND EXISTS (SELECT 'x'
6618 FROM {course} c
6619 WHERE c.id = {context}.instanceid AND c.category = 0)
6620 $emptyclause";
6621 $DB->execute($sql);
6623 // standard courses
6624 $sql = "INSERT INTO {context_temp} (id, path, depth)
6625 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6626 FROM {context} ctx
6627 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6628 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6629 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6630 $ctxemptyclause";
6631 $trans = $DB->start_delegated_transaction();
6632 $DB->delete_records('context_temp');
6633 $DB->execute($sql);
6634 context::merge_context_temp_table();
6635 $DB->delete_records('context_temp');
6636 $trans->allow_commit();
6643 * Course module context class
6645 * @package core_access
6646 * @category access
6647 * @copyright Petr Skoda {@link http://skodak.org}
6648 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6649 * @since 2.2
6651 class context_module extends context {
6653 * Please use context_module::instance($cmid) if you need the instance of context.
6654 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6656 * @param stdClass $record
6658 protected function __construct(stdClass $record) {
6659 parent::__construct($record);
6660 if ($record->contextlevel != CONTEXT_MODULE) {
6661 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6666 * Returns human readable context level name.
6668 * @static
6669 * @return string the human readable context level name.
6671 public static function get_level_name() {
6672 return get_string('activitymodule');
6676 * Returns human readable context identifier.
6678 * @param boolean $withprefix whether to prefix the name of the context with the
6679 * module name, e.g. Forum, Glossary, etc.
6680 * @param boolean $short does not apply to module context
6681 * @return string the human readable context name.
6683 public function get_context_name($withprefix = true, $short = false) {
6684 global $DB;
6686 $name = '';
6687 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6688 FROM {course_modules} cm
6689 JOIN {modules} md ON md.id = cm.module
6690 WHERE cm.id = ?", array($this->_instanceid))) {
6691 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6692 if ($withprefix){
6693 $name = get_string('modulename', $cm->modname).': ';
6695 $name .= format_string($mod->name, true, array('context' => $this));
6698 return $name;
6702 * Returns the most relevant URL for this context.
6704 * @return moodle_url
6706 public function get_url() {
6707 global $DB;
6709 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6710 FROM {course_modules} cm
6711 JOIN {modules} md ON md.id = cm.module
6712 WHERE cm.id = ?", array($this->_instanceid))) {
6713 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6716 return new moodle_url('/');
6720 * Returns array of relevant context capability records.
6722 * @return array
6724 public function get_capabilities() {
6725 global $DB, $CFG;
6727 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6729 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6730 $module = $DB->get_record('modules', array('id'=>$cm->module));
6732 $subcaps = array();
6733 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6734 if (file_exists($subpluginsfile)) {
6735 $subplugins = array(); // should be redefined in the file
6736 include($subpluginsfile);
6737 if (!empty($subplugins)) {
6738 foreach (array_keys($subplugins) as $subplugintype) {
6739 foreach (array_keys(get_plugin_list($subplugintype)) as $subpluginname) {
6740 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6746 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6747 $extracaps = array();
6748 if (file_exists($modfile)) {
6749 include_once($modfile);
6750 $modfunction = $module->name.'_get_extra_capabilities';
6751 if (function_exists($modfunction)) {
6752 $extracaps = $modfunction();
6756 $extracaps = array_merge($subcaps, $extracaps);
6757 $extra = '';
6758 list($extra, $params) = $DB->get_in_or_equal(
6759 $extracaps, SQL_PARAMS_NAMED, 'cap0', true, '');
6760 if (!empty($extra)) {
6761 $extra = "OR name $extra";
6763 $sql = "SELECT *
6764 FROM {capabilities}
6765 WHERE (contextlevel = ".CONTEXT_MODULE."
6766 AND (component = :component OR component = 'moodle'))
6767 $extra";
6768 $params['component'] = "mod_$module->name";
6770 return $DB->get_records_sql($sql.' '.$sort, $params);
6774 * Is this context part of any course? If yes return course context.
6776 * @param bool $strict true means throw exception if not found, false means return false if not found
6777 * @return course_context context of the enclosing course, null if not found or exception
6779 public function get_course_context($strict = true) {
6780 return $this->get_parent_context();
6784 * Returns module context instance.
6786 * @static
6787 * @param int $instanceid
6788 * @param int $strictness
6789 * @return context_module context instance
6791 public static function instance($instanceid, $strictness = MUST_EXIST) {
6792 global $DB;
6794 if ($context = context::cache_get(CONTEXT_MODULE, $instanceid)) {
6795 return $context;
6798 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$instanceid))) {
6799 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
6800 $parentcontext = context_course::instance($cm->course);
6801 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6805 if ($record) {
6806 $context = new context_module($record);
6807 context::cache_add($context);
6808 return $context;
6811 return false;
6815 * Create missing context instances at module context level
6816 * @static
6818 protected static function create_level_instances() {
6819 global $DB;
6821 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6822 SELECT ".CONTEXT_MODULE.", cm.id
6823 FROM {course_modules} cm
6824 WHERE NOT EXISTS (SELECT 'x'
6825 FROM {context} cx
6826 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6827 $DB->execute($sql);
6831 * Returns sql necessary for purging of stale context instances.
6833 * @static
6834 * @return string cleanup SQL
6836 protected static function get_cleanup_sql() {
6837 $sql = "
6838 SELECT c.*
6839 FROM {context} c
6840 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6841 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6844 return $sql;
6848 * Rebuild context paths and depths at module context level.
6850 * @static
6851 * @param bool $force
6853 protected static function build_paths($force) {
6854 global $DB;
6856 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6857 if ($force) {
6858 $ctxemptyclause = '';
6859 } else {
6860 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6863 $sql = "INSERT INTO {context_temp} (id, path, depth)
6864 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6865 FROM {context} ctx
6866 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6867 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6868 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6869 $ctxemptyclause";
6870 $trans = $DB->start_delegated_transaction();
6871 $DB->delete_records('context_temp');
6872 $DB->execute($sql);
6873 context::merge_context_temp_table();
6874 $DB->delete_records('context_temp');
6875 $trans->allow_commit();
6882 * Block context class
6884 * @package core_access
6885 * @category access
6886 * @copyright Petr Skoda {@link http://skodak.org}
6887 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6888 * @since 2.2
6890 class context_block extends context {
6892 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6893 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6895 * @param stdClass $record
6897 protected function __construct(stdClass $record) {
6898 parent::__construct($record);
6899 if ($record->contextlevel != CONTEXT_BLOCK) {
6900 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6905 * Returns human readable context level name.
6907 * @static
6908 * @return string the human readable context level name.
6910 public static function get_level_name() {
6911 return get_string('block');
6915 * Returns human readable context identifier.
6917 * @param boolean $withprefix whether to prefix the name of the context with Block
6918 * @param boolean $short does not apply to block context
6919 * @return string the human readable context name.
6921 public function get_context_name($withprefix = true, $short = false) {
6922 global $DB, $CFG;
6924 $name = '';
6925 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
6926 global $CFG;
6927 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6928 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6929 $blockname = "block_$blockinstance->blockname";
6930 if ($blockobject = new $blockname()) {
6931 if ($withprefix){
6932 $name = get_string('block').': ';
6934 $name .= $blockobject->title;
6938 return $name;
6942 * Returns the most relevant URL for this context.
6944 * @return moodle_url
6946 public function get_url() {
6947 $parentcontexts = $this->get_parent_context();
6948 return $parentcontexts->get_url();
6952 * Returns array of relevant context capability records.
6954 * @return array
6956 public function get_capabilities() {
6957 global $DB;
6959 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6961 $params = array();
6962 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
6964 $extra = '';
6965 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
6966 if ($extracaps) {
6967 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6968 $extra = "OR name $extra";
6971 $sql = "SELECT *
6972 FROM {capabilities}
6973 WHERE (contextlevel = ".CONTEXT_BLOCK."
6974 AND component = :component)
6975 $extra";
6976 $params['component'] = 'block_' . $bi->blockname;
6978 return $DB->get_records_sql($sql.' '.$sort, $params);
6982 * Is this context part of any course? If yes return course context.
6984 * @param bool $strict true means throw exception if not found, false means return false if not found
6985 * @return course_context context of the enclosing course, null if not found or exception
6987 public function get_course_context($strict = true) {
6988 $parentcontext = $this->get_parent_context();
6989 return $parentcontext->get_course_context($strict);
6993 * Returns block context instance.
6995 * @static
6996 * @param int $instanceid
6997 * @param int $strictness
6998 * @return context_block context instance
7000 public static function instance($instanceid, $strictness = MUST_EXIST) {
7001 global $DB;
7003 if ($context = context::cache_get(CONTEXT_BLOCK, $instanceid)) {
7004 return $context;
7007 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$instanceid))) {
7008 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
7009 $parentcontext = context::instance_by_id($bi->parentcontextid);
7010 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
7014 if ($record) {
7015 $context = new context_block($record);
7016 context::cache_add($context);
7017 return $context;
7020 return false;
7024 * Block do not have child contexts...
7025 * @return array
7027 public function get_child_contexts() {
7028 return array();
7032 * Create missing context instances at block context level
7033 * @static
7035 protected static function create_level_instances() {
7036 global $DB;
7038 $sql = "INSERT INTO {context} (contextlevel, instanceid)
7039 SELECT ".CONTEXT_BLOCK.", bi.id
7040 FROM {block_instances} bi
7041 WHERE NOT EXISTS (SELECT 'x'
7042 FROM {context} cx
7043 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
7044 $DB->execute($sql);
7048 * Returns sql necessary for purging of stale context instances.
7050 * @static
7051 * @return string cleanup SQL
7053 protected static function get_cleanup_sql() {
7054 $sql = "
7055 SELECT c.*
7056 FROM {context} c
7057 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
7058 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
7061 return $sql;
7065 * Rebuild context paths and depths at block context level.
7067 * @static
7068 * @param bool $force
7070 protected static function build_paths($force) {
7071 global $DB;
7073 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
7074 if ($force) {
7075 $ctxemptyclause = '';
7076 } else {
7077 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
7080 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
7081 $sql = "INSERT INTO {context_temp} (id, path, depth)
7082 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
7083 FROM {context} ctx
7084 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
7085 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
7086 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
7087 $ctxemptyclause";
7088 $trans = $DB->start_delegated_transaction();
7089 $DB->delete_records('context_temp');
7090 $DB->execute($sql);
7091 context::merge_context_temp_table();
7092 $DB->delete_records('context_temp');
7093 $trans->allow_commit();
7099 // ============== DEPRECATED FUNCTIONS ==========================================
7100 // Old context related functions were deprecated in 2.0, it is recommended
7101 // to use context classes in new code. Old function can be used when
7102 // creating patches that are supposed to be backported to older stable branches.
7103 // These deprecated functions will not be removed in near future,
7104 // before removing devs will be warned with a debugging message first,
7105 // then we will add error message and only after that we can remove the functions
7106 // completely.
7110 * Not available any more, use load_temp_course_role() instead.
7112 * @deprecated since 2.2
7113 * @param stdClass $context
7114 * @param int $roleid
7115 * @param array $accessdata
7116 * @return array
7118 function load_temp_role($context, $roleid, array $accessdata) {
7119 debugging('load_temp_role() is deprecated, please use load_temp_course_role() instead, temp role not loaded.');
7120 return $accessdata;
7124 * Not available any more, use remove_temp_course_roles() instead.
7126 * @deprecated since 2.2
7127 * @param stdClass $context
7128 * @param array $accessdata
7129 * @return array access data
7131 function remove_temp_roles($context, array $accessdata) {
7132 debugging('remove_temp_role() is deprecated, please use remove_temp_course_roles() instead.');
7133 return $accessdata;
7137 * Returns system context or null if can not be created yet.
7139 * @deprecated since 2.2, use context_system::instance()
7140 * @param bool $cache use caching
7141 * @return context system context (null if context table not created yet)
7143 function get_system_context($cache = true) {
7144 return context_system::instance(0, IGNORE_MISSING, $cache);
7148 * Get the context instance as an object. This function will create the
7149 * context instance if it does not exist yet.
7151 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
7152 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
7153 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
7154 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
7155 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
7156 * MUST_EXIST means throw exception if no record or multiple records found
7157 * @return context The context object.
7159 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
7160 $instances = (array)$instance;
7161 $contexts = array();
7163 $classname = context_helper::get_class_for_level($contextlevel);
7165 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
7166 foreach ($instances as $inst) {
7167 $contexts[$inst] = $classname::instance($inst, $strictness);
7170 if (is_array($instance)) {
7171 return $contexts;
7172 } else {
7173 return $contexts[$instance];
7178 * Get a context instance as an object, from a given context id.
7180 * @deprecated since 2.2, use context::instance_by_id($id) instead
7181 * @param int $id context id
7182 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
7183 * MUST_EXIST means throw exception if no record or multiple records found
7184 * @return context|bool the context object or false if not found.
7186 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
7187 return context::instance_by_id($id, $strictness);
7191 * Recursive function which, given a context, find all parent context ids,
7192 * and return the array in reverse order, i.e. parent first, then grand
7193 * parent, etc.
7195 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
7196 * @param context $context
7197 * @param bool $includeself optional, defaults to false
7198 * @return array
7200 function get_parent_contexts(context $context, $includeself = false) {
7201 return $context->get_parent_context_ids($includeself);
7205 * Return the id of the parent of this context, or false if there is no parent (only happens if this
7206 * is the site context.)
7208 * @deprecated since 2.2, use $context->get_parent_context() instead
7209 * @param context $context
7210 * @return integer the id of the parent context.
7212 function get_parent_contextid(context $context) {
7213 if ($parent = $context->get_parent_context()) {
7214 return $parent->id;
7215 } else {
7216 return false;
7221 * Recursive function which, given a context, find all its children context ids.
7223 * For course category contexts it will return immediate children only categories and courses.
7224 * It will NOT recurse into courses or child categories.
7225 * If you want to do that, call it on the returned courses/categories.
7227 * When called for a course context, it will return the modules and blocks
7228 * displayed in the course page.
7230 * If called on a user/course/module context it _will_ populate the cache with the appropriate
7231 * contexts ;-)
7233 * @deprecated since 2.2, use $context->get_child_contexts() instead
7234 * @param context $context
7235 * @return array Array of child records
7237 function get_child_contexts(context $context) {
7238 return $context->get_child_contexts();
7242 * Precreates all contexts including all parents
7244 * @deprecated since 2.2
7245 * @param int $contextlevel empty means all
7246 * @param bool $buildpaths update paths and depths
7247 * @return void
7249 function create_contexts($contextlevel = null, $buildpaths = true) {
7250 context_helper::create_instances($contextlevel, $buildpaths);
7254 * Remove stale context records
7256 * @deprecated since 2.2, use context_helper::cleanup_instances() instead
7257 * @return bool
7259 function cleanup_contexts() {
7260 context_helper::cleanup_instances();
7261 return true;
7265 * Populate context.path and context.depth where missing.
7267 * @deprecated since 2.2, use context_helper::build_all_paths() instead
7268 * @param bool $force force a complete rebuild of the path and depth fields, defaults to false
7269 * @return void
7271 function build_context_path($force = false) {
7272 context_helper::build_all_paths($force);
7276 * Rebuild all related context depth and path caches
7278 * @deprecated since 2.2
7279 * @param array $fixcontexts array of contexts, strongtyped
7280 * @return void
7282 function rebuild_contexts(array $fixcontexts) {
7283 foreach ($fixcontexts as $fixcontext) {
7284 $fixcontext->reset_paths(false);
7286 context_helper::build_all_paths(false);
7290 * Preloads all contexts relating to a course: course, modules. Block contexts
7291 * are no longer loaded here. The contexts for all the blocks on the current
7292 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
7294 * @deprecated since 2.2
7295 * @param int $courseid Course ID
7296 * @return void
7298 function preload_course_contexts($courseid) {
7299 context_helper::preload_course($courseid);
7303 * Preloads context information together with instances.
7304 * Use context_instance_preload() to strip the context info from the record and cache the context instance.
7306 * @deprecated since 2.2
7307 * @param string $joinon for example 'u.id'
7308 * @param string $contextlevel context level of instance in $joinon
7309 * @param string $tablealias context table alias
7310 * @return array with two values - select and join part
7312 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
7313 $select = ", ".context_helper::get_preload_record_columns_sql($tablealias);
7314 $join = "LEFT JOIN {context} $tablealias ON ($tablealias.instanceid = $joinon AND $tablealias.contextlevel = $contextlevel)";
7315 return array($select, $join);
7319 * Preloads context information from db record and strips the cached info.
7320 * The db request has to contain both the $join and $select from context_instance_preload_sql()
7322 * @deprecated since 2.2
7323 * @param stdClass $rec
7324 * @return void (modifies $rec)
7326 function context_instance_preload(stdClass $rec) {
7327 context_helper::preload_from_record($rec);
7331 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
7333 * @deprecated since 2.2, use $context->mark_dirty() instead
7334 * @param string $path context path
7336 function mark_context_dirty($path) {
7337 global $CFG, $USER, $ACCESSLIB_PRIVATE;
7339 if (during_initial_install()) {
7340 return;
7343 // only if it is a non-empty string
7344 if (is_string($path) && $path !== '') {
7345 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
7346 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
7347 $ACCESSLIB_PRIVATE->dirtycontexts[$path] = 1;
7348 } else {
7349 if (CLI_SCRIPT) {
7350 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
7351 } else {
7352 if (isset($USER->access['time'])) {
7353 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
7354 } else {
7355 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
7357 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
7364 * Update the path field of the context and all dep. subcontexts that follow
7366 * Update the path field of the context and
7367 * all the dependent subcontexts that follow
7368 * the move.
7370 * The most important thing here is to be as
7371 * DB efficient as possible. This op can have a
7372 * massive impact in the DB.
7374 * @deprecated since 2.2
7375 * @param context $context context obj
7376 * @param context $newparent new parent obj
7377 * @return void
7379 function context_moved(context $context, context $newparent) {
7380 $context->update_moved($newparent);
7384 * Remove a context record and any dependent entries,
7385 * removes context from static context cache too
7387 * @deprecated since 2.2, use $context->delete_content() instead
7388 * @param int $contextlevel
7389 * @param int $instanceid
7390 * @param bool $deleterecord false means keep record for now
7391 * @return bool returns true or throws an exception
7393 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
7394 if ($deleterecord) {
7395 context_helper::delete_instance($contextlevel, $instanceid);
7396 } else {
7397 $classname = context_helper::get_class_for_level($contextlevel);
7398 if ($context = $classname::instance($instanceid, IGNORE_MISSING)) {
7399 $context->delete_content();
7403 return true;
7407 * Returns context level name
7409 * @deprecated since 2.2
7410 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
7411 * @return string the name for this type of context.
7413 function get_contextlevel_name($contextlevel) {
7414 return context_helper::get_level_name($contextlevel);
7418 * Prints human readable context identifier.
7420 * @deprecated since 2.2
7421 * @param context $context the context.
7422 * @param boolean $withprefix whether to prefix the name of the context with the
7423 * type of context, e.g. User, Course, Forum, etc.
7424 * @param boolean $short whether to user the short name of the thing. Only applies
7425 * to course contexts
7426 * @return string the human readable context name.
7428 function print_context_name(context $context, $withprefix = true, $short = false) {
7429 return $context->get_context_name($withprefix, $short);
7433 * Get a URL for a context, if there is a natural one. For example, for
7434 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
7435 * user profile page.
7437 * @deprecated since 2.2
7438 * @param context $context the context.
7439 * @return moodle_url
7441 function get_context_url(context $context) {
7442 return $context->get_url();
7446 * Is this context part of any course? if yes return course context,
7447 * if not return null or throw exception.
7449 * @deprecated since 2.2, use $context->get_course_context() instead
7450 * @param context $context
7451 * @return course_context context of the enclosing course, null if not found or exception
7453 function get_course_context(context $context) {
7454 return $context->get_course_context(true);
7458 * Returns current course id or null if outside of course based on context parameter.
7460 * @deprecated since 2.2, use $context->get_course_context instead
7461 * @param context $context
7462 * @return int|bool related course id or false
7464 function get_courseid_from_context(context $context) {
7465 if ($coursecontext = $context->get_course_context(false)) {
7466 return $coursecontext->instanceid;
7467 } else {
7468 return false;
7473 * Get an array of courses where cap requested is available
7474 * and user is enrolled, this can be relatively slow.
7476 * @deprecated since 2.2, use enrol_get_users_courses() instead
7477 * @param int $userid A user id. By default (null) checks the permissions of the current user.
7478 * @param string $cap - name of the capability
7479 * @param array $accessdata_ignored
7480 * @param bool $doanything_ignored
7481 * @param string $sort - sorting fields - prefix each fieldname with "c."
7482 * @param array $fields - additional fields you are interested in...
7483 * @param int $limit_ignored
7484 * @return array $courses - ordered array of course objects - see notes above
7486 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
7488 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
7489 foreach ($courses as $id=>$course) {
7490 $context = context_course::instance($id);
7491 if (!has_capability($cap, $context, $userid)) {
7492 unset($courses[$id]);
7496 return $courses;
7500 * Extracts the relevant capabilities given a contextid.
7501 * All case based, example an instance of forum context.
7502 * Will fetch all forum related capabilities, while course contexts
7503 * Will fetch all capabilities
7505 * capabilities
7506 * `name` varchar(150) NOT NULL,
7507 * `captype` varchar(50) NOT NULL,
7508 * `contextlevel` int(10) NOT NULL,
7509 * `component` varchar(100) NOT NULL,
7511 * @deprecated since 2.2
7512 * @param context $context
7513 * @return array
7515 function fetch_context_capabilities(context $context) {
7516 return $context->get_capabilities();
7520 * Runs get_records select on context table and returns the result
7521 * Does get_records_select on the context table, and returns the results ordered
7522 * by contextlevel, and then the natural sort order within each level.
7523 * for the purpose of $select, you need to know that the context table has been
7524 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7526 * @deprecated since 2.2
7527 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7528 * @param array $params any parameters required by $select.
7529 * @return array the requested context records.
7531 function get_sorted_contexts($select, $params = array()) {
7533 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7535 global $DB;
7536 if ($select) {
7537 $select = 'WHERE ' . $select;
7539 return $DB->get_records_sql("
7540 SELECT ctx.*
7541 FROM {context} ctx
7542 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7543 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7544 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7545 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7546 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7547 $select
7548 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7549 ", $params);
7553 * This is really slow!!! do not use above course context level
7555 * @deprecated since 2.2
7556 * @param int $roleid
7557 * @param context $context
7558 * @return array
7560 function get_role_context_caps($roleid, context $context) {
7561 global $DB;
7563 //this is really slow!!!! - do not use above course context level!
7564 $result = array();
7565 $result[$context->id] = array();
7567 // first emulate the parent context capabilities merging into context
7568 $searchcontexts = array_reverse($context->get_parent_context_ids(true));
7569 foreach ($searchcontexts as $cid) {
7570 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7571 foreach ($capabilities as $cap) {
7572 if (!array_key_exists($cap->capability, $result[$context->id])) {
7573 $result[$context->id][$cap->capability] = 0;
7575 $result[$context->id][$cap->capability] += $cap->permission;
7580 // now go through the contexts below given context
7581 $searchcontexts = array_keys($context->get_child_contexts());
7582 foreach ($searchcontexts as $cid) {
7583 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7584 foreach ($capabilities as $cap) {
7585 if (!array_key_exists($cap->contextid, $result)) {
7586 $result[$cap->contextid] = array();
7588 $result[$cap->contextid][$cap->capability] = $cap->permission;
7593 return $result;
7597 * Gets a string for sql calls, searching for stuff in this context or above
7599 * NOTE: use $DB->get_in_or_equal($context->get_parent_context_ids()...
7601 * @deprecated since 2.2, $context->use get_parent_context_ids() instead
7602 * @param context $context
7603 * @return string
7605 function get_related_contexts_string(context $context) {
7607 if ($parents = $context->get_parent_context_ids()) {
7608 return (' IN ('.$context->id.','.implode(',', $parents).')');
7609 } else {
7610 return (' ='.$context->id);