Merge branch 'MDL-29569' of git://github.com/rwijaya/moodle
[moodle.git] / lib / accesslib.php
blob6ef78db739fee2cac0c10a33ef7f00be773f748a
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains functions for managing user access
20 * <b>Public API vs internals</b>
22 * General users probably only care about
24 * Context handling
25 * - context_course::instance($courseid), context_module::instance($cm->id), context_coursecat::instance($catid)
26 * - context::instance_by_id($contextid)
27 * - $context->get_parent_contexts();
28 * - $context->get_child_contexts();
30 * Whether the user can do something...
31 * - has_capability()
32 * - has_any_capability()
33 * - has_all_capabilities()
34 * - require_capability()
35 * - require_login() (from moodlelib)
36 * - is_siteadmin()
38 * What courses has this user access to?
39 * - get_enrolled_users()
41 * What users can do X in this context?
42 * - get_users_by_capability()
44 * Modify roles
45 * - role_assign()
46 * - role_unassign()
47 * - role_unassign_all()
50 * Advanced - for internal use only
51 * - load_all_capabilities()
52 * - reload_all_capabilities()
53 * - has_capability_in_accessdata()
54 * - get_user_access_sitewide()
55 * - load_course_context()
56 * - load_role_access_by_context()
57 * - etc.
59 * <b>Name conventions</b>
61 * "ctx" means context
63 * <b>accessdata</b>
65 * Access control data is held in the "accessdata" array
66 * which - for the logged-in user, will be in $USER->access
68 * For other users can be generated and passed around (but may also be cached
69 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
71 * $accessdata is a multidimensional array, holding
72 * role assignments (RAs), role-capabilities-perm sets
73 * (role defs) and a list of courses we have loaded
74 * data for.
76 * Things are keyed on "contextpaths" (the path field of
77 * the context table) for fast walking up/down the tree.
78 * <code>
79 * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
80 * [$contextpath] = array($roleid=>$roleid)
81 * [$contextpath] = array($roleid=>$roleid)
82 * </code>
84 * Role definitions are stored like this
85 * (no cap merge is done - so it's compact)
87 * <code>
88 * $accessdata['rdef']["$contextpath:$roleid"]['mod/forum:viewpost'] = 1
89 * ['mod/forum:editallpost'] = -1
90 * ['mod/forum:startdiscussion'] = -1000
91 * </code>
93 * See how has_capability_in_accessdata() walks up the tree.
95 * First we only load rdef and ra down to the course level, but not below.
96 * This keeps accessdata small and compact. Below-the-course ra/rdef
97 * are loaded as needed. We keep track of which courses we have loaded ra/rdef in
98 * <code>
99 * $accessdata['loaded'] = array($courseid1=>1, $courseid2=>1)
100 * </code>
102 * <b>Stale accessdata</b>
104 * For the logged-in user, accessdata is long-lived.
106 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
107 * context paths affected by changes. Any check at-or-below
108 * a dirty context will trigger a transparent reload of accessdata.
110 * Changes at the system level will force the reload for everyone.
112 * <b>Default role caps</b>
113 * The default role assignment is not in the DB, so we
114 * add it manually to accessdata.
116 * This means that functions that work directly off the
117 * DB need to ensure that the default role caps
118 * are dealt with appropriately.
120 * @package core
121 * @subpackage role
122 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
123 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
126 defined('MOODLE_INTERNAL') || die();
128 /** No capability change */
129 define('CAP_INHERIT', 0);
130 /** Allow permission, overrides CAP_PREVENT defined in parent contexts */
131 define('CAP_ALLOW', 1);
132 /** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
133 define('CAP_PREVENT', -1);
134 /** Prohibit permission, overrides everything in current and child contexts */
135 define('CAP_PROHIBIT', -1000);
137 /** System context level - only one instance in every system */
138 define('CONTEXT_SYSTEM', 10);
139 /** User context level - one instance for each user describing what others can do to user */
140 define('CONTEXT_USER', 30);
141 /** Course category context level - one instance for each category */
142 define('CONTEXT_COURSECAT', 40);
143 /** Course context level - one instances for each course */
144 define('CONTEXT_COURSE', 50);
145 /** Course module context level - one instance for each course module */
146 define('CONTEXT_MODULE', 70);
148 * Block context level - one instance for each block, sticky blocks are tricky
149 * because ppl think they should be able to override them at lower contexts.
150 * Any other context level instance can be parent of block context.
152 define('CONTEXT_BLOCK', 80);
154 /** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
155 define('RISK_MANAGETRUST', 0x0001);
156 /** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
157 define('RISK_CONFIG', 0x0002);
158 /** Capability allows user to add scritped content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
159 define('RISK_XSS', 0x0004);
160 /** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
161 define('RISK_PERSONAL', 0x0008);
162 /** Capability allows users to add content otehrs may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
163 define('RISK_SPAM', 0x0010);
164 /** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
165 define('RISK_DATALOSS', 0x0020);
167 /** rolename displays - the name as defined in the role definition */
168 define('ROLENAME_ORIGINAL', 0);
169 /** rolename displays - the name as defined by a role alias */
170 define('ROLENAME_ALIAS', 1);
171 /** rolename displays - Both, like this: Role alias (Original) */
172 define('ROLENAME_BOTH', 2);
173 /** rolename displays - the name as defined in the role definition and the shortname in brackets */
174 define('ROLENAME_ORIGINALANDSHORT', 3);
175 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
176 define('ROLENAME_ALIAS_RAW', 4);
177 /** rolename displays - the name is simply short role name */
178 define('ROLENAME_SHORT', 5);
180 /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
181 if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
182 define('CONTEXT_CACHE_MAX_SIZE', 2500);
186 * Although this looks like a global variable, it isn't really.
188 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
189 * It is used to cache various bits of data between function calls for performance reasons.
190 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
191 * as methods of a class, instead of functions.
193 * @private
194 * @global stdClass $ACCESSLIB_PRIVATE
195 * @name $ACCESSLIB_PRIVATE
197 global $ACCESSLIB_PRIVATE;
198 $ACCESSLIB_PRIVATE = new stdClass();
199 $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache, loaded from DB once per page
200 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
201 $ACCESSLIB_PRIVATE->rolepermissions = array(); // role permissions cache - helps a lot with mem usage
202 $ACCESSLIB_PRIVATE->capabilities = null; // detailed information about the capabilities
205 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
207 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
208 * accesslib's private caches. You need to do this before setting up test data,
209 * and also at the end of the tests.
211 * @return void
213 function accesslib_clear_all_caches_for_unit_testing() {
214 global $UNITTEST, $USER;
215 if (empty($UNITTEST->running)) {
216 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
219 accesslib_clear_all_caches(true);
221 unset($USER->access);
225 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
227 * This reset does not touch global $USER.
229 * @private
230 * @param bool $resetcontexts
231 * @return void
233 function accesslib_clear_all_caches($resetcontexts) {
234 global $ACCESSLIB_PRIVATE;
236 $ACCESSLIB_PRIVATE->dirtycontexts = null;
237 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
238 $ACCESSLIB_PRIVATE->rolepermissions = array();
239 $ACCESSLIB_PRIVATE->capabilities = null;
241 if ($resetcontexts) {
242 context_helper::reset_caches();
247 * Gets the accessdata for role "sitewide" (system down to course)
249 * @private
250 * @param int $roleid
251 * @return array
253 function get_role_access($roleid) {
254 global $DB, $ACCESSLIB_PRIVATE;
256 /* Get it in 1 DB query...
257 * - relevant role caps at the root and down
258 * to the course level - but not below
261 //TODO: MUC - this could be cached in shared memory to speed up first page loading, web crawlers, etc.
263 $accessdata = get_empty_accessdata();
265 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
268 // Overrides for the role IN ANY CONTEXTS
269 // down to COURSE - not below -
271 $sql = "SELECT ctx.path,
272 rc.capability, rc.permission
273 FROM {context} ctx
274 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
275 LEFT JOIN {context} cctx
276 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
277 WHERE rc.roleid = ? AND cctx.id IS NULL";
278 $params = array($roleid);
280 // we need extra caching in CLI scripts and cron
281 $rs = $DB->get_recordset_sql($sql, $params);
282 foreach ($rs as $rd) {
283 $k = "{$rd->path}:{$roleid}";
284 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
286 $rs->close();
288 // share the role definitions
289 foreach ($accessdata['rdef'] as $k=>$unused) {
290 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
291 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
293 $accessdata['rdef_count']++;
294 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
297 return $accessdata;
301 * Get the default guest role, this is used for guest account,
302 * search engine spiders, etc.
304 * @return stdClass role record
306 function get_guest_role() {
307 global $CFG, $DB;
309 if (empty($CFG->guestroleid)) {
310 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
311 $guestrole = array_shift($roles); // Pick the first one
312 set_config('guestroleid', $guestrole->id);
313 return $guestrole;
314 } else {
315 debugging('Can not find any guest role!');
316 return false;
318 } else {
319 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
320 return $guestrole;
321 } else {
322 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
323 set_config('guestroleid', '');
324 return get_guest_role();
330 * Check whether a user has a particular capability in a given context.
332 * For example:
333 * $context = get_context_instance(CONTEXT_MODULE, $cm->id);
334 * has_capability('mod/forum:replypost',$context)
336 * By default checks the capabilities of the current user, but you can pass a
337 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
339 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
340 * or capabilities with XSS, config or data loss risks.
342 * @param string $capability the name of the capability to check. For example mod/forum:view
343 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
344 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
345 * @param boolean $doanything If false, ignores effect of admin role assignment
346 * @return boolean true if the user has this capability. Otherwise false.
348 function has_capability($capability, context $context, $user = null, $doanything = true) {
349 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
351 if (during_initial_install()) {
352 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
353 // we are in an installer - roles can not work yet
354 return true;
355 } else {
356 return false;
360 if (strpos($capability, 'moodle/legacy:') === 0) {
361 throw new coding_exception('Legacy capabilities can not be used any more!');
364 if (!is_bool($doanything)) {
365 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
368 // capability must exist
369 if (!$capinfo = get_capability_info($capability)) {
370 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
371 return false;
374 if (!isset($USER->id)) {
375 // should never happen
376 $USER->id = 0;
379 // make sure there is a real user specified
380 if ($user === null) {
381 $userid = $USER->id;
382 } else {
383 $userid = is_object($user) ? $user->id : $user;
386 // make sure forcelogin cuts off not-logged-in users if enabled
387 if (!empty($CFG->forcelogin) and $userid == 0) {
388 return false;
391 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
392 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
393 if (isguestuser($userid) or $userid == 0) {
394 return false;
398 // somehow make sure the user is not deleted and actually exists
399 if ($userid != 0) {
400 if ($userid == $USER->id and isset($USER->deleted)) {
401 // this prevents one query per page, it is a bit of cheating,
402 // but hopefully session is terminated properly once user is deleted
403 if ($USER->deleted) {
404 return false;
406 } else {
407 if (!context_user::instance($userid, IGNORE_MISSING)) {
408 // no user context == invalid userid
409 return false;
414 // context path/depth must be valid
415 if (empty($context->path) or $context->depth == 0) {
416 // this should not happen often, each upgrade tries to rebuild the context paths
417 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()');
418 if (is_siteadmin($userid)) {
419 return true;
420 } else {
421 return false;
425 // Find out if user is admin - it is not possible to override the doanything in any way
426 // and it is not possible to switch to admin role either.
427 if ($doanything) {
428 if (is_siteadmin($userid)) {
429 if ($userid != $USER->id) {
430 return true;
432 // make sure switchrole is not used in this context
433 if (empty($USER->access['rsw'])) {
434 return true;
436 $parts = explode('/', trim($context->path, '/'));
437 $path = '';
438 $switched = false;
439 foreach ($parts as $part) {
440 $path .= '/' . $part;
441 if (!empty($USER->access['rsw'][$path])) {
442 $switched = true;
443 break;
446 if (!$switched) {
447 return true;
449 //ok, admin switched role in this context, let's use normal access control rules
453 // Careful check for staleness...
454 $context->reload_if_dirty();
456 if ($USER->id == $userid) {
457 if (!isset($USER->access)) {
458 load_all_capabilities();
460 $access =& $USER->access;
462 } else {
463 // make sure user accessdata is really loaded
464 get_user_accessdata($userid, true);
465 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
469 // Load accessdata for below-the-course context if necessary,
470 // all contexts at and above all courses are already loaded
471 if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
472 load_course_context($userid, $coursecontext, $access);
475 return has_capability_in_accessdata($capability, $context, $access);
479 * Check if the user has any one of several capabilities from a list.
481 * This is just a utility method that calls has_capability in a loop. Try to put
482 * the capabilities that most users are likely to have first in the list for best
483 * performance.
485 * @see has_capability()
486 * @param array $capabilities an array of capability names.
487 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
488 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
489 * @param boolean $doanything If false, ignore effect of admin role assignment
490 * @return boolean true if the user has any of these capabilities. Otherwise false.
492 function has_any_capability(array $capabilities, context $context, $userid = null, $doanything = true) {
493 foreach ($capabilities as $capability) {
494 if (has_capability($capability, $context, $userid, $doanything)) {
495 return true;
498 return false;
502 * Check if the user has all the capabilities in a list.
504 * This is just a utility method that calls has_capability in a loop. Try to put
505 * the capabilities that fewest users are likely to have first in the list for best
506 * performance.
508 * @see has_capability()
509 * @param array $capabilities an array of capability names.
510 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
511 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
512 * @param boolean $doanything If false, ignore effect of admin role assignment
513 * @return boolean true if the user has all of these capabilities. Otherwise false.
515 function has_all_capabilities(array $capabilities, context $context, $userid = null, $doanything = true) {
516 foreach ($capabilities as $capability) {
517 if (!has_capability($capability, $context, $userid, $doanything)) {
518 return false;
521 return true;
525 * Check if the user is an admin at the site level.
527 * Please note that use of proper capabilities is always encouraged,
528 * this function is supposed to be used from core or for temporary hacks.
530 * @param int|stdClass $user_or_id user id or user object
531 * @return bool true if user is one of the administrators, false otherwise
533 function is_siteadmin($user_or_id = null) {
534 global $CFG, $USER;
536 if ($user_or_id === null) {
537 $user_or_id = $USER;
540 if (empty($user_or_id)) {
541 return false;
543 if (!empty($user_or_id->id)) {
544 $userid = $user_or_id->id;
545 } else {
546 $userid = $user_or_id;
549 $siteadmins = explode(',', $CFG->siteadmins);
550 return in_array($userid, $siteadmins);
554 * Returns true if user has at least one role assign
555 * of 'coursecontact' role (is potentially listed in some course descriptions).
557 * @param int $userid
558 * @return bool
560 function has_coursecontact_role($userid) {
561 global $DB, $CFG;
563 if (empty($CFG->coursecontact)) {
564 return false;
566 $sql = "SELECT 1
567 FROM {role_assignments}
568 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
569 return $DB->record_exists_sql($sql, array('userid'=>$userid));
573 * Does the user have a capability to do something?
575 * Walk the accessdata array and return true/false.
576 * Deals with prohibits, role switching, aggregating
577 * capabilities, etc.
579 * The main feature of here is being FAST and with no
580 * side effects.
582 * Notes:
584 * Switch Role merges with default role
585 * ------------------------------------
586 * If you are a teacher in course X, you have at least
587 * teacher-in-X + defaultloggedinuser-sitewide. So in the
588 * course you'll have techer+defaultloggedinuser.
589 * We try to mimic that in switchrole.
591 * Permission evaluation
592 * ---------------------
593 * Originally there was an extremely complicated way
594 * to determine the user access that dealt with
595 * "locality" or role assignments and role overrides.
596 * Now we simply evaluate access for each role separately
597 * and then verify if user has at least one role with allow
598 * and at the same time no role with prohibit.
600 * @private
601 * @param string $capability
602 * @param context $context
603 * @param array $accessdata
604 * @return bool
606 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
607 global $CFG;
609 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
610 $path = $context->path;
611 $paths = array($path);
612 while($path = rtrim($path, '0123456789')) {
613 $path = rtrim($path, '/');
614 if ($path === '') {
615 break;
617 $paths[] = $path;
620 $roles = array();
621 $switchedrole = false;
623 // Find out if role switched
624 if (!empty($accessdata['rsw'])) {
625 // From the bottom up...
626 foreach ($paths as $path) {
627 if (isset($accessdata['rsw'][$path])) {
628 // Found a switchrole assignment - check for that role _plus_ the default user role
629 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
630 $switchedrole = true;
631 break;
636 if (!$switchedrole) {
637 // get all users roles in this context and above
638 foreach ($paths as $path) {
639 if (isset($accessdata['ra'][$path])) {
640 foreach ($accessdata['ra'][$path] as $roleid) {
641 $roles[$roleid] = null;
647 // Now find out what access is given to each role, going bottom-->up direction
648 $allowed = false;
649 foreach ($roles as $roleid => $ignored) {
650 foreach ($paths as $path) {
651 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
652 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
653 if ($perm === CAP_PROHIBIT) {
654 // any CAP_PROHIBIT found means no permission for the user
655 return false;
657 if (is_null($roles[$roleid])) {
658 $roles[$roleid] = $perm;
662 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
663 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
666 return $allowed;
670 * A convenience function that tests has_capability, and displays an error if
671 * the user does not have that capability.
673 * NOTE before Moodle 2.0, this function attempted to make an appropriate
674 * require_login call before checking the capability. This is no longer the case.
675 * You must call require_login (or one of its variants) if you want to check the
676 * user is logged in, before you call this function.
678 * @see has_capability()
680 * @param string $capability the name of the capability to check. For example mod/forum:view
681 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
682 * @param int $userid A user id. By default (null) checks the permissions of the current user.
683 * @param bool $doanything If false, ignore effect of admin role assignment
684 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
685 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
686 * @return void terminates with an error if the user does not have the given capability.
688 function require_capability($capability, context $context, $userid = null, $doanything = true,
689 $errormessage = 'nopermissions', $stringfile = '') {
690 if (!has_capability($capability, $context, $userid, $doanything)) {
691 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
696 * Return a nested array showing role assignments
697 * all relevant role capabilities for the user at
698 * site/course_category/course levels
700 * We do _not_ delve deeper than courses because the number of
701 * overrides at the module/block levels can be HUGE.
703 * [ra] => [/path][roleid]=roleid
704 * [rdef] => [/path:roleid][capability]=permission
706 * @private
707 * @param int $userid - the id of the user
708 * @return array access info array
710 function get_user_access_sitewide($userid) {
711 global $CFG, $DB, $ACCESSLIB_PRIVATE;
713 /* Get in a few cheap DB queries...
714 * - role assignments
715 * - relevant role caps
716 * - above and within this user's RAs
717 * - below this user's RAs - limited to course level
720 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
721 $raparents = array();
722 $accessdata = get_empty_accessdata();
724 // start with the default role
725 if (!empty($CFG->defaultuserroleid)) {
726 $syscontext = context_system::instance();
727 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
728 $raparents[$CFG->defaultuserroleid][$syscontext->path] = $syscontext->path;
731 // load the "default frontpage role"
732 if (!empty($CFG->defaultfrontpageroleid)) {
733 $frontpagecontext = context_course::instance(get_site()->id);
734 if ($frontpagecontext->path) {
735 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
736 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->path] = $frontpagecontext->path;
740 // preload every assigned role at and above course context
741 $sql = "SELECT ctx.path, ra.roleid
742 FROM {role_assignments} ra
743 JOIN {context} ctx ON ctx.id = ra.contextid
744 LEFT JOIN {context} cctx
745 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
746 WHERE ra.userid = :userid AND cctx.id IS NULL";
749 $params = array('userid'=>$userid);
750 $rs = $DB->get_recordset_sql($sql, $params);
751 foreach ($rs as $ra) {
752 // RAs leafs are arrays to support multi-role assignments...
753 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
754 $raparents[$ra->roleid][$ra->path] = $ra->path;
756 $rs->close();
758 if (empty($raparents)) {
759 return $accessdata;
762 // now get overrides of interesting roles in all interesting child contexts
763 // hopefully we will not run out of SQL limits here,
764 // users would have to have very many roles above course context...
765 $sqls = array();
766 $params = array();
768 static $cp = 0;
769 foreach ($raparents as $roleid=>$paths) {
770 $cp++;
771 list($paths, $rparams) = $DB->get_in_or_equal($paths, SQL_PARAMS_NAMED, 'p'.$cp.'_');
772 $params = array_merge($params, $rparams);
773 $params['r'.$cp] = $roleid;
774 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
775 FROM {role_capabilities} rc
776 JOIN {context} ctx
777 ON (ctx.id = rc.contextid)
778 LEFT JOIN {context} cctx
779 ON (cctx.contextlevel = ".CONTEXT_COURSE."
780 AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
781 JOIN {context} pctx
782 ON (pctx.path $paths
783 AND (ctx.id = pctx.id
784 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
785 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
786 WHERE rc.roleid = :r{$cp}
787 AND cctx.id IS NULL)";
790 // fixed capability order is necessary for rdef dedupe
791 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
793 foreach ($rs as $rd) {
794 $k = $rd->path.':'.$rd->roleid;
795 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
797 $rs->close();
799 // share the role definitions
800 foreach ($accessdata['rdef'] as $k=>$unused) {
801 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
802 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
804 $accessdata['rdef_count']++;
805 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
808 return $accessdata;
812 * Add to the access ctrl array the data needed by a user for a given course.
814 * This function injects all course related access info into the accessdata array.
816 * @private
817 * @param int $userid the id of the user
818 * @param context_course $coursecontext course context
819 * @param array $accessdata accessdata array (modified)
820 * @return void modifies $accessdata parameter
822 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
823 global $DB, $CFG, $ACCESSLIB_PRIVATE;
825 if (empty($coursecontext->path)) {
826 // weird, this should not happen
827 return;
830 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
831 // already loaded, great!
832 return;
835 $roles = array();
837 if (empty($userid)) {
838 if (!empty($CFG->notloggedinroleid)) {
839 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
842 } else if (isguestuser($userid)) {
843 if ($guestrole = get_guest_role()) {
844 $roles[$guestrole->id] = $guestrole->id;
847 } else {
848 // Interesting role assignments at, above and below the course context
849 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
850 $params['userid'] = $userid;
851 $params['children'] = $coursecontext->path."/%";
852 $sql = "SELECT ra.*, ctx.path
853 FROM {role_assignments} ra
854 JOIN {context} ctx ON ra.contextid = ctx.id
855 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
856 $rs = $DB->get_recordset_sql($sql, $params);
858 // add missing role definitions
859 foreach ($rs as $ra) {
860 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
861 $roles[$ra->roleid] = $ra->roleid;
863 $rs->close();
865 // add the "default frontpage role" when on the frontpage
866 if (!empty($CFG->defaultfrontpageroleid)) {
867 $frontpagecontext = context_course::instance(get_site()->id);
868 if ($frontpagecontext->id == $coursecontext->id) {
869 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
873 // do not forget the default role
874 if (!empty($CFG->defaultuserroleid)) {
875 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
879 if (!$roles) {
880 // weird, default roles must be missing...
881 $accessdata['loaded'][$coursecontext->instanceid] = 1;
882 return;
885 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
886 $params = array('c'=>$coursecontext->id);
887 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
888 $params = array_merge($params, $rparams);
889 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
890 $params = array_merge($params, $rparams);
892 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
893 FROM {role_capabilities} rc
894 JOIN {context} ctx
895 ON (ctx.id = rc.contextid)
896 JOIN {context} cctx
897 ON (cctx.id = :c
898 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
899 WHERE rc.roleid $roleids
900 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
901 $rs = $DB->get_recordset_sql($sql, $params);
903 $newrdefs = array();
904 foreach ($rs as $rd) {
905 $k = $rd->path.':'.$rd->roleid;
906 if (isset($accessdata['rdef'][$k])) {
907 continue;
909 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
911 $rs->close();
913 // share new role definitions
914 foreach ($newrdefs as $k=>$unused) {
915 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
916 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
918 $accessdata['rdef_count']++;
919 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
922 $accessdata['loaded'][$coursecontext->instanceid] = 1;
924 // we want to deduplicate the USER->access from time to time, this looks like a good place,
925 // because we have to do it before the end of session
926 dedupe_user_access();
930 * Add to the access ctrl array the data needed by a role for a given context.
932 * The data is added in the rdef key.
933 * This role-centric function is useful for role_switching
934 * and temporary course roles.
936 * @private
937 * @param int $roleid the id of the user
938 * @param context $context needs path!
939 * @param array $accessdata accessdata array (is modified)
940 * @return array
942 function load_role_access_by_context($roleid, context $context, &$accessdata) {
943 global $DB, $ACCESSLIB_PRIVATE;
945 /* Get the relevant rolecaps into rdef
946 * - relevant role caps
947 * - at ctx and above
948 * - below this ctx
951 if (empty($context->path)) {
952 // weird, this should not happen
953 return;
956 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
957 $params['roleid'] = $roleid;
958 $params['childpath'] = $context->path.'/%';
960 $sql = "SELECT ctx.path, rc.capability, rc.permission
961 FROM {role_capabilities} rc
962 JOIN {context} ctx ON (rc.contextid = ctx.id)
963 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
964 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
965 $rs = $DB->get_recordset_sql($sql, $params);
967 $newrdefs = array();
968 foreach ($rs as $rd) {
969 $k = $rd->path.':'.$roleid;
970 if (isset($accessdata['rdef'][$k])) {
971 continue;
973 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
975 $rs->close();
977 // share new role definitions
978 foreach ($newrdefs as $k=>$unused) {
979 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
980 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
982 $accessdata['rdef_count']++;
983 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
988 * Returns empty accessdata structure.
990 * @private
991 * @return array empt accessdata
993 function get_empty_accessdata() {
994 $accessdata = array(); // named list
995 $accessdata['ra'] = array();
996 $accessdata['rdef'] = array();
997 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
998 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
999 $accessdata['loaded'] = array(); // loaded course contexts
1000 $accessdata['time'] = time();
1002 return $accessdata;
1006 * Get accessdata for a given user.
1008 * @private
1009 * @param int $userid
1010 * @param bool $preloadonly true means do not return access array
1011 * @return array accessdata
1013 function get_user_accessdata($userid, $preloadonly=false) {
1014 global $CFG, $ACCESSLIB_PRIVATE, $USER;
1016 if (!empty($USER->acces['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1017 // share rdef from USER session with rolepermissions cache in order to conserve memory
1018 foreach($USER->acces['rdef'] as $k=>$v) {
1019 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->acces['rdef'][$k];
1021 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->acces;
1024 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1025 if (empty($userid)) {
1026 if (!empty($CFG->notloggedinroleid)) {
1027 $accessdata = get_role_access($CFG->notloggedinroleid);
1028 } else {
1029 // weird
1030 return get_empty_accessdata();
1033 } else if (isguestuser($userid)) {
1034 if ($guestrole = get_guest_role()) {
1035 $accessdata = get_role_access($guestrole->id);
1036 } else {
1037 //weird
1038 return get_empty_accessdata();
1041 } else {
1042 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1045 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1048 if ($preloadonly) {
1049 return;
1050 } else {
1051 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1056 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1057 * this function looks for contexts with the same overrides and shares them.
1059 * @private
1060 * @return void
1062 function dedupe_user_access() {
1063 global $USER;
1065 if (CLI_SCRIPT) {
1066 // no session in CLI --> no compression necessary
1067 return;
1070 if (empty($USER->access['rdef_count'])) {
1071 // weird, this should not happen
1072 return;
1075 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1076 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1077 // do not compress after each change, wait till there is more stuff to be done
1078 return;
1081 $hashmap = array();
1082 foreach ($USER->access['rdef'] as $k=>$def) {
1083 $hash = sha1(serialize($def));
1084 if (isset($hashmap[$hash])) {
1085 $USER->access['rdef'][$k] =& $hashmap[$hash];
1086 } else {
1087 $hashmap[$hash] =& $USER->access['rdef'][$k];
1091 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1095 * A convenience function to completely load all the capabilities
1096 * for the current user. It is called from has_capability() and functions change permissions.
1098 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1099 * @see check_enrolment_plugins()
1101 * @private
1102 * @return void
1104 function load_all_capabilities() {
1105 global $USER;
1107 // roles not installed yet - we are in the middle of installation
1108 if (during_initial_install()) {
1109 return;
1112 if (!isset($USER->id)) {
1113 // this should not happen
1114 $USER->id = 0;
1117 unset($USER->access);
1118 $USER->access = get_user_accessdata($USER->id);
1120 // deduplicate the overrides to minimize session size
1121 dedupe_user_access();
1123 // Clear to force a refresh
1124 unset($USER->mycourses);
1125 unset($USER->enrol);
1129 * A convenience function to completely reload all the capabilities
1130 * for the current user when roles have been updated in a relevant
1131 * context -- but PRESERVING switchroles and loginas.
1132 * This function resets all accesslib and context caches.
1134 * That is - completely transparent to the user.
1136 * Note: reloads $USER->access completely.
1138 * @private
1139 * @return void
1141 function reload_all_capabilities() {
1142 global $USER, $DB, $ACCESSLIB_PRIVATE;
1144 // copy switchroles
1145 $sw = array();
1146 if (isset($USER->access['rsw'])) {
1147 $sw = $USER->access['rsw'];
1150 accesslib_clear_all_caches(true);
1151 unset($USER->access);
1152 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1154 load_all_capabilities();
1156 foreach ($sw as $path => $roleid) {
1157 if ($record = $DB->get_record('context', array('path'=>$path))) {
1158 $context = context::instance_by_id($record->id);
1159 role_switch($roleid, $context);
1165 * Adds a temp role to current USER->access array.
1167 * Useful for the "temporary guest" access we grant to logged-in users.
1168 * @since 2.2
1170 * @param context_course $coursecontext
1171 * @param int $roleid
1172 * @return void
1174 function load_temp_course_role(context_course $coursecontext, $roleid) {
1175 global $USER;
1177 //TODO: this gets removed if there are any dirty contexts, we should probably store list of these temp roles somewhere (skodak)
1179 if (empty($roleid)) {
1180 debugging('invalid role specified in load_temp_course_role()');
1181 return;
1184 if (!isset($USER->access)) {
1185 load_all_capabilities();
1188 $coursecontext->reload_if_dirty();
1190 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1191 return;
1194 // load course stuff first
1195 load_course_context($USER->id, $coursecontext, $USER->access);
1197 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1199 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1203 * Removes any extra guest roles from current USER->access array.
1204 * @since 2.2
1206 * @param context_course $coursecontext
1207 * @return void
1209 function remove_temp_course_roles(context_course $coursecontext) {
1210 global $DB, $USER;
1212 if (empty($USER->access['ra'][$coursecontext->path])) {
1213 //no roles here, weird
1214 return;
1217 $sql = "SELECT DISTINCT ra.roleid AS id
1218 FROM {role_assignments} ra
1219 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1220 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1222 $USER->access['ra'][$coursecontext->path] = array();
1223 foreach($ras as $r) {
1224 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1229 * Returns array of all role archetypes.
1231 * @return array
1233 function get_role_archetypes() {
1234 return array(
1235 'manager' => 'manager',
1236 'coursecreator' => 'coursecreator',
1237 'editingteacher' => 'editingteacher',
1238 'teacher' => 'teacher',
1239 'student' => 'student',
1240 'guest' => 'guest',
1241 'user' => 'user',
1242 'frontpage' => 'frontpage'
1247 * Assign the defaults found in this capability definition to roles that have
1248 * the corresponding legacy capabilities assigned to them.
1250 * @param string $capability
1251 * @param array $legacyperms an array in the format (example):
1252 * 'guest' => CAP_PREVENT,
1253 * 'student' => CAP_ALLOW,
1254 * 'teacher' => CAP_ALLOW,
1255 * 'editingteacher' => CAP_ALLOW,
1256 * 'coursecreator' => CAP_ALLOW,
1257 * 'manager' => CAP_ALLOW
1258 * @return boolean success or failure.
1260 function assign_legacy_capabilities($capability, $legacyperms) {
1262 $archetypes = get_role_archetypes();
1264 foreach ($legacyperms as $type => $perm) {
1266 $systemcontext = context_system::instance();
1267 if ($type === 'admin') {
1268 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1269 $type = 'manager';
1272 if (!array_key_exists($type, $archetypes)) {
1273 print_error('invalidlegacy', '', '', $type);
1276 if ($roles = get_archetype_roles($type)) {
1277 foreach ($roles as $role) {
1278 // Assign a site level capability.
1279 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1280 return false;
1285 return true;
1289 * Verify capability risks.
1291 * @param object $capability a capability - a row from the capabilities table.
1292 * @return boolean whether this capability is safe - that is, whether people with the
1293 * safeoverrides capability should be allowed to change it.
1295 function is_safe_capability($capability) {
1296 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1300 * Get the local override (if any) for a given capability in a role in a context
1302 * @param int $roleid
1303 * @param int $contextid
1304 * @param string $capability
1305 * @return stdClass local capability override
1307 function get_local_override($roleid, $contextid, $capability) {
1308 global $DB;
1309 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1313 * Returns context instance plus related course and cm instances
1315 * @param int $contextid
1316 * @return array of ($context, $course, $cm)
1318 function get_context_info_array($contextid) {
1319 global $DB;
1321 $context = context::instance_by_id($contextid, MUST_EXIST);
1322 $course = null;
1323 $cm = null;
1325 if ($context->contextlevel == CONTEXT_COURSE) {
1326 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1328 } else if ($context->contextlevel == CONTEXT_MODULE) {
1329 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1330 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1332 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1333 $parent = $context->get_parent_context();
1335 if ($parent->contextlevel == CONTEXT_COURSE) {
1336 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1337 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1338 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1339 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1343 return array($context, $course, $cm);
1347 * Function that creates a role
1349 * @param string $name role name
1350 * @param string $shortname role short name
1351 * @param string $description role description
1352 * @param string $archetype
1353 * @return int id or dml_exception
1355 function create_role($name, $shortname, $description, $archetype = '') {
1356 global $DB;
1358 if (strpos($archetype, 'moodle/legacy:') !== false) {
1359 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1362 // verify role archetype actually exists
1363 $archetypes = get_role_archetypes();
1364 if (empty($archetypes[$archetype])) {
1365 $archetype = '';
1368 // Insert the role record.
1369 $role = new stdClass();
1370 $role->name = $name;
1371 $role->shortname = $shortname;
1372 $role->description = $description;
1373 $role->archetype = $archetype;
1375 //find free sortorder number
1376 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1377 if (empty($role->sortorder)) {
1378 $role->sortorder = 1;
1380 $id = $DB->insert_record('role', $role);
1382 return $id;
1386 * Function that deletes a role and cleanups up after it
1388 * @param int $roleid id of role to delete
1389 * @return bool always true
1391 function delete_role($roleid) {
1392 global $DB;
1394 // first unssign all users
1395 role_unassign_all(array('roleid'=>$roleid));
1397 // cleanup all references to this role, ignore errors
1398 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1399 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1400 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1401 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1402 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1403 $DB->delete_records('role_names', array('roleid'=>$roleid));
1404 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1406 // finally delete the role itself
1407 // get this before the name is gone for logging
1408 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
1410 $DB->delete_records('role', array('id'=>$roleid));
1412 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
1414 return true;
1418 * Function to write context specific overrides, or default capabilities.
1420 * NOTE: use $context->mark_dirty() after this
1422 * @param string $capability string name
1423 * @param int $permission CAP_ constants
1424 * @param int $roleid role id
1425 * @param int|context $contextid context id
1426 * @param bool $overwrite
1427 * @return bool always true or exception
1429 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1430 global $USER, $DB;
1432 if ($contextid instanceof context) {
1433 $context = $contextid;
1434 } else {
1435 $context = context::instance_by_id($contextid);
1438 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1439 unassign_capability($capability, $roleid, $context->id);
1440 return true;
1443 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1445 if ($existing and !$overwrite) { // We want to keep whatever is there already
1446 return true;
1449 $cap = new stdClass();
1450 $cap->contextid = $context->id;
1451 $cap->roleid = $roleid;
1452 $cap->capability = $capability;
1453 $cap->permission = $permission;
1454 $cap->timemodified = time();
1455 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1457 if ($existing) {
1458 $cap->id = $existing->id;
1459 $DB->update_record('role_capabilities', $cap);
1460 } else {
1461 if ($DB->record_exists('context', array('id'=>$context->id))) {
1462 $DB->insert_record('role_capabilities', $cap);
1465 return true;
1469 * Unassign a capability from a role.
1471 * NOTE: use $context->mark_dirty() after this
1473 * @param string $capability the name of the capability
1474 * @param int $roleid the role id
1475 * @param int|context $contextid null means all contexts
1476 * @return boolean true or exception
1478 function unassign_capability($capability, $roleid, $contextid = null) {
1479 global $DB;
1481 if (!empty($contextid)) {
1482 if ($contextid instanceof context) {
1483 $context = $contextid;
1484 } else {
1485 $context = context::instance_by_id($contextid);
1487 // delete from context rel, if this is the last override in this context
1488 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1489 } else {
1490 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1492 return true;
1496 * Get the roles that have a given capability assigned to it
1498 * This function does not resolve the actual permission of the capability.
1499 * It just checks for permissions and overrides.
1500 * Use get_roles_with_cap_in_context() if resolution is required.
1502 * @param string $capability - capability name (string)
1503 * @param string $permission - optional, the permission defined for this capability
1504 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1505 * @param stdClass $context, null means any
1506 * @return array of role records
1508 function get_roles_with_capability($capability, $permission = null, $context = null) {
1509 global $DB;
1511 if ($context) {
1512 $contexts = $context->get_parent_context_ids(true);
1513 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1514 $contextsql = "AND rc.contextid $insql";
1515 } else {
1516 $params = array();
1517 $contextsql = '';
1520 if ($permission) {
1521 $permissionsql = " AND rc.permission = :permission";
1522 $params['permission'] = $permission;
1523 } else {
1524 $permissionsql = '';
1527 $sql = "SELECT r.*
1528 FROM {role} r
1529 WHERE r.id IN (SELECT rc.roleid
1530 FROM {role_capabilities} rc
1531 WHERE rc.capability = :capname
1532 $contextsql
1533 $permissionsql)";
1534 $params['capname'] = $capability;
1537 return $DB->get_records_sql($sql, $params);
1541 * This function makes a role-assignment (a role for a user in a particular context)
1543 * @param int $roleid the role of the id
1544 * @param int $userid userid
1545 * @param int|context $contextid id of the context
1546 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1547 * @param int $itemid id of enrolment/auth plugin
1548 * @param string $timemodified defaults to current time
1549 * @return int new/existing id of the assignment
1551 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1552 global $USER, $DB;
1554 // first of all detect if somebody is using old style parameters
1555 if ($contextid === 0 or is_numeric($component)) {
1556 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1559 // now validate all parameters
1560 if (empty($roleid)) {
1561 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1564 if (empty($userid)) {
1565 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1568 if ($itemid) {
1569 if (strpos($component, '_') === false) {
1570 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1572 } else {
1573 $itemid = 0;
1574 if ($component !== '' and strpos($component, '_') === false) {
1575 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1579 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1580 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1583 if ($contextid instanceof context) {
1584 $context = $contextid;
1585 } else {
1586 $context = context::instance_by_id($contextid, MUST_EXIST);
1589 if (!$timemodified) {
1590 $timemodified = time();
1593 /// Check for existing entry
1594 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1596 if ($ras) {
1597 // role already assigned - this should not happen
1598 if (count($ras) > 1) {
1599 // very weird - remove all duplicates!
1600 $ra = array_shift($ras);
1601 foreach ($ras as $r) {
1602 $DB->delete_records('role_assignments', array('id'=>$r->id));
1604 } else {
1605 $ra = reset($ras);
1608 // actually there is no need to update, reset anything or trigger any event, so just return
1609 return $ra->id;
1612 // Create a new entry
1613 $ra = new stdClass();
1614 $ra->roleid = $roleid;
1615 $ra->contextid = $context->id;
1616 $ra->userid = $userid;
1617 $ra->component = $component;
1618 $ra->itemid = $itemid;
1619 $ra->timemodified = $timemodified;
1620 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1622 $ra->id = $DB->insert_record('role_assignments', $ra);
1624 // mark context as dirty - again expensive, but needed
1625 $context->mark_dirty();
1627 if (!empty($USER->id) && $USER->id == $userid) {
1628 // If the user is the current user, then do full reload of capabilities too.
1629 reload_all_capabilities();
1632 events_trigger('role_assigned', $ra);
1634 return $ra->id;
1638 * Removes one role assignment
1640 * @param int $roleid
1641 * @param int $userid
1642 * @param int|context $contextid
1643 * @param string $component
1644 * @param int $itemid
1645 * @return void
1647 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1648 // first make sure the params make sense
1649 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1650 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1653 if ($itemid) {
1654 if (strpos($component, '_') === false) {
1655 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1657 } else {
1658 $itemid = 0;
1659 if ($component !== '' and strpos($component, '_') === false) {
1660 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1664 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1668 * Removes multiple role assignments, parameters may contain:
1669 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1671 * @param array $params role assignment parameters
1672 * @param bool $subcontexts unassign in subcontexts too
1673 * @param bool $includemanual include manual role assignments too
1674 * @return void
1676 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1677 global $USER, $CFG, $DB;
1679 if (!$params) {
1680 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1683 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1684 foreach ($params as $key=>$value) {
1685 if (!in_array($key, $allowed)) {
1686 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1690 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1691 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1694 if ($includemanual) {
1695 if (!isset($params['component']) or $params['component'] === '') {
1696 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1700 if ($subcontexts) {
1701 if (empty($params['contextid'])) {
1702 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1706 $ras = $DB->get_records('role_assignments', $params);
1707 foreach($ras as $ra) {
1708 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1709 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1710 // this is a bit expensive but necessary
1711 $context->mark_dirty();
1712 /// If the user is the current user, then do full reload of capabilities too.
1713 if (!empty($USER->id) && $USER->id == $ra->userid) {
1714 reload_all_capabilities();
1717 events_trigger('role_unassigned', $ra);
1719 unset($ras);
1721 // process subcontexts
1722 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1723 if ($params['contextid'] instanceof context) {
1724 $context = $params['contextid'];
1725 } else {
1726 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1729 if ($context) {
1730 $contexts = $context->get_child_contexts();
1731 $mparams = $params;
1732 foreach($contexts as $context) {
1733 $mparams['contextid'] = $context->id;
1734 $ras = $DB->get_records('role_assignments', $mparams);
1735 foreach($ras as $ra) {
1736 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1737 // this is a bit expensive but necessary
1738 $context->mark_dirty();
1739 /// If the user is the current user, then do full reload of capabilities too.
1740 if (!empty($USER->id) && $USER->id == $ra->userid) {
1741 reload_all_capabilities();
1743 events_trigger('role_unassigned', $ra);
1749 // do this once more for all manual role assignments
1750 if ($includemanual) {
1751 $params['component'] = '';
1752 role_unassign_all($params, $subcontexts, false);
1757 * Determines if a user is currently logged in
1759 * @return bool
1761 function isloggedin() {
1762 global $USER;
1764 return (!empty($USER->id));
1768 * Determines if a user is logged in as real guest user with username 'guest'.
1770 * @param int|object $user mixed user object or id, $USER if not specified
1771 * @return bool true if user is the real guest user, false if not logged in or other user
1773 function isguestuser($user = null) {
1774 global $USER, $DB, $CFG;
1776 // make sure we have the user id cached in config table, because we are going to use it a lot
1777 if (empty($CFG->siteguest)) {
1778 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1779 // guest does not exist yet, weird
1780 return false;
1782 set_config('siteguest', $guestid);
1784 if ($user === null) {
1785 $user = $USER;
1788 if ($user === null) {
1789 // happens when setting the $USER
1790 return false;
1792 } else if (is_numeric($user)) {
1793 return ($CFG->siteguest == $user);
1795 } else if (is_object($user)) {
1796 if (empty($user->id)) {
1797 return false; // not logged in means is not be guest
1798 } else {
1799 return ($CFG->siteguest == $user->id);
1802 } else {
1803 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1808 * Does user have a (temporary or real) guest access to course?
1810 * @param context $context
1811 * @param stdClass|int $user
1812 * @return bool
1814 function is_guest(context $context, $user = null) {
1815 global $USER;
1817 // first find the course context
1818 $coursecontext = $context->get_course_context();
1820 // make sure there is a real user specified
1821 if ($user === null) {
1822 $userid = isset($USER->id) ? $USER->id : 0;
1823 } else {
1824 $userid = is_object($user) ? $user->id : $user;
1827 if (isguestuser($userid)) {
1828 // can not inspect or be enrolled
1829 return true;
1832 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1833 // viewing users appear out of nowhere, they are neither guests nor participants
1834 return false;
1837 // consider only real active enrolments here
1838 if (is_enrolled($coursecontext, $user, '', true)) {
1839 return false;
1842 return true;
1846 * Returns true if the user has moodle/course:view capability in the course,
1847 * this is intended for admins, managers (aka small admins), inspectors, etc.
1849 * @param context $context
1850 * @param int|stdClass $user, if null $USER is used
1851 * @param string $withcapability extra capability name
1852 * @return bool
1854 function is_viewing(context $context, $user = null, $withcapability = '') {
1855 // first find the course context
1856 $coursecontext = $context->get_course_context();
1858 if (isguestuser($user)) {
1859 // can not inspect
1860 return false;
1863 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1864 // admins are allowed to inspect courses
1865 return false;
1868 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1869 // site admins always have the capability, but the enrolment above blocks
1870 return false;
1873 return true;
1877 * Returns true if user is enrolled (is participating) in course
1878 * this is intended for students and teachers.
1880 * @param context $context
1881 * @param int|stdClass $user, if null $USER is used, otherwise user object or id expected
1882 * @param string $withcapability extra capability name
1883 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1884 * @return bool
1886 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1887 global $USER, $DB;
1889 // first find the course context
1890 $coursecontext = $context->get_course_context();
1892 // make sure there is a real user specified
1893 if ($user === null) {
1894 $userid = isset($USER->id) ? $USER->id : 0;
1895 } else {
1896 $userid = is_object($user) ? $user->id : $user;
1899 if (empty($userid)) {
1900 // not-logged-in!
1901 return false;
1902 } else if (isguestuser($userid)) {
1903 // guest account can not be enrolled anywhere
1904 return false;
1907 if ($coursecontext->instanceid == SITEID) {
1908 // everybody participates on frontpage
1909 } else {
1910 if ($onlyactive) {
1911 $sql = "SELECT ue.*
1912 FROM {user_enrolments} ue
1913 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1914 JOIN {user} u ON u.id = ue.userid
1915 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
1916 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
1917 // this result should be very small, better not do the complex time checks in sql for now ;-)
1918 $enrolments = $DB->get_records_sql($sql, $params);
1919 $now = time();
1920 // make sure the enrol period is ok
1921 $result = false;
1922 foreach ($enrolments as $e) {
1923 if ($e->timestart > $now) {
1924 continue;
1926 if ($e->timeend and $e->timeend < $now) {
1927 continue;
1929 $result = true;
1930 break;
1932 if (!$result) {
1933 return false;
1936 } else {
1937 // any enrolment is good for us here, even outdated, disabled or inactive
1938 $sql = "SELECT 'x'
1939 FROM {user_enrolments} ue
1940 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1941 JOIN {user} u ON u.id = ue.userid
1942 WHERE ue.userid = :userid AND u.deleted = 0";
1943 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
1944 if (!$DB->record_exists_sql($sql, $params)) {
1945 return false;
1950 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1951 return false;
1954 return true;
1958 * Returns true if the user is able to access the course.
1960 * This function is in no way, shape, or form a substitute for require_login.
1961 * It should only be used in circumstances where it is not possible to call require_login
1962 * such as the navigation.
1964 * This function checks many of the methods of access to a course such as the view
1965 * capability, enrollments, and guest access. It also makes use of the cache
1966 * generated by require_login for guest access.
1968 * The flags within the $USER object that are used here should NEVER be used outside
1969 * of this function can_access_course and require_login. Doing so WILL break future
1970 * versions.
1972 * @param context $context
1973 * @param stdClass|null $user
1974 * @param string $withcapability Check for this capability as well.
1975 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1976 * @param boolean $trustcache If set to false guest access will always be checked
1977 * against the enrolment plugins from the course, rather
1978 * than the cache generated by require_login.
1979 * @return boolean Returns true if the user is able to access the course
1981 function can_access_course(context $context, $user = null, $withcapability = '', $onlyactive = false, $trustcache = true) {
1982 global $DB, $USER;
1984 $coursecontext = $context->get_course_context();
1985 $courseid = $coursecontext->instanceid;
1987 // First check the obvious, is the user viewing or is the user enrolled.
1988 if (is_viewing($coursecontext, $user, $withcapability) || is_enrolled($coursecontext, $user, $withcapability, $onlyactive)) {
1989 // How easy was that!
1990 return true;
1993 $access = false;
1994 if (!isset($USER->enrol)) {
1995 // Cache hasn't been generated yet so we can't trust it
1996 $trustcache = false;
1998 * These flags within the $USER object should NEVER be used outside of this
1999 * function can_access_course and the function require_login.
2000 * Doing so WILL break future versions!!!!
2002 $USER->enrol = array();
2003 $USER->enrol['enrolled'] = array();
2004 $USER->enrol['tempguest'] = array();
2007 // If we don't trust the cache we need to check with the courses enrolment
2008 // plugin instances to see if the user can access the course as a guest.
2009 if (!$trustcache) {
2010 // Ok, off to the database we go!
2011 $instances = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2012 $enrols = enrol_get_plugins(true);
2013 foreach($instances as $instance) {
2014 if (!isset($enrols[$instance->enrol])) {
2015 continue;
2017 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2018 if ($until !== false) {
2019 // Never use me anywhere but here and require_login
2020 $USER->enrol['tempguest'][$courseid] = $until;
2021 $access = true;
2022 break;
2027 // If we don't already have access (from above) check the cache and see whether
2028 // there is record of it in there.
2029 if (!$access && isset($USER->enrol['tempguest'][$courseid])) {
2030 // Never use me anywhere but here and require_login
2031 if ($USER->enrol['tempguest'][$courseid] == 0) {
2032 $access = true;
2033 } else if ($USER->enrol['tempguest'][$courseid] > time()) {
2034 $access = true;
2035 } else {
2036 //expired
2037 unset($USER->enrol['tempguest'][$courseid]);
2040 return $access;
2044 * Returns array with sql code and parameters returning all ids
2045 * of users enrolled into course.
2047 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2049 * @param context $context
2050 * @param string $withcapability
2051 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2052 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2053 * @return array list($sql, $params)
2055 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2056 global $DB, $CFG;
2058 // use unique prefix just in case somebody makes some SQL magic with the result
2059 static $i = 0;
2060 $i++;
2061 $prefix = 'eu'.$i.'_';
2063 // first find the course context
2064 $coursecontext = $context->get_course_context();
2066 $isfrontpage = ($coursecontext->instanceid == SITEID);
2068 $joins = array();
2069 $wheres = array();
2070 $params = array();
2072 list($contextids, $contextpaths) = get_context_info_list($context);
2074 // get all relevant capability info for all roles
2075 if ($withcapability) {
2076 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2077 $cparams['cap'] = $withcapability;
2079 $defs = array();
2080 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2081 FROM {role_capabilities} rc
2082 JOIN {context} ctx on rc.contextid = ctx.id
2083 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2084 $rcs = $DB->get_records_sql($sql, $cparams);
2085 foreach ($rcs as $rc) {
2086 $defs[$rc->path][$rc->roleid] = $rc->permission;
2089 $access = array();
2090 if (!empty($defs)) {
2091 foreach ($contextpaths as $path) {
2092 if (empty($defs[$path])) {
2093 continue;
2095 foreach($defs[$path] as $roleid => $perm) {
2096 if ($perm == CAP_PROHIBIT) {
2097 $access[$roleid] = CAP_PROHIBIT;
2098 continue;
2100 if (!isset($access[$roleid])) {
2101 $access[$roleid] = (int)$perm;
2107 unset($defs);
2109 // make lists of roles that are needed and prohibited
2110 $needed = array(); // one of these is enough
2111 $prohibited = array(); // must not have any of these
2112 foreach ($access as $roleid => $perm) {
2113 if ($perm == CAP_PROHIBIT) {
2114 unset($needed[$roleid]);
2115 $prohibited[$roleid] = true;
2116 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2117 $needed[$roleid] = true;
2121 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2122 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2124 $nobody = false;
2126 if ($isfrontpage) {
2127 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2128 $nobody = true;
2129 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2130 // everybody not having prohibit has the capability
2131 $needed = array();
2132 } else if (empty($needed)) {
2133 $nobody = true;
2135 } else {
2136 if (!empty($prohibited[$defaultuserroleid])) {
2137 $nobody = true;
2138 } else if (!empty($needed[$defaultuserroleid])) {
2139 // everybody not having prohibit has the capability
2140 $needed = array();
2141 } else if (empty($needed)) {
2142 $nobody = true;
2146 if ($nobody) {
2147 // nobody can match so return some SQL that does not return any results
2148 $wheres[] = "1 = 2";
2150 } else {
2152 if ($needed) {
2153 $ctxids = implode(',', $contextids);
2154 $roleids = implode(',', array_keys($needed));
2155 $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))";
2158 if ($prohibited) {
2159 $ctxids = implode(',', $contextids);
2160 $roleids = implode(',', array_keys($prohibited));
2161 $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))";
2162 $wheres[] = "{$prefix}ra4.id IS NULL";
2165 if ($groupid) {
2166 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2167 $params["{$prefix}gmid"] = $groupid;
2171 } else {
2172 if ($groupid) {
2173 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2174 $params["{$prefix}gmid"] = $groupid;
2178 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2179 $params["{$prefix}guestid"] = $CFG->siteguest;
2181 if ($isfrontpage) {
2182 // all users are "enrolled" on the frontpage
2183 } else {
2184 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2185 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2186 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2188 if ($onlyactive) {
2189 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2190 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2191 $now = round(time(), -2); // rounding helps caching in DB
2192 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2193 $prefix.'active'=>ENROL_USER_ACTIVE,
2194 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2198 $joins = implode("\n", $joins);
2199 $wheres = "WHERE ".implode(" AND ", $wheres);
2201 $sql = "SELECT DISTINCT {$prefix}u.id
2202 FROM {user} {$prefix}u
2203 $joins
2204 $wheres";
2206 return array($sql, $params);
2210 * Returns list of users enrolled into course.
2212 * @param context $context
2213 * @param string $withcapability
2214 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2215 * @param string $userfields requested user record fields
2216 * @param string $orderby
2217 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2218 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2219 * @return array of user records
2221 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
2222 global $DB;
2224 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2225 $sql = "SELECT $userfields
2226 FROM {user} u
2227 JOIN ($esql) je ON je.id = u.id
2228 WHERE u.deleted = 0";
2230 if ($orderby) {
2231 $sql = "$sql ORDER BY $orderby";
2232 } else {
2233 $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
2236 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2240 * Counts list of users enrolled into course (as per above function)
2242 * @param context $context
2243 * @param string $withcapability
2244 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2245 * @return array of user records
2247 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0) {
2248 global $DB;
2250 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2251 $sql = "SELECT count(u.id)
2252 FROM {user} u
2253 JOIN ($esql) je ON je.id = u.id
2254 WHERE u.deleted = 0";
2256 return $DB->count_records_sql($sql, $params);
2260 * Loads the capability definitions for the component (from file).
2262 * Loads the capability definitions for the component (from file). If no
2263 * capabilities are defined for the component, we simply return an empty array.
2265 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2266 * @return array array of capabilities
2268 function load_capability_def($component) {
2269 $defpath = get_component_directory($component).'/db/access.php';
2271 $capabilities = array();
2272 if (file_exists($defpath)) {
2273 require($defpath);
2274 if (!empty(${$component.'_capabilities'})) {
2275 // BC capability array name
2276 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2277 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2278 $capabilities = ${$component.'_capabilities'};
2282 return $capabilities;
2286 * Gets the capabilities that have been cached in the database for this component.
2288 * @param string $component - examples: 'moodle', 'mod_forum'
2289 * @return array array of capabilities
2291 function get_cached_capabilities($component = 'moodle') {
2292 global $DB;
2293 return $DB->get_records('capabilities', array('component'=>$component));
2297 * Returns default capabilities for given role archetype.
2299 * @param string $archetype role archetype
2300 * @return array
2302 function get_default_capabilities($archetype) {
2303 global $DB;
2305 if (!$archetype) {
2306 return array();
2309 $alldefs = array();
2310 $defaults = array();
2311 $components = array();
2312 $allcaps = $DB->get_records('capabilities');
2314 foreach ($allcaps as $cap) {
2315 if (!in_array($cap->component, $components)) {
2316 $components[] = $cap->component;
2317 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2320 foreach($alldefs as $name=>$def) {
2321 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2322 if (isset($def['archetypes'])) {
2323 if (isset($def['archetypes'][$archetype])) {
2324 $defaults[$name] = $def['archetypes'][$archetype];
2326 // 'legacy' is for backward compatibility with 1.9 access.php
2327 } else {
2328 if (isset($def['legacy'][$archetype])) {
2329 $defaults[$name] = $def['legacy'][$archetype];
2334 return $defaults;
2338 * Reset role capabilities to default according to selected role archetype.
2339 * If no archetype selected, removes all capabilities.
2341 * @param int $roleid
2342 * @return void
2344 function reset_role_capabilities($roleid) {
2345 global $DB;
2347 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2348 $defaultcaps = get_default_capabilities($role->archetype);
2350 $systemcontext = context_system::instance();
2352 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2354 foreach($defaultcaps as $cap=>$permission) {
2355 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2360 * Updates the capabilities table with the component capability definitions.
2361 * If no parameters are given, the function updates the core moodle
2362 * capabilities.
2364 * Note that the absence of the db/access.php capabilities definition file
2365 * will cause any stored capabilities for the component to be removed from
2366 * the database.
2368 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2369 * @return boolean true if success, exception in case of any problems
2371 function update_capabilities($component = 'moodle') {
2372 global $DB, $OUTPUT;
2374 $storedcaps = array();
2376 $filecaps = load_capability_def($component);
2377 foreach($filecaps as $capname=>$unused) {
2378 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2379 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2383 $cachedcaps = get_cached_capabilities($component);
2384 if ($cachedcaps) {
2385 foreach ($cachedcaps as $cachedcap) {
2386 array_push($storedcaps, $cachedcap->name);
2387 // update risk bitmasks and context levels in existing capabilities if needed
2388 if (array_key_exists($cachedcap->name, $filecaps)) {
2389 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2390 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2392 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2393 $updatecap = new stdClass();
2394 $updatecap->id = $cachedcap->id;
2395 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2396 $DB->update_record('capabilities', $updatecap);
2398 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2399 $updatecap = new stdClass();
2400 $updatecap->id = $cachedcap->id;
2401 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2402 $DB->update_record('capabilities', $updatecap);
2405 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2406 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2408 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2409 $updatecap = new stdClass();
2410 $updatecap->id = $cachedcap->id;
2411 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2412 $DB->update_record('capabilities', $updatecap);
2418 // Are there new capabilities in the file definition?
2419 $newcaps = array();
2421 foreach ($filecaps as $filecap => $def) {
2422 if (!$storedcaps ||
2423 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2424 if (!array_key_exists('riskbitmask', $def)) {
2425 $def['riskbitmask'] = 0; // no risk if not specified
2427 $newcaps[$filecap] = $def;
2430 // Add new capabilities to the stored definition.
2431 foreach ($newcaps as $capname => $capdef) {
2432 $capability = new stdClass();
2433 $capability->name = $capname;
2434 $capability->captype = $capdef['captype'];
2435 $capability->contextlevel = $capdef['contextlevel'];
2436 $capability->component = $component;
2437 $capability->riskbitmask = $capdef['riskbitmask'];
2439 $DB->insert_record('capabilities', $capability, false);
2441 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
2442 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2443 foreach ($rolecapabilities as $rolecapability){
2444 //assign_capability will update rather than insert if capability exists
2445 if (!assign_capability($capname, $rolecapability->permission,
2446 $rolecapability->roleid, $rolecapability->contextid, true)){
2447 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2451 // we ignore archetype key if we have cloned permissions
2452 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2453 assign_legacy_capabilities($capname, $capdef['archetypes']);
2454 // 'legacy' is for backward compatibility with 1.9 access.php
2455 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2456 assign_legacy_capabilities($capname, $capdef['legacy']);
2459 // Are there any capabilities that have been removed from the file
2460 // definition that we need to delete from the stored capabilities and
2461 // role assignments?
2462 capabilities_cleanup($component, $filecaps);
2464 // reset static caches
2465 accesslib_clear_all_caches(false);
2467 return true;
2471 * Deletes cached capabilities that are no longer needed by the component.
2472 * Also unassigns these capabilities from any roles that have them.
2474 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2475 * @param array $newcapdef array of the new capability definitions that will be
2476 * compared with the cached capabilities
2477 * @return int number of deprecated capabilities that have been removed
2479 function capabilities_cleanup($component, $newcapdef = null) {
2480 global $DB;
2482 $removedcount = 0;
2484 if ($cachedcaps = get_cached_capabilities($component)) {
2485 foreach ($cachedcaps as $cachedcap) {
2486 if (empty($newcapdef) ||
2487 array_key_exists($cachedcap->name, $newcapdef) === false) {
2489 // Remove from capabilities cache.
2490 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2491 $removedcount++;
2492 // Delete from roles.
2493 if ($roles = get_roles_with_capability($cachedcap->name)) {
2494 foreach($roles as $role) {
2495 if (!unassign_capability($cachedcap->name, $role->id)) {
2496 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2500 } // End if.
2503 return $removedcount;
2507 * Returns an array of all the known types of risk
2508 * The array keys can be used, for example as CSS class names, or in calls to
2509 * print_risk_icon. The values are the corresponding RISK_ constants.
2511 * @return array all the known types of risk.
2513 function get_all_risks() {
2514 return array(
2515 'riskmanagetrust' => RISK_MANAGETRUST,
2516 'riskconfig' => RISK_CONFIG,
2517 'riskxss' => RISK_XSS,
2518 'riskpersonal' => RISK_PERSONAL,
2519 'riskspam' => RISK_SPAM,
2520 'riskdataloss' => RISK_DATALOSS,
2525 * Return a link to moodle docs for a given capability name
2527 * @param object $capability a capability - a row from the mdl_capabilities table.
2528 * @return string the human-readable capability name as a link to Moodle Docs.
2530 function get_capability_docs_link($capability) {
2531 $url = get_docs_url('Capabilities/' . $capability->name);
2532 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2536 * This function pulls out all the resolved capabilities (overrides and
2537 * defaults) of a role used in capability overrides in contexts at a given
2538 * context.
2540 * @param context $context
2541 * @param int $roleid
2542 * @param string $cap capability, optional, defaults to ''
2543 * @return array of capabilities
2545 function role_context_capabilities($roleid, context $context, $cap = '') {
2546 global $DB;
2548 $contexts = $context->get_parent_context_ids(true);
2549 $contexts = '('.implode(',', $contexts).')';
2551 $params = array($roleid);
2553 if ($cap) {
2554 $search = " AND rc.capability = ? ";
2555 $params[] = $cap;
2556 } else {
2557 $search = '';
2560 $sql = "SELECT rc.*
2561 FROM {role_capabilities} rc, {context} c
2562 WHERE rc.contextid in $contexts
2563 AND rc.roleid = ?
2564 AND rc.contextid = c.id $search
2565 ORDER BY c.contextlevel DESC, rc.capability DESC";
2567 $capabilities = array();
2569 if ($records = $DB->get_records_sql($sql, $params)) {
2570 // We are traversing via reverse order.
2571 foreach ($records as $record) {
2572 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2573 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2574 $capabilities[$record->capability] = $record->permission;
2578 return $capabilities;
2582 * Constructs array with contextids as first parameter and context paths,
2583 * in both cases bottom top including self.
2585 * @private
2586 * @param context $context
2587 * @return array
2589 function get_context_info_list(context $context) {
2590 $contextids = explode('/', ltrim($context->path, '/'));
2591 $contextpaths = array();
2592 $contextids2 = $contextids;
2593 while ($contextids2) {
2594 $contextpaths[] = '/' . implode('/', $contextids2);
2595 array_pop($contextids2);
2597 return array($contextids, $contextpaths);
2601 * Check if context is the front page context or a context inside it
2603 * Returns true if this context is the front page context, or a context inside it,
2604 * otherwise false.
2606 * @param context $context a context object.
2607 * @return bool
2609 function is_inside_frontpage(context $context) {
2610 $frontpagecontext = context_course::instance(SITEID);
2611 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2615 * Returns capability information (cached)
2617 * @param string $capabilityname
2618 * @return object or null if capability not found
2620 function get_capability_info($capabilityname) {
2621 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2623 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2625 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2626 $ACCESSLIB_PRIVATE->capabilities = array();
2627 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2628 foreach ($caps as $cap) {
2629 $capname = $cap->name;
2630 unset($cap->id);
2631 unset($cap->name);
2632 $cap->riskbitmask = (int)$cap->riskbitmask;
2633 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2637 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2641 * Returns the human-readable, translated version of the capability.
2642 * Basically a big switch statement.
2644 * @param string $capabilityname e.g. mod/choice:readresponses
2645 * @return string
2647 function get_capability_string($capabilityname) {
2649 // Typical capability name is 'plugintype/pluginname:capabilityname'
2650 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2652 if ($type === 'moodle') {
2653 $component = 'core_role';
2654 } else if ($type === 'quizreport') {
2655 //ugly hack!!
2656 $component = 'quiz_'.$name;
2657 } else {
2658 $component = $type.'_'.$name;
2661 $stringname = $name.':'.$capname;
2663 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2664 return get_string($stringname, $component);
2667 $dir = get_component_directory($component);
2668 if (!file_exists($dir)) {
2669 // plugin broken or does not exist, do not bother with printing of debug message
2670 return $capabilityname.' ???';
2673 // something is wrong in plugin, better print debug
2674 return get_string($stringname, $component);
2678 * This gets the mod/block/course/core etc strings.
2680 * @param string $component
2681 * @param int $contextlevel
2682 * @return string|bool String is success, false if failed
2684 function get_component_string($component, $contextlevel) {
2686 if ($component === 'moodle' or $component === 'core') {
2687 switch ($contextlevel) {
2688 // TODO: this should probably use context level names instead
2689 case CONTEXT_SYSTEM: return get_string('coresystem');
2690 case CONTEXT_USER: return get_string('users');
2691 case CONTEXT_COURSECAT: return get_string('categories');
2692 case CONTEXT_COURSE: return get_string('course');
2693 case CONTEXT_MODULE: return get_string('activities');
2694 case CONTEXT_BLOCK: return get_string('block');
2695 default: print_error('unknowncontext');
2699 list($type, $name) = normalize_component($component);
2700 $dir = get_plugin_directory($type, $name);
2701 if (!file_exists($dir)) {
2702 // plugin not installed, bad luck, there is no way to find the name
2703 return $component.' ???';
2706 switch ($type) {
2707 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2708 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2709 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2710 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2711 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2712 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2713 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2714 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2715 case 'mod':
2716 if (get_string_manager()->string_exists('pluginname', $component)) {
2717 return get_string('activity').': '.get_string('pluginname', $component);
2718 } else {
2719 return get_string('activity').': '.get_string('modulename', $component);
2721 default: return get_string('pluginname', $component);
2726 * Gets the list of roles assigned to this context and up (parents)
2727 * from the list of roles that are visible on user profile page
2728 * and participants page.
2730 * @param context $context
2731 * @return array
2733 function get_profile_roles(context $context) {
2734 global $CFG, $DB;
2736 if (empty($CFG->profileroles)) {
2737 return array();
2740 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2741 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2742 $params = array_merge($params, $cparams);
2744 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2745 FROM {role_assignments} ra, {role} r
2746 WHERE r.id = ra.roleid
2747 AND ra.contextid $contextlist
2748 AND r.id $rallowed
2749 ORDER BY r.sortorder ASC";
2751 return $DB->get_records_sql($sql, $params);
2755 * Gets the list of roles assigned to this context and up (parents)
2757 * @param context $context
2758 * @return array
2760 function get_roles_used_in_context(context $context) {
2761 global $DB;
2763 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true));
2765 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2766 FROM {role_assignments} ra, {role} r
2767 WHERE r.id = ra.roleid
2768 AND ra.contextid $contextlist
2769 ORDER BY r.sortorder ASC";
2771 return $DB->get_records_sql($sql, $params);
2775 * This function is used to print roles column in user profile page.
2776 * It is using the CFG->profileroles to limit the list to only interesting roles.
2777 * (The permission tab has full details of user role assignments.)
2779 * @param int $userid
2780 * @param int $courseid
2781 * @return string
2783 function get_user_roles_in_course($userid, $courseid) {
2784 global $CFG, $DB;
2786 if (empty($CFG->profileroles)) {
2787 return '';
2790 if ($courseid == SITEID) {
2791 $context = context_system::instance();
2792 } else {
2793 $context = context_course::instance($courseid);
2796 if (empty($CFG->profileroles)) {
2797 return array();
2800 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2801 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2802 $params = array_merge($params, $cparams);
2804 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2805 FROM {role_assignments} ra, {role} r
2806 WHERE r.id = ra.roleid
2807 AND ra.contextid $contextlist
2808 AND r.id $rallowed
2809 AND ra.userid = :userid
2810 ORDER BY r.sortorder ASC";
2811 $params['userid'] = $userid;
2813 $rolestring = '';
2815 if ($roles = $DB->get_records_sql($sql, $params)) {
2816 foreach ($roles as $userrole) {
2817 $rolenames[$userrole->id] = $userrole->name;
2820 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
2822 foreach ($rolenames as $roleid => $rolename) {
2823 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
2825 $rolestring = implode(',', $rolenames);
2828 return $rolestring;
2832 * Checks if a user can assign users to a particular role in this context
2834 * @param context $context
2835 * @param int $targetroleid - the id of the role you want to assign users to
2836 * @return boolean
2838 function user_can_assign(context $context, $targetroleid) {
2839 global $DB;
2841 // first check if user has override capability
2842 // if not return false;
2843 if (!has_capability('moodle/role:assign', $context)) {
2844 return false;
2846 // pull out all active roles of this user from this context(or above)
2847 if ($userroles = get_user_roles($context)) {
2848 foreach ($userroles as $userrole) {
2849 // if any in the role_allow_override table, then it's ok
2850 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2851 return true;
2856 return false;
2860 * Returns all site roles in correct sort order.
2862 * @return array
2864 function get_all_roles() {
2865 global $DB;
2866 return $DB->get_records('role', null, 'sortorder ASC');
2870 * Returns roles of a specified archetype
2872 * @param string $archetype
2873 * @return array of full role records
2875 function get_archetype_roles($archetype) {
2876 global $DB;
2877 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2881 * Gets all the user roles assigned in this context, or higher contexts
2882 * this is mainly used when checking if a user can assign a role, or overriding a role
2883 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2884 * allow_override tables
2886 * @param context $context
2887 * @param int $userid
2888 * @param bool $checkparentcontexts defaults to true
2889 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2890 * @return array
2892 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2893 global $USER, $DB;
2895 if (empty($userid)) {
2896 if (empty($USER->id)) {
2897 return array();
2899 $userid = $USER->id;
2902 if ($checkparentcontexts) {
2903 $contextids = $context->get_parent_context_ids();
2904 } else {
2905 $contextids = array();
2907 $contextids[] = $context->id;
2909 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2911 array_unshift($params, $userid);
2913 $sql = "SELECT ra.*, r.name, r.shortname
2914 FROM {role_assignments} ra, {role} r, {context} c
2915 WHERE ra.userid = ?
2916 AND ra.roleid = r.id
2917 AND ra.contextid = c.id
2918 AND ra.contextid $contextids
2919 ORDER BY $order";
2921 return $DB->get_records_sql($sql ,$params);
2925 * Creates a record in the role_allow_override table
2927 * @param int $sroleid source roleid
2928 * @param int $troleid target roleid
2929 * @return void
2931 function allow_override($sroleid, $troleid) {
2932 global $DB;
2934 $record = new stdClass();
2935 $record->roleid = $sroleid;
2936 $record->allowoverride = $troleid;
2937 $DB->insert_record('role_allow_override', $record);
2941 * Creates a record in the role_allow_assign table
2943 * @param int $fromroleid source roleid
2944 * @param int $targetroleid target roleid
2945 * @return void
2947 function allow_assign($fromroleid, $targetroleid) {
2948 global $DB;
2950 $record = new stdClass();
2951 $record->roleid = $fromroleid;
2952 $record->allowassign = $targetroleid;
2953 $DB->insert_record('role_allow_assign', $record);
2957 * Creates a record in the role_allow_switch table
2959 * @param int $fromroleid source roleid
2960 * @param int $targetroleid target roleid
2961 * @return void
2963 function allow_switch($fromroleid, $targetroleid) {
2964 global $DB;
2966 $record = new stdClass();
2967 $record->roleid = $fromroleid;
2968 $record->allowswitch = $targetroleid;
2969 $DB->insert_record('role_allow_switch', $record);
2973 * Gets a list of roles that this user can assign in this context
2975 * @param context $context the context.
2976 * @param int $rolenamedisplay the type of role name to display. One of the
2977 * ROLENAME_X constants. Default ROLENAME_ALIAS.
2978 * @param bool $withusercounts if true, count the number of users with each role.
2979 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
2980 * @return array if $withusercounts is false, then an array $roleid => $rolename.
2981 * if $withusercounts is true, returns a list of three arrays,
2982 * $rolenames, $rolecounts, and $nameswithcounts.
2984 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
2985 global $USER, $DB;
2987 // make sure there is a real user specified
2988 if ($user === null) {
2989 $userid = isset($USER->id) ? $USER->id : 0;
2990 } else {
2991 $userid = is_object($user) ? $user->id : $user;
2994 if (!has_capability('moodle/role:assign', $context, $userid)) {
2995 if ($withusercounts) {
2996 return array(array(), array(), array());
2997 } else {
2998 return array();
3002 $parents = $context->get_parent_context_ids(true);
3003 $contexts = implode(',' , $parents);
3005 $params = array();
3006 $extrafields = '';
3007 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT or $rolenamedisplay == ROLENAME_SHORT) {
3008 $extrafields .= ', r.shortname';
3011 if ($withusercounts) {
3012 $extrafields = ', (SELECT count(u.id)
3013 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3014 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3015 ) AS usercount';
3016 $params['conid'] = $context->id;
3019 if (is_siteadmin($userid)) {
3020 // show all roles allowed in this context to admins
3021 $assignrestriction = "";
3022 } else {
3023 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3024 FROM {role_allow_assign} raa
3025 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3026 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3027 ) ar ON ar.id = r.id";
3028 $params['userid'] = $userid;
3030 $params['contextlevel'] = $context->contextlevel;
3031 $sql = "SELECT r.id, r.name $extrafields
3032 FROM {role} r
3033 $assignrestriction
3034 JOIN {role_context_levels} rcl ON r.id = rcl.roleid
3035 WHERE rcl.contextlevel = :contextlevel
3036 ORDER BY r.sortorder ASC";
3037 $roles = $DB->get_records_sql($sql, $params);
3039 $rolenames = array();
3040 foreach ($roles as $role) {
3041 if ($rolenamedisplay == ROLENAME_SHORT) {
3042 $rolenames[$role->id] = $role->shortname;
3043 continue;
3045 $rolenames[$role->id] = $role->name;
3046 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3047 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3050 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT and $rolenamedisplay != ROLENAME_SHORT) {
3051 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3054 if (!$withusercounts) {
3055 return $rolenames;
3058 $rolecounts = array();
3059 $nameswithcounts = array();
3060 foreach ($roles as $role) {
3061 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3062 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3064 return array($rolenames, $rolecounts, $nameswithcounts);
3068 * Gets a list of roles that this user can switch to in a context
3070 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3071 * This function just process the contents of the role_allow_switch table. You also need to
3072 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3074 * @param context $context a context.
3075 * @return array an array $roleid => $rolename.
3077 function get_switchable_roles(context $context) {
3078 global $USER, $DB;
3080 $params = array();
3081 $extrajoins = '';
3082 $extrawhere = '';
3083 if (!is_siteadmin()) {
3084 // Admins are allowed to switch to any role with.
3085 // Others are subject to the additional constraint that the switch-to role must be allowed by
3086 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3087 $parents = $context->get_parent_context_ids(true);
3088 $contexts = implode(',' , $parents);
3090 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3091 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3092 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3093 $params['userid'] = $USER->id;
3096 $query = "
3097 SELECT r.id, r.name
3098 FROM (SELECT DISTINCT rc.roleid
3099 FROM {role_capabilities} rc
3100 $extrajoins
3101 $extrawhere) idlist
3102 JOIN {role} r ON r.id = idlist.roleid
3103 ORDER BY r.sortorder";
3105 $rolenames = $DB->get_records_sql_menu($query, $params);
3106 return role_fix_names($rolenames, $context, ROLENAME_ALIAS);
3110 * Gets a list of roles that this user can override in this context.
3112 * @param context $context the context.
3113 * @param int $rolenamedisplay the type of role name to display. One of the
3114 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3115 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3116 * @return array if $withcounts is false, then an array $roleid => $rolename.
3117 * if $withusercounts is true, returns a list of three arrays,
3118 * $rolenames, $rolecounts, and $nameswithcounts.
3120 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3121 global $USER, $DB;
3123 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3124 if ($withcounts) {
3125 return array(array(), array(), array());
3126 } else {
3127 return array();
3131 $parents = $context->get_parent_context_ids(true);
3132 $contexts = implode(',' , $parents);
3134 $params = array();
3135 $extrafields = '';
3136 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3137 $extrafields .= ', ro.shortname';
3140 $params['userid'] = $USER->id;
3141 if ($withcounts) {
3142 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3143 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3144 $params['conid'] = $context->id;
3147 if (is_siteadmin()) {
3148 // show all roles to admins
3149 $roles = $DB->get_records_sql("
3150 SELECT ro.id, ro.name$extrafields
3151 FROM {role} ro
3152 ORDER BY ro.sortorder ASC", $params);
3154 } else {
3155 $roles = $DB->get_records_sql("
3156 SELECT ro.id, ro.name$extrafields
3157 FROM {role} ro
3158 JOIN (SELECT DISTINCT r.id
3159 FROM {role} r
3160 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3161 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3162 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3163 ) inline_view ON ro.id = inline_view.id
3164 ORDER BY ro.sortorder ASC", $params);
3167 $rolenames = array();
3168 foreach ($roles as $role) {
3169 $rolenames[$role->id] = $role->name;
3170 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3171 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3174 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT) {
3175 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3178 if (!$withcounts) {
3179 return $rolenames;
3182 $rolecounts = array();
3183 $nameswithcounts = array();
3184 foreach ($roles as $role) {
3185 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3186 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3188 return array($rolenames, $rolecounts, $nameswithcounts);
3192 * Create a role menu suitable for default role selection in enrol plugins.
3193 * @param context $context
3194 * @param int $addroleid current or default role - always added to list
3195 * @return array roleid=>localised role name
3197 function get_default_enrol_roles(context $context, $addroleid = null) {
3198 global $DB;
3200 $params = array('contextlevel'=>CONTEXT_COURSE);
3201 if ($addroleid) {
3202 $addrole = "OR r.id = :addroleid";
3203 $params['addroleid'] = $addroleid;
3204 } else {
3205 $addrole = "";
3207 $sql = "SELECT r.id, r.name
3208 FROM {role} r
3209 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3210 WHERE rcl.id IS NOT NULL $addrole
3211 ORDER BY sortorder DESC";
3213 $roles = $DB->get_records_sql_menu($sql, $params);
3214 $roles = role_fix_names($roles, $context, ROLENAME_BOTH);
3216 return $roles;
3220 * Return context levels where this role is assignable.
3221 * @param integer $roleid the id of a role.
3222 * @return array list of the context levels at which this role may be assigned.
3224 function get_role_contextlevels($roleid) {
3225 global $DB;
3226 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3227 'contextlevel', 'id,contextlevel');
3231 * Return roles suitable for assignment at the specified context level.
3233 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3235 * @param integer $contextlevel a contextlevel.
3236 * @return array list of role ids that are assignable at this context level.
3238 function get_roles_for_contextlevels($contextlevel) {
3239 global $DB;
3240 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3241 '', 'id,roleid');
3245 * Returns default context levels where roles can be assigned.
3247 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3248 * from the array returned by get_role_archetypes();
3249 * @return array list of the context levels at which this type of role may be assigned by default.
3251 function get_default_contextlevels($rolearchetype) {
3252 static $defaults = array(
3253 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3254 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3255 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3256 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3257 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3258 'guest' => array(),
3259 'user' => array(),
3260 'frontpage' => array());
3262 if (isset($defaults[$rolearchetype])) {
3263 return $defaults[$rolearchetype];
3264 } else {
3265 return array();
3270 * Set the context levels at which a particular role can be assigned.
3271 * Throws exceptions in case of error.
3273 * @param integer $roleid the id of a role.
3274 * @param array $contextlevels the context levels at which this role should be assignable,
3275 * duplicate levels are removed.
3276 * @return void
3278 function set_role_contextlevels($roleid, array $contextlevels) {
3279 global $DB;
3280 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3281 $rcl = new stdClass();
3282 $rcl->roleid = $roleid;
3283 $contextlevels = array_unique($contextlevels);
3284 foreach ($contextlevels as $level) {
3285 $rcl->contextlevel = $level;
3286 $DB->insert_record('role_context_levels', $rcl, false, true);
3291 * Who has this capability in this context?
3293 * This can be a very expensive call - use sparingly and keep
3294 * the results if you are going to need them again soon.
3296 * Note if $fields is empty this function attempts to get u.*
3297 * which can get rather large - and has a serious perf impact
3298 * on some DBs.
3300 * @param context $context
3301 * @param string|array $capability - capability name(s)
3302 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3303 * @param string $sort - the sort order. Default is lastaccess time.
3304 * @param mixed $limitfrom - number of records to skip (offset)
3305 * @param mixed $limitnum - number of records to fetch
3306 * @param string|array $groups - single group or array of groups - only return
3307 * users who are in one of these group(s).
3308 * @param string|array $exceptions - list of users to exclude, comma separated or array
3309 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3310 * @param bool $view_ignored - use get_enrolled_sql() instead
3311 * @param bool $useviewallgroups if $groups is set the return users who
3312 * have capability both $capability and moodle/site:accessallgroups
3313 * in this context, as well as users who have $capability and who are
3314 * in $groups.
3315 * @return mixed
3317 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3318 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3319 global $CFG, $DB;
3321 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3322 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3324 $ctxids = trim($context->path, '/');
3325 $ctxids = str_replace('/', ',', $ctxids);
3327 // Context is the frontpage
3328 $iscoursepage = false; // coursepage other than fp
3329 $isfrontpage = false;
3330 if ($context->contextlevel == CONTEXT_COURSE) {
3331 if ($context->instanceid == SITEID) {
3332 $isfrontpage = true;
3333 } else {
3334 $iscoursepage = true;
3337 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3339 $caps = (array)$capability;
3341 // construct list of context paths bottom-->top
3342 list($contextids, $paths) = get_context_info_list($context);
3344 // we need to find out all roles that have these capabilities either in definition or in overrides
3345 $defs = array();
3346 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3347 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3348 $params = array_merge($params, $params2);
3349 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3350 FROM {role_capabilities} rc
3351 JOIN {context} ctx on rc.contextid = ctx.id
3352 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3354 $rcs = $DB->get_records_sql($sql, $params);
3355 foreach ($rcs as $rc) {
3356 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3359 // go through the permissions bottom-->top direction to evaluate the current permission,
3360 // first one wins (prohibit is an exception that always wins)
3361 $access = array();
3362 foreach ($caps as $cap) {
3363 foreach ($paths as $path) {
3364 if (empty($defs[$cap][$path])) {
3365 continue;
3367 foreach($defs[$cap][$path] as $roleid => $perm) {
3368 if ($perm == CAP_PROHIBIT) {
3369 $access[$cap][$roleid] = CAP_PROHIBIT;
3370 continue;
3372 if (!isset($access[$cap][$roleid])) {
3373 $access[$cap][$roleid] = (int)$perm;
3379 // make lists of roles that are needed and prohibited in this context
3380 $needed = array(); // one of these is enough
3381 $prohibited = array(); // must not have any of these
3382 foreach ($caps as $cap) {
3383 if (empty($access[$cap])) {
3384 continue;
3386 foreach ($access[$cap] as $roleid => $perm) {
3387 if ($perm == CAP_PROHIBIT) {
3388 unset($needed[$cap][$roleid]);
3389 $prohibited[$cap][$roleid] = true;
3390 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3391 $needed[$cap][$roleid] = true;
3394 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3395 // easy, nobody has the permission
3396 unset($needed[$cap]);
3397 unset($prohibited[$cap]);
3398 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3399 // everybody is disqualified on the frontapge
3400 unset($needed[$cap]);
3401 unset($prohibited[$cap]);
3403 if (empty($prohibited[$cap])) {
3404 unset($prohibited[$cap]);
3408 if (empty($needed)) {
3409 // there can not be anybody if no roles match this request
3410 return array();
3413 if (empty($prohibited)) {
3414 // we can compact the needed roles
3415 $n = array();
3416 foreach ($needed as $cap) {
3417 foreach ($cap as $roleid=>$unused) {
3418 $n[$roleid] = true;
3421 $needed = array('any'=>$n);
3422 unset($n);
3425 /// ***** Set up default fields ******
3426 if (empty($fields)) {
3427 if ($iscoursepage) {
3428 $fields = 'u.*, ul.timeaccess AS lastaccess';
3429 } else {
3430 $fields = 'u.*';
3432 } else {
3433 if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3434 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3438 /// Set up default sort
3439 if (empty($sort)) { // default to course lastaccess or just lastaccess
3440 if ($iscoursepage) {
3441 $sort = 'ul.timeaccess';
3442 } else {
3443 $sort = 'u.lastaccess';
3447 // Prepare query clauses
3448 $wherecond = array();
3449 $params = array();
3450 $joins = array();
3452 // User lastaccess JOIN
3453 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3454 // user_lastaccess is not required MDL-13810
3455 } else {
3456 if ($iscoursepage) {
3457 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3458 } else {
3459 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3463 /// We never return deleted users or guest account.
3464 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3465 $params['guestid'] = $CFG->siteguest;
3467 /// Groups
3468 if ($groups) {
3469 $groups = (array)$groups;
3470 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3471 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3472 $params = array_merge($params, $grpparams);
3474 if ($useviewallgroups) {
3475 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3476 if (!empty($viewallgroupsusers)) {
3477 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3478 } else {
3479 $wherecond[] = "($grouptest)";
3481 } else {
3482 $wherecond[] = "($grouptest)";
3486 /// User exceptions
3487 if (!empty($exceptions)) {
3488 $exceptions = (array)$exceptions;
3489 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3490 $params = array_merge($params, $exparams);
3491 $wherecond[] = "u.id $exsql";
3494 // now add the needed and prohibited roles conditions as joins
3495 if (!empty($needed['any'])) {
3496 // simple case - there are no prohibits involved
3497 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3498 // everybody
3499 } else {
3500 $joins[] = "JOIN (SELECT DISTINCT userid
3501 FROM {role_assignments}
3502 WHERE contextid IN ($ctxids)
3503 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3504 ) ra ON ra.userid = u.id";
3506 } else {
3507 $unions = array();
3508 $everybody = false;
3509 foreach ($needed as $cap=>$unused) {
3510 if (empty($prohibited[$cap])) {
3511 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3512 $everybody = true;
3513 break;
3514 } else {
3515 $unions[] = "SELECT userid
3516 FROM {role_assignments}
3517 WHERE contextid IN ($ctxids)
3518 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3520 } else {
3521 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3522 // nobody can have this cap because it is prevented in default roles
3523 continue;
3525 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3526 // everybody except the prohibitted - hiding does not matter
3527 $unions[] = "SELECT id AS userid
3528 FROM {user}
3529 WHERE id NOT IN (SELECT userid
3530 FROM {role_assignments}
3531 WHERE contextid IN ($ctxids)
3532 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3534 } else {
3535 $unions[] = "SELECT userid
3536 FROM {role_assignments}
3537 WHERE contextid IN ($ctxids)
3538 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3539 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3543 if (!$everybody) {
3544 if ($unions) {
3545 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3546 } else {
3547 // only prohibits found - nobody can be matched
3548 $wherecond[] = "1 = 2";
3553 // Collect WHERE conditions and needed joins
3554 $where = implode(' AND ', $wherecond);
3555 if ($where !== '') {
3556 $where = 'WHERE ' . $where;
3558 $joins = implode("\n", $joins);
3560 /// Ok, let's get the users!
3561 $sql = "SELECT $fields
3562 FROM {user} u
3563 $joins
3564 $where
3565 ORDER BY $sort";
3567 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3571 * Re-sort a users array based on a sorting policy
3573 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3574 * based on a sorting policy. This is to support the odd practice of
3575 * sorting teachers by 'authority', where authority was "lowest id of the role
3576 * assignment".
3578 * Will execute 1 database query. Only suitable for small numbers of users, as it
3579 * uses an u.id IN() clause.
3581 * Notes about the sorting criteria.
3583 * As a default, we cannot rely on role.sortorder because then
3584 * admins/coursecreators will always win. That is why the sane
3585 * rule "is locality matters most", with sortorder as 2nd
3586 * consideration.
3588 * If you want role.sortorder, use the 'sortorder' policy, and
3589 * name explicitly what roles you want to cover. It's probably
3590 * a good idea to see what roles have the capabilities you want
3591 * (array_diff() them against roiles that have 'can-do-anything'
3592 * to weed out admin-ish roles. Or fetch a list of roles from
3593 * variables like $CFG->coursecontact .
3595 * @param array $users Users array, keyed on userid
3596 * @param context $context
3597 * @param array $roles ids of the roles to include, optional
3598 * @param string $sortpolicy defaults to locality, more about
3599 * @return array sorted copy of the array
3601 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3602 global $DB;
3604 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3605 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3606 if (empty($roles)) {
3607 $roleswhere = '';
3608 } else {
3609 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3612 $sql = "SELECT ra.userid
3613 FROM {role_assignments} ra
3614 JOIN {role} r
3615 ON ra.roleid=r.id
3616 JOIN {context} ctx
3617 ON ra.contextid=ctx.id
3618 WHERE $userswhere
3619 $contextwhere
3620 $roleswhere";
3622 // Default 'locality' policy -- read PHPDoc notes
3623 // about sort policies...
3624 $orderby = 'ORDER BY '
3625 .'ctx.depth DESC, ' /* locality wins */
3626 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3627 .'ra.id'; /* role assignment order tie-breaker */
3628 if ($sortpolicy === 'sortorder') {
3629 $orderby = 'ORDER BY '
3630 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3631 .'ra.id'; /* role assignment order tie-breaker */
3634 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3635 $sortedusers = array();
3636 $seen = array();
3638 foreach ($sortedids as $id) {
3639 // Avoid duplicates
3640 if (isset($seen[$id])) {
3641 continue;
3643 $seen[$id] = true;
3645 // assign
3646 $sortedusers[$id] = $users[$id];
3648 return $sortedusers;
3652 * Gets all the users assigned this role in this context or higher
3654 * @param int $roleid (can also be an array of ints!)
3655 * @param context $context
3656 * @param bool $parent if true, get list of users assigned in higher context too
3657 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3658 * @param string $sort sort from user (u.) , role assignment (ra) or role (r.)
3659 * @param bool $gethidden_ignored use enrolments instead
3660 * @param string $group defaults to ''
3661 * @param mixed $limitfrom defaults to ''
3662 * @param mixed $limitnum defaults to ''
3663 * @param string $extrawheretest defaults to ''
3664 * @param string|array $whereparams defaults to ''
3665 * @return array
3667 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3668 $sort = 'u.lastname, u.firstname', $gethidden_ignored = null, $group = '',
3669 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereparams = array()) {
3670 global $DB;
3672 if (empty($fields)) {
3673 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3674 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
3675 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3676 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder';
3679 $parentcontexts = '';
3680 if ($parent) {
3681 $parentcontexts = substr($context->path, 1); // kill leading slash
3682 $parentcontexts = str_replace('/', ',', $parentcontexts);
3683 if ($parentcontexts !== '') {
3684 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3688 if ($roleid) {
3689 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3690 $roleselect = "AND ra.roleid $rids";
3691 } else {
3692 $params = array();
3693 $roleselect = '';
3696 if ($group) {
3697 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3698 $groupselect = " AND gm.groupid = ? ";
3699 $params[] = $group;
3700 } else {
3701 $groupjoin = '';
3702 $groupselect = '';
3705 array_unshift($params, $context->id);
3707 if ($extrawheretest) {
3708 $extrawheretest = ' AND ' . $extrawheretest;
3709 $params = array_merge($params, $whereparams);
3712 $sql = "SELECT DISTINCT $fields, ra.roleid
3713 FROM {role_assignments} ra
3714 JOIN {user} u ON u.id = ra.userid
3715 JOIN {role} r ON ra.roleid = r.id
3716 $groupjoin
3717 WHERE (ra.contextid = ? $parentcontexts)
3718 $roleselect
3719 $groupselect
3720 $extrawheretest
3721 ORDER BY $sort"; // join now so that we can just use fullname() later
3723 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3727 * Counts all the users assigned this role in this context or higher
3729 * @param int|array $roleid either int or an array of ints
3730 * @param context $context
3731 * @param bool $parent if true, get list of users assigned in higher context too
3732 * @return int Returns the result count
3734 function count_role_users($roleid, context $context, $parent = false) {
3735 global $DB;
3737 if ($parent) {
3738 if ($contexts = $context->get_parent_context_ids()) {
3739 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3740 } else {
3741 $parentcontexts = '';
3743 } else {
3744 $parentcontexts = '';
3747 if ($roleid) {
3748 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3749 $roleselect = "AND r.roleid $rids";
3750 } else {
3751 $params = array();
3752 $roleselect = '';
3755 array_unshift($params, $context->id);
3757 $sql = "SELECT COUNT(u.id)
3758 FROM {role_assignments} r
3759 JOIN {user} u ON u.id = r.userid
3760 WHERE (r.contextid = ? $parentcontexts)
3761 $roleselect
3762 AND u.deleted = 0";
3764 return $DB->count_records_sql($sql, $params);
3768 * This function gets the list of courses that this user has a particular capability in.
3769 * It is still not very efficient.
3771 * @param string $capability Capability in question
3772 * @param int $userid User ID or null for current user
3773 * @param bool $doanything True if 'doanything' is permitted (default)
3774 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3775 * otherwise use a comma-separated list of the fields you require, not including id
3776 * @param string $orderby If set, use a comma-separated list of fields from course
3777 * table with sql modifiers (DESC) if needed
3778 * @return array Array of courses, may have zero entries. Or false if query failed.
3780 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
3781 global $DB;
3783 // Convert fields list and ordering
3784 $fieldlist = '';
3785 if ($fieldsexceptid) {
3786 $fields = explode(',', $fieldsexceptid);
3787 foreach($fields as $field) {
3788 $fieldlist .= ',c.'.$field;
3791 if ($orderby) {
3792 $fields = explode(',', $orderby);
3793 $orderby = '';
3794 foreach($fields as $field) {
3795 if ($orderby) {
3796 $orderby .= ',';
3798 $orderby .= 'c.'.$field;
3800 $orderby = 'ORDER BY '.$orderby;
3803 // Obtain a list of everything relevant about all courses including context.
3804 // Note the result can be used directly as a context (we are going to), the course
3805 // fields are just appended.
3807 $courses = array();
3808 $rs = $DB->get_recordset_sql("SELECT x.*, c.id AS courseid $fieldlist
3809 FROM {course} c
3810 INNER JOIN {context} x
3811 ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
3812 $orderby");
3813 // Check capability for each course in turn
3814 foreach ($rs as $coursecontext) {
3815 if (has_capability($capability, $coursecontext, $userid, $doanything)) {
3816 // We've got the capability. Make the record look like a course record
3817 // and store it
3818 $coursecontext->id = $coursecontext->courseid;
3819 unset($coursecontext->courseid);
3820 unset($coursecontext->contextlevel);
3821 unset($coursecontext->instanceid);
3822 $courses[] = $coursecontext;
3825 $rs->close();
3826 return empty($courses) ? false : $courses;
3830 * This function finds the roles assigned directly to this context only
3831 * i.e. no roles in parent contexts
3833 * @param context $context
3834 * @return array
3836 function get_roles_on_exact_context(context $context) {
3837 global $DB;
3839 return $DB->get_records_sql("SELECT r.*
3840 FROM {role_assignments} ra, {role} r
3841 WHERE ra.roleid = r.id AND ra.contextid = ?",
3842 array($context->id));
3846 * Switches the current user to another role for the current session and only
3847 * in the given context.
3849 * The caller *must* check
3850 * - that this op is allowed
3851 * - that the requested role can be switched to in this context (use get_switchable_roles)
3852 * - that the requested role is NOT $CFG->defaultuserroleid
3854 * To "unswitch" pass 0 as the roleid.
3856 * This function *will* modify $USER->access - beware
3858 * @param integer $roleid the role to switch to.
3859 * @param context $context the context in which to perform the switch.
3860 * @return bool success or failure.
3862 function role_switch($roleid, context $context) {
3863 global $USER;
3866 // Plan of action
3868 // - Add the ghost RA to $USER->access
3869 // as $USER->access['rsw'][$path] = $roleid
3871 // - Make sure $USER->access['rdef'] has the roledefs
3872 // it needs to honour the switcherole
3874 // Roledefs will get loaded "deep" here - down to the last child
3875 // context. Note that
3877 // - When visiting subcontexts, our selective accessdata loading
3878 // will still work fine - though those ra/rdefs will be ignored
3879 // appropriately while the switch is in place
3881 // - If a switcherole happens at a category with tons of courses
3882 // (that have many overrides for switched-to role), the session
3883 // will get... quite large. Sometimes you just can't win.
3885 // To un-switch just unset($USER->access['rsw'][$path])
3887 // Note: it is not possible to switch to roles that do not have course:view
3889 // Add the switch RA
3890 if (!isset($USER->access['rsw'])) {
3891 $USER->access['rsw'] = array();
3894 if ($roleid == 0) {
3895 unset($USER->access['rsw'][$context->path]);
3896 if (empty($USER->access['rsw'])) {
3897 unset($USER->access['rsw']);
3899 return true;
3902 $USER->access['rsw'][$context->path] = $roleid;
3904 // Load roledefs
3905 load_role_access_by_context($roleid, $context, $USER->access);
3907 return true;
3911 * Checks if the user has switched roles within the given course.
3913 * Note: You can only switch roles within the course, hence it takes a courseid
3914 * rather than a context. On that note Petr volunteered to implement this across
3915 * all other contexts, all requests for this should be forwarded to him ;)
3917 * @param int $courseid The id of the course to check
3918 * @return bool True if the user has switched roles within the course.
3920 function is_role_switched($courseid) {
3921 global $USER;
3922 $context = context_course::instance($courseid, MUST_EXIST);
3923 return (!empty($USER->access['rsw'][$context->path]));
3927 * Get any role that has an override on exact context
3929 * @param context $context The context to check
3930 * @return array An array of roles
3932 function get_roles_with_override_on_context(context $context) {
3933 global $DB;
3935 return $DB->get_records_sql("SELECT r.*
3936 FROM {role_capabilities} rc, {role} r
3937 WHERE rc.roleid = r.id AND rc.contextid = ?",
3938 array($context->id));
3942 * Get all capabilities for this role on this context (overrides)
3944 * @param stdClass $role
3945 * @param context $context
3946 * @return array
3948 function get_capabilities_from_role_on_context($role, context $context) {
3949 global $DB;
3951 return $DB->get_records_sql("SELECT *
3952 FROM {role_capabilities}
3953 WHERE contextid = ? AND roleid = ?",
3954 array($context->id, $role->id));
3958 * Find out which roles has assignment on this context
3960 * @param context $context
3961 * @return array
3964 function get_roles_with_assignment_on_context(context $context) {
3965 global $DB;
3967 return $DB->get_records_sql("SELECT r.*
3968 FROM {role_assignments} ra, {role} r
3969 WHERE ra.roleid = r.id AND ra.contextid = ?",
3970 array($context->id));
3974 * Find all user assignment of users for this role, on this context
3976 * @param stdClass $role
3977 * @param context $context
3978 * @return array
3980 function get_users_from_role_on_context($role, context $context) {
3981 global $DB;
3983 return $DB->get_records_sql("SELECT *
3984 FROM {role_assignments}
3985 WHERE contextid = ? AND roleid = ?",
3986 array($context->id, $role->id));
3990 * Simple function returning a boolean true if user has roles
3991 * in context or parent contexts, otherwise false.
3993 * @param int $userid
3994 * @param int $roleid
3995 * @param int $contextid empty means any context
3996 * @return bool
3998 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
3999 global $DB;
4001 if ($contextid) {
4002 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4003 return false;
4005 $parents = $context->get_parent_context_ids(true);
4006 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4007 $params['userid'] = $userid;
4008 $params['roleid'] = $roleid;
4010 $sql = "SELECT COUNT(ra.id)
4011 FROM {role_assignments} ra
4012 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4014 $count = $DB->get_field_sql($sql, $params);
4015 return ($count > 0);
4017 } else {
4018 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4023 * Get role name or alias if exists and format the text.
4025 * @param stdClass $role role object
4026 * @param context_course $coursecontext
4027 * @return string name of role in course context
4029 function role_get_name($role, context_course $coursecontext) {
4030 global $DB;
4032 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4033 return strip_tags(format_string($r->name));
4034 } else {
4035 return strip_tags(format_string($role->name));
4040 * Prepare list of roles for display, apply aliases and format text
4042 * @param array $roleoptions array roleid => rolename or roleid => roleobject
4043 * @param context $context a context
4044 * @param int $rolenamedisplay
4045 * @return array Array of context-specific role names, or role objexts with a ->localname field added.
4047 function role_fix_names($roleoptions, context $context, $rolenamedisplay = ROLENAME_ALIAS) {
4048 global $DB;
4050 // Make sure we have a course context.
4051 $coursecontext = $context->get_course_context(false);
4053 // Make sure we are working with an array roleid => name. Normally we
4054 // want to use the unlocalised name if the localised one is not present.
4055 $newnames = array();
4056 foreach ($roleoptions as $rid => $roleorname) {
4057 if ($rolenamedisplay != ROLENAME_ALIAS_RAW) {
4058 if (is_object($roleorname)) {
4059 $newnames[$rid] = $roleorname->name;
4060 } else {
4061 $newnames[$rid] = $roleorname;
4063 } else {
4064 $newnames[$rid] = '';
4068 // If necessary, get the localised names.
4069 if ($rolenamedisplay != ROLENAME_ORIGINAL && !empty($coursecontext->id)) {
4070 // The get the relevant renames, and use them.
4071 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4072 foreach ($aliasnames as $alias) {
4073 if (isset($newnames[$alias->roleid])) {
4074 if ($rolenamedisplay == ROLENAME_ALIAS || $rolenamedisplay == ROLENAME_ALIAS_RAW) {
4075 $newnames[$alias->roleid] = $alias->name;
4076 } else if ($rolenamedisplay == ROLENAME_BOTH) {
4077 $newnames[$alias->roleid] = $alias->name . ' (' . $roleoptions[$alias->roleid] . ')';
4083 // Finally, apply format_string and put the result in the right place.
4084 foreach ($roleoptions as $rid => $roleorname) {
4085 if ($rolenamedisplay != ROLENAME_ALIAS_RAW) {
4086 $newnames[$rid] = strip_tags(format_string($newnames[$rid]));
4088 if (is_object($roleorname)) {
4089 $roleoptions[$rid]->localname = $newnames[$rid];
4090 } else {
4091 $roleoptions[$rid] = $newnames[$rid];
4094 return $roleoptions;
4098 * Aids in detecting if a new line is required when reading a new capability
4100 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4101 * when we read in a new capability.
4102 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4103 * but when we are in grade, all reports/import/export capabilities should be together
4105 * @param string $cap component string a
4106 * @param string $comp component string b
4107 * @param int $contextlevel
4108 * @return bool whether 2 component are in different "sections"
4110 function component_level_changed($cap, $comp, $contextlevel) {
4112 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4113 $compsa = explode('/', $cap->component);
4114 $compsb = explode('/', $comp);
4116 // list of system reports
4117 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4118 return false;
4121 // we are in gradebook, still
4122 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4123 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4124 return false;
4127 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4128 return false;
4132 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4136 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4137 * and return an array of roleids in order.
4139 * @param array $allroles array of roles, as returned by get_all_roles();
4140 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4142 function fix_role_sortorder($allroles) {
4143 global $DB;
4145 $rolesort = array();
4146 $i = 0;
4147 foreach ($allroles as $role) {
4148 $rolesort[$i] = $role->id;
4149 if ($role->sortorder != $i) {
4150 $r = new stdClass();
4151 $r->id = $role->id;
4152 $r->sortorder = $i;
4153 $DB->update_record('role', $r);
4154 $allroles[$role->id]->sortorder = $i;
4156 $i++;
4158 return $rolesort;
4162 * Switch the sort order of two roles (used in admin/roles/manage.php).
4164 * @param object $first The first role. Actually, only ->sortorder is used.
4165 * @param object $second The second role. Actually, only ->sortorder is used.
4166 * @return boolean success or failure
4168 function switch_roles($first, $second) {
4169 global $DB;
4170 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4171 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4172 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4173 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4174 return $result;
4178 * Duplicates all the base definitions of a role
4180 * @param object $sourcerole role to copy from
4181 * @param int $targetrole id of role to copy to
4183 function role_cap_duplicate($sourcerole, $targetrole) {
4184 global $DB;
4186 $systemcontext = context_system::instance();
4187 $caps = $DB->get_records_sql("SELECT *
4188 FROM {role_capabilities}
4189 WHERE roleid = ? AND contextid = ?",
4190 array($sourcerole->id, $systemcontext->id));
4191 // adding capabilities
4192 foreach ($caps as $cap) {
4193 unset($cap->id);
4194 $cap->roleid = $targetrole;
4195 $DB->insert_record('role_capabilities', $cap);
4200 * Returns two lists, this can be used to find out if user has capability.
4201 * Having any needed role and no forbidden role in this context means
4202 * user has this capability in this context.
4203 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4205 * @param object $context
4206 * @param string $capability
4207 * @return array($neededroles, $forbiddenroles)
4209 function get_roles_with_cap_in_context($context, $capability) {
4210 global $DB;
4212 $ctxids = trim($context->path, '/'); // kill leading slash
4213 $ctxids = str_replace('/', ',', $ctxids);
4215 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4216 FROM {role_capabilities} rc
4217 JOIN {context} ctx ON ctx.id = rc.contextid
4218 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4219 ORDER BY rc.roleid ASC, ctx.depth DESC";
4220 $params = array('cap'=>$capability);
4222 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4223 // no cap definitions --> no capability
4224 return array(array(), array());
4227 $forbidden = array();
4228 $needed = array();
4229 foreach($capdefs as $def) {
4230 if (isset($forbidden[$def->roleid])) {
4231 continue;
4233 if ($def->permission == CAP_PROHIBIT) {
4234 $forbidden[$def->roleid] = $def->roleid;
4235 unset($needed[$def->roleid]);
4236 continue;
4238 if (!isset($needed[$def->roleid])) {
4239 if ($def->permission == CAP_ALLOW) {
4240 $needed[$def->roleid] = true;
4241 } else if ($def->permission == CAP_PREVENT) {
4242 $needed[$def->roleid] = false;
4246 unset($capdefs);
4248 // remove all those roles not allowing
4249 foreach($needed as $key=>$value) {
4250 if (!$value) {
4251 unset($needed[$key]);
4252 } else {
4253 $needed[$key] = $key;
4257 return array($needed, $forbidden);
4261 * Returns an array of role IDs that have ALL of the the supplied capabilities
4262 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4264 * @param object $context
4265 * @param array $capabilities An array of capabilities
4266 * @return array of roles with all of the required capabilities
4268 function get_roles_with_caps_in_context($context, $capabilities) {
4269 $neededarr = array();
4270 $forbiddenarr = array();
4271 foreach($capabilities as $caprequired) {
4272 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4275 $rolesthatcanrate = array();
4276 if (!empty($neededarr)) {
4277 foreach ($neededarr as $needed) {
4278 if (empty($rolesthatcanrate)) {
4279 $rolesthatcanrate = $needed;
4280 } else {
4281 //only want roles that have all caps
4282 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4286 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4287 foreach ($forbiddenarr as $forbidden) {
4288 //remove any roles that are forbidden any of the caps
4289 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4292 return $rolesthatcanrate;
4296 * Returns an array of role names that have ALL of the the supplied capabilities
4297 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4299 * @param object $context
4300 * @param array $capabilities An array of capabilities
4301 * @return array of roles with all of the required capabilities
4303 function get_role_names_with_caps_in_context($context, $capabilities) {
4304 global $DB;
4306 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4308 $allroles = array();
4309 $roles = $DB->get_records('role', null, 'sortorder DESC');
4310 foreach ($roles as $roleid=>$role) {
4311 $allroles[$roleid] = $role->name;
4314 $rolenames = array();
4315 foreach ($rolesthatcanrate as $r) {
4316 $rolenames[$r] = $allroles[$r];
4318 $rolenames = role_fix_names($rolenames, $context);
4319 return $rolenames;
4323 * This function verifies the prohibit comes from this context
4324 * and there are no more prohibits in parent contexts.
4326 * @param int $roleid
4327 * @param context $context
4328 * @param string $capability name
4329 * @return bool
4331 function prohibit_is_removable($roleid, context $context, $capability) {
4332 global $DB;
4334 $ctxids = trim($context->path, '/'); // kill leading slash
4335 $ctxids = str_replace('/', ',', $ctxids);
4337 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4339 $sql = "SELECT ctx.id
4340 FROM {role_capabilities} rc
4341 JOIN {context} ctx ON ctx.id = rc.contextid
4342 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4343 ORDER BY ctx.depth DESC";
4345 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4346 // no prohibits == nothing to remove
4347 return true;
4350 if (count($prohibits) > 1) {
4351 // more prohibints can not be removed
4352 return false;
4355 return !empty($prohibits[$context->id]);
4359 * More user friendly role permission changing,
4360 * it should produce as few overrides as possible.
4361 * @param int $roleid
4362 * @param object $context
4363 * @param string $capname capability name
4364 * @param int $permission
4365 * @return void
4367 function role_change_permission($roleid, $context, $capname, $permission) {
4368 global $DB;
4370 if ($permission == CAP_INHERIT) {
4371 unassign_capability($capname, $roleid, $context->id);
4372 $context->mark_dirty();
4373 return;
4376 $ctxids = trim($context->path, '/'); // kill leading slash
4377 $ctxids = str_replace('/', ',', $ctxids);
4379 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4381 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4382 FROM {role_capabilities} rc
4383 JOIN {context} ctx ON ctx.id = rc.contextid
4384 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4385 ORDER BY ctx.depth DESC";
4387 if ($existing = $DB->get_records_sql($sql, $params)) {
4388 foreach($existing as $e) {
4389 if ($e->permission == CAP_PROHIBIT) {
4390 // prohibit can not be overridden, no point in changing anything
4391 return;
4394 $lowest = array_shift($existing);
4395 if ($lowest->permission == $permission) {
4396 // permission already set in this context or parent - nothing to do
4397 return;
4399 if ($existing) {
4400 $parent = array_shift($existing);
4401 if ($parent->permission == $permission) {
4402 // permission already set in parent context or parent - just unset in this context
4403 // we do this because we want as few overrides as possible for performance reasons
4404 unassign_capability($capname, $roleid, $context->id);
4405 $context->mark_dirty();
4406 return;
4410 } else {
4411 if ($permission == CAP_PREVENT) {
4412 // nothing means role does not have permission
4413 return;
4417 // assign the needed capability
4418 assign_capability($capname, $permission, $roleid, $context->id, true);
4420 // force cap reloading
4421 $context->mark_dirty();
4426 * Basic moodle context abstraction class.
4428 * @author Petr Skoda
4429 * @since 2.2
4431 * @property-read int $id context id
4432 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4433 * @property-read int $instanceid id of related instance in each context
4434 * @property-read string $path path to context, starts with system context
4435 * @property-read dept $depth
4437 abstract class context extends stdClass {
4440 * Google confirms that no other important framework is using "context" class,
4441 * we could use something else like mcontext or moodle_context, but we need to type
4442 * this very often which would be annoying and it would take too much space...
4444 * This class is derived from stdClass for backwards compatibility with
4445 * odl $context record that was returned from DML $DB->get_record()
4448 protected $_id;
4449 protected $_contextlevel;
4450 protected $_instanceid;
4451 protected $_path;
4452 protected $_depth;
4454 /* context caching info */
4456 private static $cache_contextsbyid = array();
4457 private static $cache_contexts = array();
4458 protected static $cache_count = 0; // why do we do count contexts? Because count($array) is horribly slow for large arrays
4460 protected static $cache_preloaded = array();
4461 protected static $systemcontext = null;
4464 * Resets the cache to remove all data.
4465 * @static
4467 protected static function reset_caches() {
4468 self::$cache_contextsbyid = array();
4469 self::$cache_contexts = array();
4470 self::$cache_count = 0;
4471 self::$cache_preloaded = array();
4473 self::$systemcontext = null;
4477 * Adds a context to the cache. If the cache is full, discards a batch of
4478 * older entries.
4480 * @static
4481 * @param context $context New context to add
4482 * @return void
4484 protected static function cache_add(context $context) {
4485 if (isset(self::$cache_contextsbyid[$context->id])) {
4486 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4487 return;
4490 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4491 $i = 0;
4492 foreach(self::$cache_contextsbyid as $ctx) {
4493 $i++;
4494 if ($i <= 100) {
4495 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4496 continue;
4498 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4499 // we remove oldest third of the contexts to make room for more contexts
4500 break;
4502 unset(self::$cache_contextsbyid[$ctx->id]);
4503 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4504 self::$cache_count--;
4508 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4509 self::$cache_contextsbyid[$context->id] = $context;
4510 self::$cache_count++;
4514 * Removes a context from the cache.
4516 * @static
4517 * @param context $context Context object to remove
4518 * @return void
4520 protected static function cache_remove(context $context) {
4521 if (!isset(self::$cache_contextsbyid[$context->id])) {
4522 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4523 return;
4525 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4526 unset(self::$cache_contextsbyid[$context->id]);
4528 self::$cache_count--;
4530 if (self::$cache_count < 0) {
4531 self::$cache_count = 0;
4536 * Gets a context from the cache.
4538 * @static
4539 * @param int $contextlevel Context level
4540 * @param int $instance Instance ID
4541 * @return context|bool Context or false if not in cache
4543 protected static function cache_get($contextlevel, $instance) {
4544 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4545 return self::$cache_contexts[$contextlevel][$instance];
4547 return false;
4551 * Gets a context from the cache based on its id.
4553 * @static
4554 * @param int $id Context ID
4555 * @return context|bool Context or false if not in cache
4557 protected static function cache_get_by_id($id) {
4558 if (isset(self::$cache_contextsbyid[$id])) {
4559 return self::$cache_contextsbyid[$id];
4561 return false;
4565 * Preloads context information from db record and strips the cached info.
4567 * @static
4568 * @param stdClass $rec
4569 * @return void (modifies $rec)
4571 protected static function preload_from_record(stdClass $rec) {
4572 if (empty($rec->ctxid) or empty($rec->ctxlevel) or empty($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4573 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4574 return;
4577 // note: in PHP5 the objects are passed by reference, no need to return $rec
4578 $record = new stdClass();
4579 $record->id = $rec->ctxid; unset($rec->ctxid);
4580 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4581 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4582 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4583 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4585 return context::create_instance_from_record($record);
4589 // ====== magic methods =======
4592 * Magic setter method, we do not want anybody to modify properties from the outside
4593 * @param string $name
4594 * @param mixed @value
4596 public function __set($name, $value) {
4597 debugging('Can not change context instance properties!');
4601 * Magic method getter, redirects to read only values.
4602 * @param string $name
4603 * @return mixed
4605 public function __get($name) {
4606 switch ($name) {
4607 case 'id': return $this->_id;
4608 case 'contextlevel': return $this->_contextlevel;
4609 case 'instanceid': return $this->_instanceid;
4610 case 'path': return $this->_path;
4611 case 'depth': return $this->_depth;
4613 default:
4614 debugging('Invalid context property accessed! '.$name);
4615 return null;
4620 * Full support for isset on our magic read only properties.
4621 * @param $name
4622 * @return bool
4624 public function __isset($name) {
4625 switch ($name) {
4626 case 'id': return isset($this->_id);
4627 case 'contextlevel': return isset($this->_contextlevel);
4628 case 'instanceid': return isset($this->_instanceid);
4629 case 'path': return isset($this->_path);
4630 case 'depth': return isset($this->_depth);
4632 default: return false;
4638 * ALl properties are read only, sorry.
4639 * @param string $name
4641 public function __unset($name) {
4642 debugging('Can not unset context instance properties!');
4645 // ====== general context methods ======
4648 * Constructor is protected so that devs are forced to
4649 * use context_xxx::instance() or context::instance_by_id().
4651 * @param stdClass $record
4653 protected function __construct(stdClass $record) {
4654 $this->_id = $record->id;
4655 $this->_contextlevel = (int)$record->contextlevel;
4656 $this->_instanceid = $record->instanceid;
4657 $this->_path = $record->path;
4658 $this->_depth = $record->depth;
4662 * This function is also used to work around 'protected' keyword problems in context_helper.
4663 * @static
4664 * @param stdClass $record
4665 * @return context instance
4667 protected static function create_instance_from_record(stdClass $record) {
4668 $classname = context_helper::get_class_for_level($record->contextlevel);
4670 if ($context = context::cache_get_by_id($record->id)) {
4671 return $context;
4674 $context = new $classname($record);
4675 context::cache_add($context);
4677 return $context;
4681 * Copy prepared new contexts from temp table to context table,
4682 * we do this in db specific way for perf reasons only.
4683 * @static
4685 protected static function merge_context_temp_table() {
4686 global $DB;
4688 /* MDL-11347:
4689 * - mysql does not allow to use FROM in UPDATE statements
4690 * - using two tables after UPDATE works in mysql, but might give unexpected
4691 * results in pg 8 (depends on configuration)
4692 * - using table alias in UPDATE does not work in pg < 8.2
4694 * Different code for each database - mostly for performance reasons
4697 $dbfamily = $DB->get_dbfamily();
4698 if ($dbfamily == 'mysql') {
4699 $updatesql = "UPDATE {context} ct, {context_temp} temp
4700 SET ct.path = temp.path,
4701 ct.depth = temp.depth
4702 WHERE ct.id = temp.id";
4703 } else if ($dbfamily == 'oracle') {
4704 $updatesql = "UPDATE {context} ct
4705 SET (ct.path, ct.depth) =
4706 (SELECT temp.path, temp.depth
4707 FROM {context_temp} temp
4708 WHERE temp.id=ct.id)
4709 WHERE EXISTS (SELECT 'x'
4710 FROM {context_temp} temp
4711 WHERE temp.id = ct.id)";
4712 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
4713 $updatesql = "UPDATE {context}
4714 SET path = temp.path,
4715 depth = temp.depth
4716 FROM {context_temp} temp
4717 WHERE temp.id={context}.id";
4718 } else {
4719 // sqlite and others
4720 $updatesql = "UPDATE {context}
4721 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
4722 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
4723 WHERE id IN (SELECT id FROM {context_temp})";
4726 $DB->execute($updatesql);
4730 * Get a context instance as an object, from a given context id.
4732 * @static
4733 * @param int $id context id
4734 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
4735 * MUST_EXIST means throw exception if no record found
4736 * @return context|bool the context object or false if not found
4738 public static function instance_by_id($id, $strictness = MUST_EXIST) {
4739 global $DB;
4741 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
4742 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
4743 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
4746 if ($id == SYSCONTEXTID) {
4747 return context_system::instance(0, $strictness);
4750 if (is_array($id) or is_object($id) or empty($id)) {
4751 throw new coding_exception('Invalid context id specified context::instance_by_id()');
4754 if ($context = context::cache_get_by_id($id)) {
4755 return $context;
4758 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
4759 return context::create_instance_from_record($record);
4762 return false;
4766 * Update context info after moving context in the tree structure.
4768 * @param context $newparent
4769 * @return void
4771 public function update_moved(context $newparent) {
4772 global $DB;
4774 $frompath = $this->_path;
4775 $newpath = $newparent->path . '/' . $this->_id;
4777 $trans = $DB->start_delegated_transaction();
4779 $this->mark_dirty();
4781 $setdepth = '';
4782 if (($newparent->depth +1) != $this->_depth) {
4783 $diff = $newparent->depth - $this->_depth + 1;
4784 $setdepth = ", depth = depth + $diff";
4786 $sql = "UPDATE {context}
4787 SET path = ?
4788 $setdepth
4789 WHERE id = ?";
4790 $params = array($newpath, $this->_id);
4791 $DB->execute($sql, $params);
4793 $this->_path = $newpath;
4794 $this->_depth = $newparent->depth + 1;
4796 $sql = "UPDATE {context}
4797 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
4798 $setdepth
4799 WHERE path LIKE ?";
4800 $params = array($newpath, "{$frompath}/%");
4801 $DB->execute($sql, $params);
4803 $this->mark_dirty();
4805 context::reset_caches();
4807 $trans->allow_commit();
4811 * Remove all context path info and optionally rebuild it.
4813 * @param bool $rebuild
4814 * @return void
4816 public function reset_paths($rebuild = true) {
4817 global $DB;
4819 if ($this->_path) {
4820 $this->mark_dirty();
4822 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
4823 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
4824 if ($this->_contextlevel != CONTEXT_SYSTEM) {
4825 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
4826 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
4827 $this->_depth = 0;
4828 $this->_path = null;
4831 if ($rebuild) {
4832 context_helper::build_all_paths(false);
4835 context::reset_caches();
4839 * Delete all data linked to content, do not delete the context record itself
4841 public function delete_content() {
4842 global $CFG, $DB;
4844 blocks_delete_all_for_context($this->_id);
4845 filter_delete_all_for_context($this->_id);
4847 require_once($CFG->dirroot . '/comment/lib.php');
4848 comment::delete_comments(array('contextid'=>$this->_id));
4850 require_once($CFG->dirroot.'/rating/lib.php');
4851 $delopt = new stdclass();
4852 $delopt->contextid = $this->_id;
4853 $rm = new rating_manager();
4854 $rm->delete_ratings($delopt);
4856 // delete all files attached to this context
4857 $fs = get_file_storage();
4858 $fs->delete_area_files($this->_id);
4860 // now delete stuff from role related tables, role_unassign_all
4861 // and unenrol should be called earlier to do proper cleanup
4862 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
4863 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
4864 $DB->delete_records('role_names', array('contextid'=>$this->_id));
4868 * Delete the context content and the context record itself
4870 public function delete() {
4871 global $DB;
4873 // double check the context still exists
4874 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
4875 context::cache_remove($this);
4876 return;
4879 $this->delete_content();
4880 $DB->delete_records('context', array('id'=>$this->_id));
4881 // purge static context cache if entry present
4882 context::cache_remove($this);
4884 // do not mark dirty contexts if parents unknown
4885 if (!is_null($this->_path) and $this->_depth > 0) {
4886 $this->mark_dirty();
4890 // ====== context level related methods ======
4893 * Utility method for context creation
4895 * @static
4896 * @param int $contextlevel
4897 * @param int $instanceid
4898 * @param string $parentpath
4899 * @return stdClass context record
4901 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
4902 global $DB;
4904 $record = new stdClass();
4905 $record->contextlevel = $contextlevel;
4906 $record->instanceid = $instanceid;
4907 $record->depth = 0;
4908 $record->path = null; //not known before insert
4910 $record->id = $DB->insert_record('context', $record);
4912 // now add path if known - it can be added later
4913 if (!is_null($parentpath)) {
4914 $record->path = $parentpath.'/'.$record->id;
4915 $record->depth = substr_count($record->path, '/');
4916 $DB->update_record('context', $record);
4919 return $record;
4923 * Returns human readable context level name.
4925 * @static
4926 * @return string the human readable context level name.
4928 protected static function get_level_name() {
4929 // must be implemented in all context levels
4930 throw new coding_exception('can not get level name of abstract context');
4934 * Returns human readable context identifier.
4936 * @param boolean $withprefix whether to prefix the name of the context with the
4937 * type of context, e.g. User, Course, Forum, etc.
4938 * @param boolean $short whether to use the short name of the thing. Only applies
4939 * to course contexts
4940 * @return string the human readable context name.
4942 public function get_context_name($withprefix = true, $short = false) {
4943 // must be implemented in all context levels
4944 throw new coding_exception('can not get name of abstract context');
4948 * Returns the most relevant URL for this context.
4950 * @return moodle_url
4952 public abstract function get_url();
4955 * Returns array of relevant context capability records.
4957 * @return array
4959 public abstract function get_capabilities();
4962 * Recursive function which, given a context, find all its children context ids.
4964 * For course category contexts it will return immediate children and all subcategory contexts.
4965 * It will NOT recurse into courses or subcategories categories.
4966 * If you want to do that, call it on the returned courses/categories.
4968 * When called for a course context, it will return the modules and blocks
4969 * displayed in the course page and blocks displayed on the module pages.
4971 * If called on a user/course/module context it _will_ populate the cache with the appropriate
4972 * contexts ;-)
4974 * @return array Array of child records
4976 public function get_child_contexts() {
4977 global $DB;
4979 $sql = "SELECT ctx.*
4980 FROM {context} ctx
4981 WHERE ctx.path LIKE ?";
4982 $params = array($this->_path.'/%');
4983 $records = $DB->get_records_sql($sql, $params);
4985 $result = array();
4986 foreach ($records as $record) {
4987 $result[$record->id] = context::create_instance_from_record($record);
4990 return $result;
4994 * Returns parent contexts of this context in reversed order, i.e. parent first,
4995 * then grand parent, etc.
4997 * @param bool $includeself tre means include self too
4998 * @return array of context instances
5000 public function get_parent_contexts($includeself = false) {
5001 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5002 return array();
5005 $result = array();
5006 foreach ($contextids as $contextid) {
5007 $parent = context::instance_by_id($contextid, MUST_EXIST);
5008 $result[$parent->id] = $parent;
5011 return $result;
5015 * Returns parent contexts of this context in reversed order, i.e. parent first,
5016 * then grand parent, etc.
5018 * @param bool $includeself tre means include self too
5019 * @return array of context ids
5021 public function get_parent_context_ids($includeself = false) {
5022 if (empty($this->_path)) {
5023 return array();
5026 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5027 $parentcontexts = explode('/', $parentcontexts);
5028 if (!$includeself) {
5029 array_pop($parentcontexts); // and remove its own id
5032 return array_reverse($parentcontexts);
5036 * Returns parent context
5038 * @return context
5040 public function get_parent_context() {
5041 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5042 return false;
5045 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5046 $parentcontexts = explode('/', $parentcontexts);
5047 array_pop($parentcontexts); // self
5048 $contextid = array_pop($parentcontexts); // immediate parent
5050 return context::instance_by_id($contextid, MUST_EXIST);
5054 * Is this context part of any course? If yes return course context.
5056 * @param bool $strict true means throw exception if not found, false means return false if not found
5057 * @return course_context context of the enclosing course, null if not found or exception
5059 public function get_course_context($strict = true) {
5060 if ($strict) {
5061 throw new coding_exception('Context does not belong to any course.');
5062 } else {
5063 return false;
5068 * Returns sql necessary for purging of stale context instances.
5070 * @static
5071 * @return string cleanup SQL
5073 protected static function get_cleanup_sql() {
5074 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5078 * Rebuild context paths and depths at context level.
5080 * @static
5081 * @param $force
5082 * @return void
5084 protected static function build_paths($force) {
5085 throw new coding_exception('build_paths() method must be implemented in all context levels');
5089 * Create missing context instances at given level
5091 * @static
5092 * @return void
5094 protected static function create_level_instances() {
5095 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5099 * Reset all cached permissions and definitions if the necessary.
5100 * @return void
5102 public function reload_if_dirty() {
5103 global $ACCESSLIB_PRIVATE, $USER;
5105 // Load dirty contexts list if needed
5106 if (CLI_SCRIPT) {
5107 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5108 // we do not load dirty flags in CLI and cron
5109 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5111 } else {
5112 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5113 if (!isset($USER->access['time'])) {
5114 // nothing was loaded yet, we do not need to check dirty contexts now
5115 return;
5117 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5118 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5122 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5123 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5124 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5125 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5126 reload_all_capabilities();
5127 break;
5133 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5135 public function mark_dirty() {
5136 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5138 if (during_initial_install()) {
5139 return;
5142 // only if it is a non-empty string
5143 if (is_string($this->_path) && $this->_path !== '') {
5144 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5145 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5146 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5147 } else {
5148 if (CLI_SCRIPT) {
5149 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5150 } else {
5151 if (isset($USER->access['time'])) {
5152 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5153 } else {
5154 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5156 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5165 * Context maintenance and helper methods.
5167 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5168 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5169 * level implementation from the rest of code, the code completion returns what developers need.
5171 * Thank you Tim Hunt for helping me with this nasty trick.
5173 * @author Petr Skoda
5174 * @since 2.2
5176 class context_helper extends context {
5178 private static $alllevels = array(
5179 CONTEXT_SYSTEM => 'context_system',
5180 CONTEXT_USER => 'context_user',
5181 CONTEXT_COURSECAT => 'context_coursecat',
5182 CONTEXT_COURSE => 'context_course',
5183 CONTEXT_MODULE => 'context_module',
5184 CONTEXT_BLOCK => 'context_block',
5188 * Instance does not make sense here, only static use
5190 protected function __construct() {
5194 * Returns a class name of the context level class
5196 * @static
5197 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5198 * @return string class name of the context class
5200 public static function get_class_for_level($contextlevel) {
5201 if (isset(self::$alllevels[$contextlevel])) {
5202 return self::$alllevels[$contextlevel];
5203 } else {
5204 throw new coding_exception('Invalid context level specified');
5209 * Returns a list of all context levels
5211 * @static
5212 * @return array int=>string (level=>level class name)
5214 public static function get_all_levels() {
5215 return self::$alllevels;
5219 * Remove stale contexts that belonged to deleted instances.
5220 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5222 * @static
5223 * @return void
5225 public static function cleanup_instances() {
5226 global $DB;
5227 $sqls = array();
5228 foreach (self::$alllevels as $level=>$classname) {
5229 $sqls[] = $classname::get_cleanup_sql();
5232 $sql = implode(" UNION ", $sqls);
5234 // it is probably better to use transactions, it might be faster too
5235 $transaction = $DB->start_delegated_transaction();
5237 $rs = $DB->get_recordset_sql($sql);
5238 foreach ($rs as $record) {
5239 $context = context::create_instance_from_record($record);
5240 $context->delete();
5242 $rs->close();
5244 $transaction->allow_commit();
5248 * Create all context instances at the given level and above.
5250 * @static
5251 * @param int $contextlevel null means all levels
5252 * @param bool $buildpaths
5253 * @return void
5255 public static function create_instances($contextlevel = null, $buildpaths = true) {
5256 foreach (self::$alllevels as $level=>$classname) {
5257 if ($contextlevel and $level > $contextlevel) {
5258 // skip potential sub-contexts
5259 continue;
5261 $classname::create_level_instances();
5262 if ($buildpaths) {
5263 $classname::build_paths(false);
5269 * Rebuild paths and depths in all context levels.
5271 * @static
5272 * @param bool $force false means add missing only
5273 * @return void
5275 public static function build_all_paths($force = false) {
5276 foreach (self::$alllevels as $classname) {
5277 $classname::build_paths($force);
5280 // reset static course cache - it might have incorrect cached data
5281 accesslib_clear_all_caches(true);
5285 * Resets the cache to remove all data.
5286 * @static
5288 public static function reset_caches() {
5289 context::reset_caches();
5293 * Returns all fields necessary for context preloading from user $rec.
5295 * This helps with performance when dealing with hundreds of contexts.
5297 * @static
5298 * @param string $tablealias context table alias in the query
5299 * @return array (table.column=>alias, ...)
5301 public static function get_preload_record_columns($tablealias) {
5302 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5306 * Returns all fields necessary for context preloading from user $rec.
5308 * This helps with performance when dealing with hundreds of contexts.
5310 * @static
5311 * @param string $tablealias context table alias in the query
5312 * @return string
5314 public static function get_preload_record_columns_sql($tablealias) {
5315 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5319 * Preloads context information from db record and strips the cached info.
5321 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5323 * @static
5324 * @param stdClass $rec
5325 * @return void (modifies $rec)
5327 public static function preload_from_record(stdClass $rec) {
5328 context::preload_from_record($rec);
5332 * Preload all contexts instances from course.
5334 * To be used if you expect multiple queries for course activities...
5336 * @static
5337 * @param $courseid
5339 public static function preload_course($courseid) {
5340 // Users can call this multiple times without doing any harm
5341 if (isset(context::$cache_preloaded[$courseid])) {
5342 return;
5344 $coursecontext = context_course::instance($courseid);
5345 $coursecontext->get_child_contexts();
5347 context::$cache_preloaded[$courseid] = true;
5351 * Delete context instance
5353 * @static
5354 * @param int $contextlevel
5355 * @param int $instanceid
5356 * @return void
5358 public static function delete_instance($contextlevel, $instanceid) {
5359 global $DB;
5361 // double check the context still exists
5362 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5363 $context = context::create_instance_from_record($record);
5364 $context->delete();
5365 } else {
5366 // we should try to purge the cache anyway
5371 * Returns the name of specified context level
5373 * @static
5374 * @param int $contextlevel
5375 * @return string name of the context level
5377 public static function get_level_name($contextlevel) {
5378 $classname = context_helper::get_class_for_level($contextlevel);
5379 return $classname::get_level_name();
5383 * not used
5385 public function get_url() {
5389 * not used
5391 public function get_capabilities() {
5397 * Basic context class
5398 * @author Petr Skoda (http://skodak.org)
5399 * @since 2.2
5401 class context_system extends context {
5403 * Please use context_system::instance() if you need the instance of context.
5405 * @param stdClass $record
5407 protected function __construct(stdClass $record) {
5408 parent::__construct($record);
5409 if ($record->contextlevel != CONTEXT_SYSTEM) {
5410 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5415 * Returns human readable context level name.
5417 * @static
5418 * @return string the human readable context level name.
5420 protected static function get_level_name() {
5421 return get_string('coresystem');
5425 * Returns human readable context identifier.
5427 * @param boolean $withprefix does not apply to system context
5428 * @param boolean $short does not apply to system context
5429 * @return string the human readable context name.
5431 public function get_context_name($withprefix = true, $short = false) {
5432 return self::get_level_name();
5436 * Returns the most relevant URL for this context.
5438 * @return moodle_url
5440 public function get_url() {
5441 return new moodle_url('/');
5445 * Returns array of relevant context capability records.
5447 * @return array
5449 public function get_capabilities() {
5450 global $DB;
5452 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5454 $params = array();
5455 $sql = "SELECT *
5456 FROM {capabilities}";
5458 return $DB->get_records_sql($sql.' '.$sort, $params);
5462 * Create missing context instances at system context
5463 * @static
5465 protected static function create_level_instances() {
5466 // nothing to do here, the system context is created automatically in installer
5467 self::instance(0);
5471 * Returns system context instance.
5473 * @static
5474 * @param int $instanceid
5475 * @param int $strictness
5476 * @param bool $cache
5477 * @return context_system context instance
5479 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5480 global $DB;
5482 if ($instanceid != 0) {
5483 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5486 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5487 if (!isset(context::$systemcontext)) {
5488 $record = new stdClass();
5489 $record->id = SYSCONTEXTID;
5490 $record->contextlevel = CONTEXT_SYSTEM;
5491 $record->instanceid = 0;
5492 $record->path = '/'.SYSCONTEXTID;
5493 $record->depth = 1;
5494 context::$systemcontext = new context_system($record);
5496 return context::$systemcontext;
5500 try {
5501 // we ignore the strictness completely because system context must except except during install
5502 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5503 } catch (dml_exception $e) {
5504 //table or record does not exist
5505 if (!during_initial_install()) {
5506 // do not mess with system context after install, it simply must exist
5507 throw $e;
5509 $record = null;
5512 if (!$record) {
5513 $record = new stdClass();
5514 $record->contextlevel = CONTEXT_SYSTEM;
5515 $record->instanceid = 0;
5516 $record->depth = 1;
5517 $record->path = null; //not known before insert
5519 try {
5520 if ($DB->count_records('context')) {
5521 // contexts already exist, this is very weird, system must be first!!!
5522 return null;
5524 if (defined('SYSCONTEXTID')) {
5525 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5526 $record->id = SYSCONTEXTID;
5527 $DB->import_record('context', $record);
5528 $DB->get_manager()->reset_sequence('context');
5529 } else {
5530 $record->id = $DB->insert_record('context', $record);
5532 } catch (dml_exception $e) {
5533 // can not create context - table does not exist yet, sorry
5534 return null;
5538 if ($record->instanceid != 0) {
5539 // this is very weird, somebody must be messing with context table
5540 debugging('Invalid system context detected');
5543 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5544 // fix path if necessary, initial install or path reset
5545 $record->depth = 1;
5546 $record->path = '/'.$record->id;
5547 $DB->update_record('context', $record);
5550 if (!defined('SYSCONTEXTID')) {
5551 define('SYSCONTEXTID', $record->id);
5554 context::$systemcontext = new context_system($record);
5555 return context::$systemcontext;
5559 * Returns all site contexts except the system context, DO NOT call on production servers!!
5561 * Contexts are not cached.
5563 * @return array
5565 public function get_child_contexts() {
5566 global $DB;
5568 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5570 // Just get all the contexts except for CONTEXT_SYSTEM level
5571 // and hope we don't OOM in the process - don't cache
5572 $sql = "SELECT c.*
5573 FROM {context} c
5574 WHERE contextlevel > ".CONTEXT_SYSTEM;
5575 $records = $DB->get_records_sql($sql);
5577 $result = array();
5578 foreach ($records as $record) {
5579 $result[$record->id] = context::create_instance_from_record($record);
5582 return $result;
5586 * Returns sql necessary for purging of stale context instances.
5588 * @static
5589 * @return string cleanup SQL
5591 protected static function get_cleanup_sql() {
5592 $sql = "
5593 SELECT c.*
5594 FROM {context} c
5595 WHERE 1=2
5598 return $sql;
5602 * Rebuild context paths and depths at system context level.
5604 * @static
5605 * @param $force
5607 protected static function build_paths($force) {
5608 global $DB;
5610 /* note: ignore $force here, we always do full test of system context */
5612 // exactly one record must exist
5613 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5615 if ($record->instanceid != 0) {
5616 debugging('Invalid system context detected');
5619 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
5620 debugging('Invalid SYSCONTEXTID detected');
5623 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5624 // fix path if necessary, initial install or path reset
5625 $record->depth = 1;
5626 $record->path = '/'.$record->id;
5627 $DB->update_record('context', $record);
5634 * User context class
5635 * @author Petr Skoda (http://skodak.org)
5636 * @since 2.2
5638 class context_user extends context {
5640 * Please use context_user::instance($userid) if you need the instance of context.
5641 * Alternatively if you know only the context id use context::instance_by_id($contextid)
5643 * @param stdClass $record
5645 protected function __construct(stdClass $record) {
5646 parent::__construct($record);
5647 if ($record->contextlevel != CONTEXT_USER) {
5648 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
5653 * Returns human readable context level name.
5655 * @static
5656 * @return string the human readable context level name.
5658 protected static function get_level_name() {
5659 return get_string('user');
5663 * Returns human readable context identifier.
5665 * @param boolean $withprefix whether to prefix the name of the context with User
5666 * @param boolean $short does not apply to user context
5667 * @return string the human readable context name.
5669 public function get_context_name($withprefix = true, $short = false) {
5670 global $DB;
5672 $name = '';
5673 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
5674 if ($withprefix){
5675 $name = get_string('user').': ';
5677 $name .= fullname($user);
5679 return $name;
5683 * Returns the most relevant URL for this context.
5685 * @return moodle_url
5687 public function get_url() {
5688 global $COURSE;
5690 if ($COURSE->id == SITEID) {
5691 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
5692 } else {
5693 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
5695 return $url;
5699 * Returns array of relevant context capability records.
5701 * @return array
5703 public function get_capabilities() {
5704 global $DB;
5706 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5708 $extracaps = array('moodle/grade:viewall');
5709 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
5710 $sql = "SELECT *
5711 FROM {capabilities}
5712 WHERE contextlevel = ".CONTEXT_USER."
5713 OR name $extra";
5715 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
5719 * Returns user context instance.
5721 * @static
5722 * @param int $instanceid
5723 * @param int $strictness
5724 * @return context_user context instance
5726 public static function instance($instanceid, $strictness = MUST_EXIST) {
5727 global $DB;
5729 if ($context = context::cache_get(CONTEXT_USER, $instanceid)) {
5730 return $context;
5733 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER, 'instanceid'=>$instanceid))) {
5734 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
5735 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
5739 if ($record) {
5740 $context = new context_user($record);
5741 context::cache_add($context);
5742 return $context;
5745 return false;
5749 * Create missing context instances at user context level
5750 * @static
5752 protected static function create_level_instances() {
5753 global $DB;
5755 $sql = "INSERT INTO {context} (contextlevel, instanceid)
5756 SELECT ".CONTEXT_USER.", u.id
5757 FROM {user} u
5758 WHERE u.deleted = 0
5759 AND NOT EXISTS (SELECT 'x'
5760 FROM {context} cx
5761 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
5762 $DB->execute($sql);
5766 * Returns sql necessary for purging of stale context instances.
5768 * @static
5769 * @return string cleanup SQL
5771 protected static function get_cleanup_sql() {
5772 $sql = "
5773 SELECT c.*
5774 FROM {context} c
5775 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
5776 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
5779 return $sql;
5783 * Rebuild context paths and depths at user context level.
5785 * @static
5786 * @param $force
5788 protected static function build_paths($force) {
5789 global $DB;
5791 // first update normal users
5792 $sql = "UPDATE {context}
5793 SET depth = 2,
5794 path = ".$DB->sql_concat("'/".SYSCONTEXTID."/'", 'id')."
5795 WHERE contextlevel=".CONTEXT_USER;
5796 $DB->execute($sql);
5802 * Course category context class
5803 * @author Petr Skoda (http://skodak.org)
5804 * @since 2.2
5806 class context_coursecat extends context {
5808 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
5809 * Alternatively if you know only the context id use context::instance_by_id($contextid)
5811 * @param stdClass $record
5813 protected function __construct(stdClass $record) {
5814 parent::__construct($record);
5815 if ($record->contextlevel != CONTEXT_COURSECAT) {
5816 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
5821 * Returns human readable context level name.
5823 * @static
5824 * @return string the human readable context level name.
5826 protected static function get_level_name() {
5827 return get_string('category');
5831 * Returns human readable context identifier.
5833 * @param boolean $withprefix whether to prefix the name of the context with Category
5834 * @param boolean $short does not apply to course categories
5835 * @return string the human readable context name.
5837 public function get_context_name($withprefix = true, $short = false) {
5838 global $DB;
5840 $name = '';
5841 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
5842 if ($withprefix){
5843 $name = get_string('category').': ';
5845 $name .= format_string($category->name, true, array('context' => $this));
5847 return $name;
5851 * Returns the most relevant URL for this context.
5853 * @return moodle_url
5855 public function get_url() {
5856 return new moodle_url('/course/category.php', array('id'=>$this->_instanceid));
5860 * Returns array of relevant context capability records.
5862 * @return array
5864 public function get_capabilities() {
5865 global $DB;
5867 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5869 $params = array();
5870 $sql = "SELECT *
5871 FROM {capabilities}
5872 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
5874 return $DB->get_records_sql($sql.' '.$sort, $params);
5878 * Returns course category context instance.
5880 * @static
5881 * @param int $instanceid
5882 * @param int $strictness
5883 * @return context_coursecat context instance
5885 public static function instance($instanceid, $strictness = MUST_EXIST) {
5886 global $DB;
5888 if ($context = context::cache_get(CONTEXT_COURSECAT, $instanceid)) {
5889 return $context;
5892 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT, 'instanceid'=>$instanceid))) {
5893 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
5894 if ($category->parent) {
5895 $parentcontext = context_coursecat::instance($category->parent);
5896 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
5897 } else {
5898 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
5903 if ($record) {
5904 $context = new context_coursecat($record);
5905 context::cache_add($context);
5906 return $context;
5909 return false;
5913 * Returns immediate child contexts of category and all subcategories,
5914 * children of subcategories and courses are not returned.
5916 * @return array
5918 public function get_child_contexts() {
5919 global $DB;
5921 $sql = "SELECT ctx.*
5922 FROM {context} ctx
5923 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
5924 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
5925 $records = $DB->get_records_sql($sql, $params);
5927 $result = array();
5928 foreach ($records as $record) {
5929 $result[$record->id] = context::create_instance_from_record($record);
5932 return $result;
5936 * Create missing context instances at course category context level
5937 * @static
5939 protected static function create_level_instances() {
5940 global $DB;
5942 $sql = "INSERT INTO {context} (contextlevel, instanceid)
5943 SELECT ".CONTEXT_COURSECAT.", cc.id
5944 FROM {course_categories} cc
5945 WHERE NOT EXISTS (SELECT 'x'
5946 FROM {context} cx
5947 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
5948 $DB->execute($sql);
5952 * Returns sql necessary for purging of stale context instances.
5954 * @static
5955 * @return string cleanup SQL
5957 protected static function get_cleanup_sql() {
5958 $sql = "
5959 SELECT c.*
5960 FROM {context} c
5961 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
5962 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
5965 return $sql;
5969 * Rebuild context paths and depths at course category context level.
5971 * @static
5972 * @param $force
5974 protected static function build_paths($force) {
5975 global $DB;
5977 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
5978 if ($force) {
5979 $ctxemptyclause = $emptyclause = '';
5980 } else {
5981 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
5982 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
5985 $base = '/'.SYSCONTEXTID;
5987 // Normal top level categories
5988 $sql = "UPDATE {context}
5989 SET depth=2,
5990 path=".$DB->sql_concat("'$base/'", 'id')."
5991 WHERE contextlevel=".CONTEXT_COURSECAT."
5992 AND EXISTS (SELECT 'x'
5993 FROM {course_categories} cc
5994 WHERE cc.id = {context}.instanceid AND cc.depth=1)
5995 $emptyclause";
5996 $DB->execute($sql);
5998 // Deeper categories - one query per depthlevel
5999 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6000 for ($n=2; $n<=$maxdepth; $n++) {
6001 $sql = "INSERT INTO {context_temp} (id, path, depth)
6002 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6003 FROM {context} ctx
6004 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6005 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6006 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6007 $ctxemptyclause";
6008 $trans = $DB->start_delegated_transaction();
6009 $DB->delete_records('context_temp');
6010 $DB->execute($sql);
6011 context::merge_context_temp_table();
6012 $DB->delete_records('context_temp');
6013 $trans->allow_commit();
6022 * Course context class
6023 * @author Petr Skoda (http://skodak.org)
6024 * @since 2.2
6026 class context_course extends context {
6028 * Please use context_course::instance($courseid) if you need the instance of context.
6029 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6031 * @param stdClass $record
6033 protected function __construct(stdClass $record) {
6034 parent::__construct($record);
6035 if ($record->contextlevel != CONTEXT_COURSE) {
6036 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6041 * Returns human readable context level name.
6043 * @static
6044 * @return string the human readable context level name.
6046 protected static function get_level_name() {
6047 return get_string('course');
6051 * Returns human readable context identifier.
6053 * @param boolean $withprefix whether to prefix the name of the context with Course
6054 * @param boolean $short whether to use the short name of the thing.
6055 * @return string the human readable context name.
6057 public function get_context_name($withprefix = true, $short = false) {
6058 global $DB;
6060 $name = '';
6061 if ($this->_instanceid == SITEID) {
6062 $name = get_string('frontpage', 'admin');
6063 } else {
6064 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6065 if ($withprefix){
6066 $name = get_string('course').': ';
6068 if ($short){
6069 $name .= format_string($course->shortname, true, array('context' => $this));
6070 } else {
6071 $name .= format_string($course->fullname);
6075 return $name;
6079 * Returns the most relevant URL for this context.
6081 * @return moodle_url
6083 public function get_url() {
6084 if ($this->_instanceid != SITEID) {
6085 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6088 return new moodle_url('/');
6092 * Returns array of relevant context capability records.
6094 * @return array
6096 public function get_capabilities() {
6097 global $DB;
6099 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6101 $params = array();
6102 $sql = "SELECT *
6103 FROM {capabilities}
6104 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6106 return $DB->get_records_sql($sql.' '.$sort, $params);
6110 * Is this context part of any course? If yes return course context.
6112 * @param bool $strict true means throw exception if not found, false means return false if not found
6113 * @return course_context context of the enclosing course, null if not found or exception
6115 public function get_course_context($strict = true) {
6116 return $this;
6120 * Returns course context instance.
6122 * @static
6123 * @param int $instanceid
6124 * @param int $strictness
6125 * @return context_course context instance
6127 public static function instance($instanceid, $strictness = MUST_EXIST) {
6128 global $DB;
6130 if ($context = context::cache_get(CONTEXT_COURSE, $instanceid)) {
6131 return $context;
6134 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$instanceid))) {
6135 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6136 if ($course->category) {
6137 $parentcontext = context_coursecat::instance($course->category);
6138 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6139 } else {
6140 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6145 if ($record) {
6146 $context = new context_course($record);
6147 context::cache_add($context);
6148 return $context;
6151 return false;
6155 * Create missing context instances at course context level
6156 * @static
6158 protected static function create_level_instances() {
6159 global $DB;
6161 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6162 SELECT ".CONTEXT_COURSE.", c.id
6163 FROM {course} c
6164 WHERE NOT EXISTS (SELECT 'x'
6165 FROM {context} cx
6166 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6167 $DB->execute($sql);
6171 * Returns sql necessary for purging of stale context instances.
6173 * @static
6174 * @return string cleanup SQL
6176 protected static function get_cleanup_sql() {
6177 $sql = "
6178 SELECT c.*
6179 FROM {context} c
6180 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6181 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6184 return $sql;
6188 * Rebuild context paths and depths at course context level.
6190 * @static
6191 * @param $force
6193 protected static function build_paths($force) {
6194 global $DB;
6196 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6197 if ($force) {
6198 $ctxemptyclause = $emptyclause = '';
6199 } else {
6200 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6201 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6204 $base = '/'.SYSCONTEXTID;
6206 // Standard frontpage
6207 $sql = "UPDATE {context}
6208 SET depth = 2,
6209 path = ".$DB->sql_concat("'$base/'", 'id')."
6210 WHERE contextlevel = ".CONTEXT_COURSE."
6211 AND EXISTS (SELECT 'x'
6212 FROM {course} c
6213 WHERE c.id = {context}.instanceid AND c.category = 0)
6214 $emptyclause";
6215 $DB->execute($sql);
6217 // standard courses
6218 $sql = "INSERT INTO {context_temp} (id, path, depth)
6219 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6220 FROM {context} ctx
6221 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6222 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6223 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6224 $ctxemptyclause";
6225 $trans = $DB->start_delegated_transaction();
6226 $DB->delete_records('context_temp');
6227 $DB->execute($sql);
6228 context::merge_context_temp_table();
6229 $DB->delete_records('context_temp');
6230 $trans->allow_commit();
6237 * Course module context class
6238 * @author Petr Skoda (http://skodak.org)
6239 * @since 2.2
6241 class context_module extends context {
6243 * Please use context_module::instance($cmid) if you need the instance of context.
6244 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6246 * @param stdClass $record
6248 protected function __construct(stdClass $record) {
6249 parent::__construct($record);
6250 if ($record->contextlevel != CONTEXT_MODULE) {
6251 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6256 * Returns human readable context level name.
6258 * @static
6259 * @return string the human readable context level name.
6261 protected static function get_level_name() {
6262 return get_string('activitymodule');
6266 * Returns human readable context identifier.
6268 * @param boolean $withprefix whether to prefix the name of the context with the
6269 * module name, e.g. Forum, Glossary, etc.
6270 * @param boolean $short does not apply to module context
6271 * @return string the human readable context name.
6273 public function get_context_name($withprefix = true, $short = false) {
6274 global $DB;
6276 $name = '';
6277 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6278 FROM {course_modules} cm
6279 JOIN {modules} md ON md.id = cm.module
6280 WHERE cm.id = ?", array($this->_instanceid))) {
6281 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6282 if ($withprefix){
6283 $name = get_string('modulename', $cm->modname).': ';
6285 $name .= $mod->name;
6288 return $name;
6292 * Returns the most relevant URL for this context.
6294 * @return moodle_url
6296 public function get_url() {
6297 global $DB;
6299 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6300 FROM {course_modules} cm
6301 JOIN {modules} md ON md.id = cm.module
6302 WHERE cm.id = ?", array($this->_instanceid))) {
6303 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6306 return new moodle_url('/');
6310 * Returns array of relevant context capability records.
6312 * @return array
6314 public function get_capabilities() {
6315 global $DB, $CFG;
6317 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6319 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6320 $module = $DB->get_record('modules', array('id'=>$cm->module));
6322 $subcaps = array();
6323 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6324 if (file_exists($subpluginsfile)) {
6325 $subplugins = array(); // should be redefined in the file
6326 include($subpluginsfile);
6327 if (!empty($subplugins)) {
6328 foreach (array_keys($subplugins) as $subplugintype) {
6329 foreach (array_keys(get_plugin_list($subplugintype)) as $subpluginname) {
6330 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6336 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6337 if (file_exists($modfile)) {
6338 include_once($modfile);
6339 $modfunction = $module->name.'_get_extra_capabilities';
6340 if (function_exists($modfunction)) {
6341 $extracaps = $modfunction();
6344 if (empty($extracaps)) {
6345 $extracaps = array();
6348 $extracaps = array_merge($subcaps, $extracaps);
6350 // All modules allow viewhiddenactivities. This is so you can hide
6351 // the module then override to allow specific roles to see it.
6352 // The actual check is in course page so not module-specific
6353 $extracaps[] = "moodle/course:viewhiddenactivities";
6354 list($extra, $params) = $DB->get_in_or_equal(
6355 $extracaps, SQL_PARAMS_NAMED, 'cap0');
6356 $extra = "OR name $extra";
6358 $sql = "SELECT *
6359 FROM {capabilities}
6360 WHERE (contextlevel = ".CONTEXT_MODULE."
6361 AND component = :component)
6362 $extra";
6363 $params['component'] = "mod_$module->name";
6365 return $DB->get_records_sql($sql.' '.$sort, $params);
6369 * Is this context part of any course? If yes return course context.
6371 * @param bool $strict true means throw exception if not found, false means return false if not found
6372 * @return course_context context of the enclosing course, null if not found or exception
6374 public function get_course_context($strict = true) {
6375 return $this->get_parent_context();
6379 * Returns module context instance.
6381 * @static
6382 * @param int $instanceid
6383 * @param int $strictness
6384 * @return context_module context instance
6386 public static function instance($instanceid, $strictness = MUST_EXIST) {
6387 global $DB;
6389 if ($context = context::cache_get(CONTEXT_MODULE, $instanceid)) {
6390 return $context;
6393 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$instanceid))) {
6394 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
6395 $parentcontext = context_course::instance($cm->course);
6396 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6400 if ($record) {
6401 $context = new context_module($record);
6402 context::cache_add($context);
6403 return $context;
6406 return false;
6410 * Create missing context instances at module context level
6411 * @static
6413 protected static function create_level_instances() {
6414 global $DB;
6416 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6417 SELECT ".CONTEXT_MODULE.", cm.id
6418 FROM {course_modules} cm
6419 WHERE NOT EXISTS (SELECT 'x'
6420 FROM {context} cx
6421 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6422 $DB->execute($sql);
6426 * Returns sql necessary for purging of stale context instances.
6428 * @static
6429 * @return string cleanup SQL
6431 protected static function get_cleanup_sql() {
6432 $sql = "
6433 SELECT c.*
6434 FROM {context} c
6435 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6436 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6439 return $sql;
6443 * Rebuild context paths and depths at module context level.
6445 * @static
6446 * @param $force
6448 protected static function build_paths($force) {
6449 global $DB;
6451 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6452 if ($force) {
6453 $ctxemptyclause = '';
6454 } else {
6455 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6458 $sql = "INSERT INTO {context_temp} (id, path, depth)
6459 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6460 FROM {context} ctx
6461 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6462 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6463 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6464 $ctxemptyclause";
6465 $trans = $DB->start_delegated_transaction();
6466 $DB->delete_records('context_temp');
6467 $DB->execute($sql);
6468 context::merge_context_temp_table();
6469 $DB->delete_records('context_temp');
6470 $trans->allow_commit();
6477 * Block context class
6478 * @author Petr Skoda (http://skodak.org)
6479 * @since 2.2
6481 class context_block extends context {
6483 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6484 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6486 * @param stdClass $record
6488 protected function __construct(stdClass $record) {
6489 parent::__construct($record);
6490 if ($record->contextlevel != CONTEXT_BLOCK) {
6491 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6496 * Returns human readable context level name.
6498 * @static
6499 * @return string the human readable context level name.
6501 protected static function get_level_name() {
6502 return get_string('block');
6506 * Returns human readable context identifier.
6508 * @param boolean $withprefix whether to prefix the name of the context with Block
6509 * @param boolean $short does not apply to block context
6510 * @return string the human readable context name.
6512 public function get_context_name($withprefix = true, $short = false) {
6513 global $DB, $CFG;
6515 $name = '';
6516 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
6517 global $CFG;
6518 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6519 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6520 $blockname = "block_$blockinstance->blockname";
6521 if ($blockobject = new $blockname()) {
6522 if ($withprefix){
6523 $name = get_string('block').': ';
6525 $name .= $blockobject->title;
6529 return $name;
6533 * Returns the most relevant URL for this context.
6535 * @return moodle_url
6537 public function get_url() {
6538 $parentcontexts = $this->get_parent_context();
6539 return $parentcontexts->get_url();
6543 * Returns array of relevant context capability records.
6545 * @return array
6547 public function get_capabilities() {
6548 global $DB;
6550 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6552 $params = array();
6553 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
6555 $extra = '';
6556 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
6557 if ($extracaps) {
6558 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6559 $extra = "OR name $extra";
6562 $sql = "SELECT *
6563 FROM {capabilities}
6564 WHERE (contextlevel = ".CONTEXT_BLOCK."
6565 AND component = :component)
6566 $extra";
6567 $params['component'] = 'block_' . $bi->blockname;
6569 return $DB->get_records_sql($sql.' '.$sort, $params);
6573 * Is this context part of any course? If yes return course context.
6575 * @param bool $strict true means throw exception if not found, false means return false if not found
6576 * @return course_context context of the enclosing course, null if not found or exception
6578 public function get_course_context($strict = true) {
6579 $parentcontext = $this->get_parent_context();
6580 return $parentcontext->get_course_context($strict);
6584 * Returns block context instance.
6586 * @static
6587 * @param int $instanceid
6588 * @param int $strictness
6589 * @return context_block context instance
6591 public static function instance($instanceid, $strictness = MUST_EXIST) {
6592 global $DB;
6594 if ($context = context::cache_get(CONTEXT_BLOCK, $instanceid)) {
6595 return $context;
6598 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$instanceid))) {
6599 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
6600 $parentcontext = context::instance_by_id($bi->parentcontextid);
6601 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
6605 if ($record) {
6606 $context = new context_block($record);
6607 context::cache_add($context);
6608 return $context;
6611 return false;
6615 * Block do not have child contexts...
6616 * @return array
6618 public function get_child_contexts() {
6619 return array();
6623 * Create missing context instances at block context level
6624 * @static
6626 protected static function create_level_instances() {
6627 global $DB;
6629 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6630 SELECT ".CONTEXT_BLOCK.", bi.id
6631 FROM {block_instances} bi
6632 WHERE NOT EXISTS (SELECT 'x'
6633 FROM {context} cx
6634 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
6635 $DB->execute($sql);
6639 * Returns sql necessary for purging of stale context instances.
6641 * @static
6642 * @return string cleanup SQL
6644 protected static function get_cleanup_sql() {
6645 $sql = "
6646 SELECT c.*
6647 FROM {context} c
6648 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
6649 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
6652 return $sql;
6656 * Rebuild context paths and depths at block context level.
6658 * @static
6659 * @param $force
6661 protected static function build_paths($force) {
6662 global $DB;
6664 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
6665 if ($force) {
6666 $ctxemptyclause = '';
6667 } else {
6668 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6671 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
6672 $sql = "INSERT INTO {context_temp} (id, path, depth)
6673 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6674 FROM {context} ctx
6675 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
6676 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
6677 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
6678 $ctxemptyclause";
6679 $trans = $DB->start_delegated_transaction();
6680 $DB->delete_records('context_temp');
6681 $DB->execute($sql);
6682 context::merge_context_temp_table();
6683 $DB->delete_records('context_temp');
6684 $trans->allow_commit();
6690 // ============== DEPRECATED FUNCTIONS ==========================================
6691 // Old context related functions were deprecated in 2.0, it is recommended
6692 // to use context classes in new code. Old function can be used when
6693 // creating patches that are supposed to be backported to older stable branches.
6694 // These deprecated functions will not be removed in near future,
6695 // before removing devs will be warned with a debugging message first,
6696 // then we will add error message and only after that we can remove the functions
6697 // completely.
6701 * Not available any more, use load_temp_course_role() instead.
6703 * @deprecated since 2.2
6704 * @param stdClass $context
6705 * @param int $roleid
6706 * @param array $accessdata
6707 * @return array
6709 function load_temp_role($context, $roleid, array $accessdata) {
6710 debugging('load_temp_role() is deprecated, please use load_temp_course_role() instead, temp role not loaded.');
6711 return $accessdata;
6715 * Not available any more, use remove_temp_course_roles() instead.
6717 * @deprecated since 2.2
6718 * @param object $context
6719 * @param array $accessdata
6720 * @return array access data
6722 function remove_temp_roles($context, array $accessdata) {
6723 debugging('remove_temp_role() is deprecated, please use remove_temp_course_roles() instead.');
6724 return $accessdata;
6728 * Returns system context or null if can not be created yet.
6730 * @deprecated since 2.2, use context_system::instance()
6731 * @param bool $cache use caching
6732 * @return context system context (null if context table not created yet)
6734 function get_system_context($cache = true) {
6735 return context_system::instance(0, IGNORE_MISSING, $cache);
6739 * Get the context instance as an object. This function will create the
6740 * context instance if it does not exist yet.
6742 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
6743 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
6744 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
6745 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
6746 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
6747 * MUST_EXIST means throw exception if no record or multiple records found
6748 * @return context The context object.
6750 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
6751 $instances = (array)$instance;
6752 $contexts = array();
6754 $classname = context_helper::get_class_for_level($contextlevel);
6756 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
6757 foreach ($instances as $inst) {
6758 $contexts[$inst] = $classname::instance($inst, $strictness);
6761 if (is_array($instance)) {
6762 return $contexts;
6763 } else {
6764 return $contexts[$instance];
6769 * Get a context instance as an object, from a given context id.
6771 * @deprecated since 2.2, use context::instance_by_id($id) instead
6772 * @param int $id context id
6773 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
6774 * MUST_EXIST means throw exception if no record or multiple records found
6775 * @return context|bool the context object or false if not found.
6777 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
6778 return context::instance_by_id($id, $strictness);
6782 * Recursive function which, given a context, find all parent context ids,
6783 * and return the array in reverse order, i.e. parent first, then grand
6784 * parent, etc.
6786 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
6787 * @param context $context
6788 * @param bool $includeself optional, defaults to false
6789 * @return array
6791 function get_parent_contexts(context $context, $includeself = false) {
6792 return $context->get_parent_context_ids($includeself);
6796 * Return the id of the parent of this context, or false if there is no parent (only happens if this
6797 * is the site context.)
6799 * @deprecated since 2.2, use $context->get_parent_context() instead
6800 * @param context $context
6801 * @return integer the id of the parent context.
6803 function get_parent_contextid(context $context) {
6804 if ($parent = $context->get_parent_context()) {
6805 return $parent->id;
6806 } else {
6807 return false;
6812 * Recursive function which, given a context, find all its children context ids.
6814 * For course category contexts it will return immediate children only categories and courses.
6815 * It will NOT recurse into courses or child categories.
6816 * If you want to do that, call it on the returned courses/categories.
6818 * When called for a course context, it will return the modules and blocks
6819 * displayed in the course page.
6821 * If called on a user/course/module context it _will_ populate the cache with the appropriate
6822 * contexts ;-)
6824 * @deprecated since 2.2, use $context->get_child_contexts() instead
6825 * @param context $context.
6826 * @return array Array of child records
6828 function get_child_contexts(context $context) {
6829 return $context->get_child_contexts();
6833 * Precreates all contexts including all parents
6835 * @deprecated since 2.2
6836 * @param int $contextlevel empty means all
6837 * @param bool $buildpaths update paths and depths
6838 * @return void
6840 function create_contexts($contextlevel = null, $buildpaths = true) {
6841 context_helper::create_instances($contextlevel, $buildpaths);
6845 * Remove stale context records
6847 * @deprecated since 2.2, use context_helper::cleanup_instances() instead
6848 * @return bool
6850 function cleanup_contexts() {
6851 context_helper::cleanup_instances();
6852 return true;
6856 * Populate context.path and context.depth where missing.
6858 * @deprecated since 2.2, use context_helper::build_all_paths() instead
6859 * @param bool $force force a complete rebuild of the path and depth fields, defaults to false
6860 * @return void
6862 function build_context_path($force = false) {
6863 context_helper::build_all_paths($force);
6867 * Rebuild all related context depth and path caches
6869 * @deprecated
6870 * @param array $fixcontexts array of contexts, strongtyped
6871 * @return void
6873 function rebuild_contexts(array $fixcontexts) {
6874 foreach ($fixcontexts as $fixcontext) {
6875 $fixcontext->reset_paths(false);
6877 context_helper::build_all_paths(false);
6881 * Preloads all contexts relating to a course: course, modules. Block contexts
6882 * are no longer loaded here. The contexts for all the blocks on the current
6883 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
6885 * @deprecated since 2.2
6886 * @param int $courseid Course ID
6887 * @return void
6889 function preload_course_contexts($courseid) {
6890 context_helper::preload_course($courseid);
6894 * Preloads context information together with instances.
6895 * Use context_instance_preload() to strip the context info from the record and cache the context instance.
6897 * @deprecated
6898 * @param string $joinon for example 'u.id'
6899 * @param string $contextlevel context level of instance in $joinon
6900 * @param string $tablealias context table alias
6901 * @return array with two values - select and join part
6903 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
6904 $select = ", ".context_helper::get_preload_record_columns_sql($tablealias);
6905 $join = "LEFT JOIN {context} $tablealias ON ($tablealias.instanceid = $joinon AND $tablealias.contextlevel = $contextlevel)";
6906 return array($select, $join);
6910 * Preloads context information from db record and strips the cached info.
6911 * The db request has to contain both the $join and $select from context_instance_preload_sql()
6913 * @deprecated since 2.2
6914 * @param stdClass $rec
6915 * @return void (modifies $rec)
6917 function context_instance_preload(stdClass $rec) {
6918 context_helper::preload_from_record($rec);
6922 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
6924 * @deprecated since 2.2, use $context->mark_dirty() instead
6925 * @param string $path context path
6927 function mark_context_dirty($path) {
6928 global $CFG, $USER, $ACCESSLIB_PRIVATE;
6930 if (during_initial_install()) {
6931 return;
6934 // only if it is a non-empty string
6935 if (is_string($path) && $path !== '') {
6936 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
6937 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
6938 $ACCESSLIB_PRIVATE->dirtycontexts[$path] = 1;
6939 } else {
6940 if (CLI_SCRIPT) {
6941 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
6942 } else {
6943 if (isset($USER->access['time'])) {
6944 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
6945 } else {
6946 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
6948 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
6955 * Update the path field of the context and all dep. subcontexts that follow
6957 * Update the path field of the context and
6958 * all the dependent subcontexts that follow
6959 * the move.
6961 * The most important thing here is to be as
6962 * DB efficient as possible. This op can have a
6963 * massive impact in the DB.
6965 * @deprecated since 2.2
6966 * @param context $context context obj
6967 * @param context $newparent new parent obj
6968 * @return void
6970 function context_moved(context $context, context $newparent) {
6971 $context->update_moved($newparent);
6975 * Remove a context record and any dependent entries,
6976 * removes context from static context cache too
6978 * @deprecated since 2.2, use $context->delete_content() instead
6979 * @param int $contextlevel
6980 * @param int $instanceid
6981 * @param bool $deleterecord false means keep record for now
6982 * @return bool returns true or throws an exception
6984 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
6985 if ($deleterecord) {
6986 context_helper::delete_instance($contextlevel, $instanceid);
6987 } else {
6988 $classname = context_helper::get_class_for_level($contextlevel);
6989 if ($context = $classname::instance($instanceid, IGNORE_MISSING)) {
6990 $context->delete_content();
6994 return true;
6998 * Returns context level name
6999 * @deprecated since 2.2
7000 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
7001 * @return string the name for this type of context.
7003 function get_contextlevel_name($contextlevel) {
7004 return context_helper::get_level_name($contextlevel);
7008 * Prints human readable context identifier.
7010 * @deprecated since 2.2
7011 * @param context $context the context.
7012 * @param boolean $withprefix whether to prefix the name of the context with the
7013 * type of context, e.g. User, Course, Forum, etc.
7014 * @param boolean $short whether to user the short name of the thing. Only applies
7015 * to course contexts
7016 * @return string the human readable context name.
7018 function print_context_name(context $context, $withprefix = true, $short = false) {
7019 return $context->get_context_name($withprefix, $short);
7023 * Get a URL for a context, if there is a natural one. For example, for
7024 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
7025 * user profile page.
7027 * @deprecated since 2.2
7028 * @param context $context the context.
7029 * @return moodle_url
7031 function get_context_url(context $context) {
7032 return $context->get_url();
7036 * Is this context part of any course? if yes return course context,
7037 * if not return null or throw exception.
7039 * @deprecated since 2.2, use $context->get_course_context() instead
7040 * @param context $context
7041 * @return course_context context of the enclosing course, null if not found or exception
7043 function get_course_context(context $context) {
7044 return $context->get_course_context(true);
7048 * Returns current course id or null if outside of course based on context parameter.
7050 * @deprecated since 2.2, use $context->get_course_context instead
7051 * @param context $context
7052 * @return int|bool related course id or false
7054 function get_courseid_from_context(context $context) {
7055 if ($coursecontext = $context->get_course_context(false)) {
7056 return $coursecontext->instanceid;
7057 } else {
7058 return false;
7063 * Get an array of courses where cap requested is available
7064 * and user is enrolled, this can be relatively slow.
7066 * @deprecated since 2.2, use enrol_get_users_courses() instead
7067 * @param int $userid A user id. By default (null) checks the permissions of the current user.
7068 * @param string $cap - name of the capability
7069 * @param array $accessdata_ignored
7070 * @param bool $doanything_ignored
7071 * @param string $sort - sorting fields - prefix each fieldname with "c."
7072 * @param array $fields - additional fields you are interested in...
7073 * @param int $limit_ignored
7074 * @return array $courses - ordered array of course objects - see notes above
7076 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
7078 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
7079 foreach ($courses as $id=>$course) {
7080 $context = context_course::instance($id);
7081 if (!has_capability($cap, $context, $userid)) {
7082 unset($courses[$id]);
7086 return $courses;
7090 * Extracts the relevant capabilities given a contextid.
7091 * All case based, example an instance of forum context.
7092 * Will fetch all forum related capabilities, while course contexts
7093 * Will fetch all capabilities
7095 * capabilities
7096 * `name` varchar(150) NOT NULL,
7097 * `captype` varchar(50) NOT NULL,
7098 * `contextlevel` int(10) NOT NULL,
7099 * `component` varchar(100) NOT NULL,
7101 * @deprecated since 2.2
7102 * @param context $context
7103 * @return array
7105 function fetch_context_capabilities(context $context) {
7106 return $context->get_capabilities();
7110 * Runs get_records select on context table and returns the result
7111 * Does get_records_select on the context table, and returns the results ordered
7112 * by contextlevel, and then the natural sort order within each level.
7113 * for the purpose of $select, you need to know that the context table has been
7114 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7116 * @deprecated since 2.2
7117 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7118 * @param array $params any parameters required by $select.
7119 * @return array the requested context records.
7121 function get_sorted_contexts($select, $params = array()) {
7123 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7125 global $DB;
7126 if ($select) {
7127 $select = 'WHERE ' . $select;
7129 return $DB->get_records_sql("
7130 SELECT ctx.*
7131 FROM {context} ctx
7132 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7133 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7134 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7135 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7136 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7137 $select
7138 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7139 ", $params);
7143 * This is really slow!!! do not use above course context level
7145 * @deprecated since 2.2
7146 * @param int $roleid
7147 * @param context $context
7148 * @return array
7150 function get_role_context_caps($roleid, context $context) {
7151 global $DB;
7153 //this is really slow!!!! - do not use above course context level!
7154 $result = array();
7155 $result[$context->id] = array();
7157 // first emulate the parent context capabilities merging into context
7158 $searchcontexts = array_reverse($context->get_parent_context_ids(true));
7159 foreach ($searchcontexts as $cid) {
7160 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7161 foreach ($capabilities as $cap) {
7162 if (!array_key_exists($cap->capability, $result[$context->id])) {
7163 $result[$context->id][$cap->capability] = 0;
7165 $result[$context->id][$cap->capability] += $cap->permission;
7170 // now go through the contexts bellow given context
7171 $searchcontexts = array_keys($context->get_child_contexts());
7172 foreach ($searchcontexts as $cid) {
7173 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7174 foreach ($capabilities as $cap) {
7175 if (!array_key_exists($cap->contextid, $result)) {
7176 $result[$cap->contextid] = array();
7178 $result[$cap->contextid][$cap->capability] = $cap->permission;
7183 return $result;
7187 * Gets a string for sql calls, searching for stuff in this context or above
7189 * NOTE: use $DB->get_in_or_equal($context->get_parent_context_ids()...
7191 * @deprecated since 2.2, $context->use get_parent_context_ids() instead
7192 * @param context $context
7193 * @return string
7195 function get_related_contexts_string(context $context) {
7197 if ($parents = $context->get_parent_context_ids()) {
7198 return (' IN ('.$context->id.','.implode(',', $parents).')');
7199 } else {
7200 return (' ='.$context->id);