MDL-27622 theme_mymobile: add it to core themes
[moodle.git] / lib / accesslib.php
blob131b0e35a6a2e3b3172cc72566065f450cbb4f39
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);
1126 // init/reset internal enrol caches - active course enrolments and temp access
1127 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1131 * A convenience function to completely reload all the capabilities
1132 * for the current user when roles have been updated in a relevant
1133 * context -- but PRESERVING switchroles and loginas.
1134 * This function resets all accesslib and context caches.
1136 * That is - completely transparent to the user.
1138 * Note: reloads $USER->access completely.
1140 * @private
1141 * @return void
1143 function reload_all_capabilities() {
1144 global $USER, $DB, $ACCESSLIB_PRIVATE;
1146 // copy switchroles
1147 $sw = array();
1148 if (isset($USER->access['rsw'])) {
1149 $sw = $USER->access['rsw'];
1152 accesslib_clear_all_caches(true);
1153 unset($USER->access);
1154 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1156 load_all_capabilities();
1158 foreach ($sw as $path => $roleid) {
1159 if ($record = $DB->get_record('context', array('path'=>$path))) {
1160 $context = context::instance_by_id($record->id);
1161 role_switch($roleid, $context);
1167 * Adds a temp role to current USER->access array.
1169 * Useful for the "temporary guest" access we grant to logged-in users.
1170 * @since 2.2
1172 * @param context_course $coursecontext
1173 * @param int $roleid
1174 * @return void
1176 function load_temp_course_role(context_course $coursecontext, $roleid) {
1177 global $USER, $SITE;
1179 if (empty($roleid)) {
1180 debugging('invalid role specified in load_temp_course_role()');
1181 return;
1184 if ($coursecontext->instanceid == $SITE->id) {
1185 debugging('Can not use temp roles on the frontpage');
1186 return;
1189 if (!isset($USER->access)) {
1190 load_all_capabilities();
1193 $coursecontext->reload_if_dirty();
1195 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1196 return;
1199 // load course stuff first
1200 load_course_context($USER->id, $coursecontext, $USER->access);
1202 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1204 load_role_access_by_context($roleid, $coursecontext, $USER->access);
1208 * Removes any extra guest roles from current USER->access array.
1209 * @since 2.2
1211 * @param context_course $coursecontext
1212 * @return void
1214 function remove_temp_course_roles(context_course $coursecontext) {
1215 global $DB, $USER, $SITE;
1217 if ($coursecontext->instanceid == $SITE->id) {
1218 debugging('Can not use temp roles on the frontpage');
1219 return;
1222 if (empty($USER->access['ra'][$coursecontext->path])) {
1223 //no roles here, weird
1224 return;
1227 $sql = "SELECT DISTINCT ra.roleid AS id
1228 FROM {role_assignments} ra
1229 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1230 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1232 $USER->access['ra'][$coursecontext->path] = array();
1233 foreach($ras as $r) {
1234 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1239 * Returns array of all role archetypes.
1241 * @return array
1243 function get_role_archetypes() {
1244 return array(
1245 'manager' => 'manager',
1246 'coursecreator' => 'coursecreator',
1247 'editingteacher' => 'editingteacher',
1248 'teacher' => 'teacher',
1249 'student' => 'student',
1250 'guest' => 'guest',
1251 'user' => 'user',
1252 'frontpage' => 'frontpage'
1257 * Assign the defaults found in this capability definition to roles that have
1258 * the corresponding legacy capabilities assigned to them.
1260 * @param string $capability
1261 * @param array $legacyperms an array in the format (example):
1262 * 'guest' => CAP_PREVENT,
1263 * 'student' => CAP_ALLOW,
1264 * 'teacher' => CAP_ALLOW,
1265 * 'editingteacher' => CAP_ALLOW,
1266 * 'coursecreator' => CAP_ALLOW,
1267 * 'manager' => CAP_ALLOW
1268 * @return boolean success or failure.
1270 function assign_legacy_capabilities($capability, $legacyperms) {
1272 $archetypes = get_role_archetypes();
1274 foreach ($legacyperms as $type => $perm) {
1276 $systemcontext = context_system::instance();
1277 if ($type === 'admin') {
1278 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1279 $type = 'manager';
1282 if (!array_key_exists($type, $archetypes)) {
1283 print_error('invalidlegacy', '', '', $type);
1286 if ($roles = get_archetype_roles($type)) {
1287 foreach ($roles as $role) {
1288 // Assign a site level capability.
1289 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1290 return false;
1295 return true;
1299 * Verify capability risks.
1301 * @param object $capability a capability - a row from the capabilities table.
1302 * @return boolean whether this capability is safe - that is, whether people with the
1303 * safeoverrides capability should be allowed to change it.
1305 function is_safe_capability($capability) {
1306 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1310 * Get the local override (if any) for a given capability in a role in a context
1312 * @param int $roleid
1313 * @param int $contextid
1314 * @param string $capability
1315 * @return stdClass local capability override
1317 function get_local_override($roleid, $contextid, $capability) {
1318 global $DB;
1319 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1323 * Returns context instance plus related course and cm instances
1325 * @param int $contextid
1326 * @return array of ($context, $course, $cm)
1328 function get_context_info_array($contextid) {
1329 global $DB;
1331 $context = context::instance_by_id($contextid, MUST_EXIST);
1332 $course = null;
1333 $cm = null;
1335 if ($context->contextlevel == CONTEXT_COURSE) {
1336 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1338 } else if ($context->contextlevel == CONTEXT_MODULE) {
1339 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1340 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1342 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1343 $parent = $context->get_parent_context();
1345 if ($parent->contextlevel == CONTEXT_COURSE) {
1346 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1347 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1348 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1349 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1353 return array($context, $course, $cm);
1357 * Function that creates a role
1359 * @param string $name role name
1360 * @param string $shortname role short name
1361 * @param string $description role description
1362 * @param string $archetype
1363 * @return int id or dml_exception
1365 function create_role($name, $shortname, $description, $archetype = '') {
1366 global $DB;
1368 if (strpos($archetype, 'moodle/legacy:') !== false) {
1369 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1372 // verify role archetype actually exists
1373 $archetypes = get_role_archetypes();
1374 if (empty($archetypes[$archetype])) {
1375 $archetype = '';
1378 // Insert the role record.
1379 $role = new stdClass();
1380 $role->name = $name;
1381 $role->shortname = $shortname;
1382 $role->description = $description;
1383 $role->archetype = $archetype;
1385 //find free sortorder number
1386 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1387 if (empty($role->sortorder)) {
1388 $role->sortorder = 1;
1390 $id = $DB->insert_record('role', $role);
1392 return $id;
1396 * Function that deletes a role and cleanups up after it
1398 * @param int $roleid id of role to delete
1399 * @return bool always true
1401 function delete_role($roleid) {
1402 global $DB;
1404 // first unssign all users
1405 role_unassign_all(array('roleid'=>$roleid));
1407 // cleanup all references to this role, ignore errors
1408 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1409 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1410 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1411 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1412 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1413 $DB->delete_records('role_names', array('roleid'=>$roleid));
1414 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1416 // finally delete the role itself
1417 // get this before the name is gone for logging
1418 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
1420 $DB->delete_records('role', array('id'=>$roleid));
1422 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
1424 return true;
1428 * Function to write context specific overrides, or default capabilities.
1430 * NOTE: use $context->mark_dirty() after this
1432 * @param string $capability string name
1433 * @param int $permission CAP_ constants
1434 * @param int $roleid role id
1435 * @param int|context $contextid context id
1436 * @param bool $overwrite
1437 * @return bool always true or exception
1439 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1440 global $USER, $DB;
1442 if ($contextid instanceof context) {
1443 $context = $contextid;
1444 } else {
1445 $context = context::instance_by_id($contextid);
1448 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1449 unassign_capability($capability, $roleid, $context->id);
1450 return true;
1453 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1455 if ($existing and !$overwrite) { // We want to keep whatever is there already
1456 return true;
1459 $cap = new stdClass();
1460 $cap->contextid = $context->id;
1461 $cap->roleid = $roleid;
1462 $cap->capability = $capability;
1463 $cap->permission = $permission;
1464 $cap->timemodified = time();
1465 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
1467 if ($existing) {
1468 $cap->id = $existing->id;
1469 $DB->update_record('role_capabilities', $cap);
1470 } else {
1471 if ($DB->record_exists('context', array('id'=>$context->id))) {
1472 $DB->insert_record('role_capabilities', $cap);
1475 return true;
1479 * Unassign a capability from a role.
1481 * NOTE: use $context->mark_dirty() after this
1483 * @param string $capability the name of the capability
1484 * @param int $roleid the role id
1485 * @param int|context $contextid null means all contexts
1486 * @return boolean true or exception
1488 function unassign_capability($capability, $roleid, $contextid = null) {
1489 global $DB;
1491 if (!empty($contextid)) {
1492 if ($contextid instanceof context) {
1493 $context = $contextid;
1494 } else {
1495 $context = context::instance_by_id($contextid);
1497 // delete from context rel, if this is the last override in this context
1498 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1499 } else {
1500 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1502 return true;
1506 * Get the roles that have a given capability assigned to it
1508 * This function does not resolve the actual permission of the capability.
1509 * It just checks for permissions and overrides.
1510 * Use get_roles_with_cap_in_context() if resolution is required.
1512 * @param string $capability - capability name (string)
1513 * @param string $permission - optional, the permission defined for this capability
1514 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1515 * @param stdClass $context, null means any
1516 * @return array of role records
1518 function get_roles_with_capability($capability, $permission = null, $context = null) {
1519 global $DB;
1521 if ($context) {
1522 $contexts = $context->get_parent_context_ids(true);
1523 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1524 $contextsql = "AND rc.contextid $insql";
1525 } else {
1526 $params = array();
1527 $contextsql = '';
1530 if ($permission) {
1531 $permissionsql = " AND rc.permission = :permission";
1532 $params['permission'] = $permission;
1533 } else {
1534 $permissionsql = '';
1537 $sql = "SELECT r.*
1538 FROM {role} r
1539 WHERE r.id IN (SELECT rc.roleid
1540 FROM {role_capabilities} rc
1541 WHERE rc.capability = :capname
1542 $contextsql
1543 $permissionsql)";
1544 $params['capname'] = $capability;
1547 return $DB->get_records_sql($sql, $params);
1551 * This function makes a role-assignment (a role for a user in a particular context)
1553 * @param int $roleid the role of the id
1554 * @param int $userid userid
1555 * @param int|context $contextid id of the context
1556 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1557 * @param int $itemid id of enrolment/auth plugin
1558 * @param string $timemodified defaults to current time
1559 * @return int new/existing id of the assignment
1561 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1562 global $USER, $DB;
1564 // first of all detect if somebody is using old style parameters
1565 if ($contextid === 0 or is_numeric($component)) {
1566 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1569 // now validate all parameters
1570 if (empty($roleid)) {
1571 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1574 if (empty($userid)) {
1575 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1578 if ($itemid) {
1579 if (strpos($component, '_') === false) {
1580 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1582 } else {
1583 $itemid = 0;
1584 if ($component !== '' and strpos($component, '_') === false) {
1585 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1589 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1590 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1593 if ($contextid instanceof context) {
1594 $context = $contextid;
1595 } else {
1596 $context = context::instance_by_id($contextid, MUST_EXIST);
1599 if (!$timemodified) {
1600 $timemodified = time();
1603 /// Check for existing entry
1604 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1606 if ($ras) {
1607 // role already assigned - this should not happen
1608 if (count($ras) > 1) {
1609 // very weird - remove all duplicates!
1610 $ra = array_shift($ras);
1611 foreach ($ras as $r) {
1612 $DB->delete_records('role_assignments', array('id'=>$r->id));
1614 } else {
1615 $ra = reset($ras);
1618 // actually there is no need to update, reset anything or trigger any event, so just return
1619 return $ra->id;
1622 // Create a new entry
1623 $ra = new stdClass();
1624 $ra->roleid = $roleid;
1625 $ra->contextid = $context->id;
1626 $ra->userid = $userid;
1627 $ra->component = $component;
1628 $ra->itemid = $itemid;
1629 $ra->timemodified = $timemodified;
1630 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
1632 $ra->id = $DB->insert_record('role_assignments', $ra);
1634 // mark context as dirty - again expensive, but needed
1635 $context->mark_dirty();
1637 if (!empty($USER->id) && $USER->id == $userid) {
1638 // If the user is the current user, then do full reload of capabilities too.
1639 reload_all_capabilities();
1642 events_trigger('role_assigned', $ra);
1644 return $ra->id;
1648 * Removes one role assignment
1650 * @param int $roleid
1651 * @param int $userid
1652 * @param int|context $contextid
1653 * @param string $component
1654 * @param int $itemid
1655 * @return void
1657 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1658 // first make sure the params make sense
1659 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1660 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1663 if ($itemid) {
1664 if (strpos($component, '_') === false) {
1665 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1667 } else {
1668 $itemid = 0;
1669 if ($component !== '' and strpos($component, '_') === false) {
1670 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1674 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1678 * Removes multiple role assignments, parameters may contain:
1679 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1681 * @param array $params role assignment parameters
1682 * @param bool $subcontexts unassign in subcontexts too
1683 * @param bool $includemanual include manual role assignments too
1684 * @return void
1686 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1687 global $USER, $CFG, $DB;
1689 if (!$params) {
1690 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1693 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1694 foreach ($params as $key=>$value) {
1695 if (!in_array($key, $allowed)) {
1696 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1700 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1701 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1704 if ($includemanual) {
1705 if (!isset($params['component']) or $params['component'] === '') {
1706 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1710 if ($subcontexts) {
1711 if (empty($params['contextid'])) {
1712 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1716 $ras = $DB->get_records('role_assignments', $params);
1717 foreach($ras as $ra) {
1718 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1719 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1720 // this is a bit expensive but necessary
1721 $context->mark_dirty();
1722 /// If the user is the current user, then do full reload of capabilities too.
1723 if (!empty($USER->id) && $USER->id == $ra->userid) {
1724 reload_all_capabilities();
1727 events_trigger('role_unassigned', $ra);
1729 unset($ras);
1731 // process subcontexts
1732 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1733 if ($params['contextid'] instanceof context) {
1734 $context = $params['contextid'];
1735 } else {
1736 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1739 if ($context) {
1740 $contexts = $context->get_child_contexts();
1741 $mparams = $params;
1742 foreach($contexts as $context) {
1743 $mparams['contextid'] = $context->id;
1744 $ras = $DB->get_records('role_assignments', $mparams);
1745 foreach($ras as $ra) {
1746 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1747 // this is a bit expensive but necessary
1748 $context->mark_dirty();
1749 /// If the user is the current user, then do full reload of capabilities too.
1750 if (!empty($USER->id) && $USER->id == $ra->userid) {
1751 reload_all_capabilities();
1753 events_trigger('role_unassigned', $ra);
1759 // do this once more for all manual role assignments
1760 if ($includemanual) {
1761 $params['component'] = '';
1762 role_unassign_all($params, $subcontexts, false);
1767 * Determines if a user is currently logged in
1769 * @return bool
1771 function isloggedin() {
1772 global $USER;
1774 return (!empty($USER->id));
1778 * Determines if a user is logged in as real guest user with username 'guest'.
1780 * @param int|object $user mixed user object or id, $USER if not specified
1781 * @return bool true if user is the real guest user, false if not logged in or other user
1783 function isguestuser($user = null) {
1784 global $USER, $DB, $CFG;
1786 // make sure we have the user id cached in config table, because we are going to use it a lot
1787 if (empty($CFG->siteguest)) {
1788 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1789 // guest does not exist yet, weird
1790 return false;
1792 set_config('siteguest', $guestid);
1794 if ($user === null) {
1795 $user = $USER;
1798 if ($user === null) {
1799 // happens when setting the $USER
1800 return false;
1802 } else if (is_numeric($user)) {
1803 return ($CFG->siteguest == $user);
1805 } else if (is_object($user)) {
1806 if (empty($user->id)) {
1807 return false; // not logged in means is not be guest
1808 } else {
1809 return ($CFG->siteguest == $user->id);
1812 } else {
1813 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1818 * Does user have a (temporary or real) guest access to course?
1820 * @param context $context
1821 * @param stdClass|int $user
1822 * @return bool
1824 function is_guest(context $context, $user = null) {
1825 global $USER;
1827 // first find the course context
1828 $coursecontext = $context->get_course_context();
1830 // make sure there is a real user specified
1831 if ($user === null) {
1832 $userid = isset($USER->id) ? $USER->id : 0;
1833 } else {
1834 $userid = is_object($user) ? $user->id : $user;
1837 if (isguestuser($userid)) {
1838 // can not inspect or be enrolled
1839 return true;
1842 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1843 // viewing users appear out of nowhere, they are neither guests nor participants
1844 return false;
1847 // consider only real active enrolments here
1848 if (is_enrolled($coursecontext, $user, '', true)) {
1849 return false;
1852 return true;
1856 * Returns true if the user has moodle/course:view capability in the course,
1857 * this is intended for admins, managers (aka small admins), inspectors, etc.
1859 * @param context $context
1860 * @param int|stdClass $user, if null $USER is used
1861 * @param string $withcapability extra capability name
1862 * @return bool
1864 function is_viewing(context $context, $user = null, $withcapability = '') {
1865 // first find the course context
1866 $coursecontext = $context->get_course_context();
1868 if (isguestuser($user)) {
1869 // can not inspect
1870 return false;
1873 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1874 // admins are allowed to inspect courses
1875 return false;
1878 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1879 // site admins always have the capability, but the enrolment above blocks
1880 return false;
1883 return true;
1887 * Returns true if user is enrolled (is participating) in course
1888 * this is intended for students and teachers.
1890 * Since 2.2 the result for active enrolments and current user are cached.
1892 * @param context $context
1893 * @param int|stdClass $user, if null $USER is used, otherwise user object or id expected
1894 * @param string $withcapability extra capability name
1895 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1896 * @return bool
1898 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1899 global $USER, $DB;
1901 // first find the course context
1902 $coursecontext = $context->get_course_context();
1904 // make sure there is a real user specified
1905 if ($user === null) {
1906 $userid = isset($USER->id) ? $USER->id : 0;
1907 } else {
1908 $userid = is_object($user) ? $user->id : $user;
1911 if (empty($userid)) {
1912 // not-logged-in!
1913 return false;
1914 } else if (isguestuser($userid)) {
1915 // guest account can not be enrolled anywhere
1916 return false;
1919 if ($coursecontext->instanceid == SITEID) {
1920 // everybody participates on frontpage
1921 } else {
1922 // try cached info first - the enrolled flag is set only when active enrolment present
1923 if ($USER->id == $userid) {
1924 $coursecontext->reload_if_dirty();
1925 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1926 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1927 return true;
1932 if ($onlyactive) {
1933 // look for active enrolments only
1934 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1936 if ($until === false) {
1937 return false;
1940 if ($USER->id == $userid) {
1941 if ($until == 0) {
1942 $until = ENROL_MAX_TIMESTAMP;
1944 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1945 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1946 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1947 remove_temp_course_roles($coursecontext);
1951 } else {
1952 // any enrolment is good for us here, even outdated, disabled or inactive
1953 $sql = "SELECT 'x'
1954 FROM {user_enrolments} ue
1955 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1956 JOIN {user} u ON u.id = ue.userid
1957 WHERE ue.userid = :userid AND u.deleted = 0";
1958 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
1959 if (!$DB->record_exists_sql($sql, $params)) {
1960 return false;
1965 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1966 return false;
1969 return true;
1973 * Returns true if the user is able to access the course.
1975 * This function is in no way, shape, or form a substitute for require_login.
1976 * It should only be used in circumstances where it is not possible to call require_login
1977 * such as the navigation.
1979 * This function checks many of the methods of access to a course such as the view
1980 * capability, enrollments, and guest access. It also makes use of the cache
1981 * generated by require_login for guest access.
1983 * The flags within the $USER object that are used here should NEVER be used outside
1984 * of this function can_access_course and require_login. Doing so WILL break future
1985 * versions.
1987 * @param stdClass $course record
1988 * @param stdClass|int|null $user user record or id, current user if null
1989 * @param string $withcapability Check for this capability as well.
1990 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1991 * @return boolean Returns true if the user is able to access the course
1993 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
1994 global $DB, $USER;
1996 // this function originally accepted $coursecontext parameter
1997 if ($course instanceof context) {
1998 if ($course instanceof context_course) {
1999 debugging('deprecated context parameter, please use $course record');
2000 $coursecontext = $course;
2001 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2002 } else {
2003 debugging('Invalid context parameter, please use $course record');
2004 return false;
2006 } else {
2007 $coursecontext = context_course::instance($course->id);
2010 if (!isset($USER->id)) {
2011 // should never happen
2012 $USER->id = 0;
2015 // make sure there is a user specified
2016 if ($user === null) {
2017 $userid = $USER->id;
2018 } else {
2019 $userid = is_object($user) ? $user->id : $user;
2021 unset($user);
2023 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2024 return false;
2027 if ($userid == $USER->id) {
2028 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2029 // the fact that somebody switched role means they can access the course no matter to what role they switched
2030 return true;
2034 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2035 return false;
2038 if (is_viewing($coursecontext, $userid)) {
2039 return true;
2042 if ($userid != $USER->id) {
2043 // for performance reasons we do not verify temporary guest access for other users, sorry...
2044 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2047 // === from here we deal only with $USER ===
2049 $coursecontext->reload_if_dirty();
2051 if (isset($USER->enrol['enrolled'][$course->id])) {
2052 if ($USER->enrol['enrolled'][$course->id] > time()) {
2053 return true;
2056 if (isset($USER->enrol['tempguest'][$course->id])) {
2057 if ($USER->enrol['tempguest'][$course->id] > time()) {
2058 return true;
2062 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2063 return true;
2066 // if not enrolled try to gain temporary guest access
2067 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2068 $enrols = enrol_get_plugins(true);
2069 foreach($instances as $instance) {
2070 if (!isset($enrols[$instance->enrol])) {
2071 continue;
2073 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2074 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2075 if ($until !== false and $until > time()) {
2076 $USER->enrol['tempguest'][$course->id] = $until;
2077 return true;
2080 if (isset($USER->enrol['tempguest'][$course->id])) {
2081 unset($USER->enrol['tempguest'][$course->id]);
2082 remove_temp_course_roles($coursecontext);
2085 return false;
2089 * Returns array with sql code and parameters returning all ids
2090 * of users enrolled into course.
2092 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2094 * @param context $context
2095 * @param string $withcapability
2096 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2097 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2098 * @return array list($sql, $params)
2100 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2101 global $DB, $CFG;
2103 // use unique prefix just in case somebody makes some SQL magic with the result
2104 static $i = 0;
2105 $i++;
2106 $prefix = 'eu'.$i.'_';
2108 // first find the course context
2109 $coursecontext = $context->get_course_context();
2111 $isfrontpage = ($coursecontext->instanceid == SITEID);
2113 $joins = array();
2114 $wheres = array();
2115 $params = array();
2117 list($contextids, $contextpaths) = get_context_info_list($context);
2119 // get all relevant capability info for all roles
2120 if ($withcapability) {
2121 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2122 $cparams['cap'] = $withcapability;
2124 $defs = array();
2125 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2126 FROM {role_capabilities} rc
2127 JOIN {context} ctx on rc.contextid = ctx.id
2128 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2129 $rcs = $DB->get_records_sql($sql, $cparams);
2130 foreach ($rcs as $rc) {
2131 $defs[$rc->path][$rc->roleid] = $rc->permission;
2134 $access = array();
2135 if (!empty($defs)) {
2136 foreach ($contextpaths as $path) {
2137 if (empty($defs[$path])) {
2138 continue;
2140 foreach($defs[$path] as $roleid => $perm) {
2141 if ($perm == CAP_PROHIBIT) {
2142 $access[$roleid] = CAP_PROHIBIT;
2143 continue;
2145 if (!isset($access[$roleid])) {
2146 $access[$roleid] = (int)$perm;
2152 unset($defs);
2154 // make lists of roles that are needed and prohibited
2155 $needed = array(); // one of these is enough
2156 $prohibited = array(); // must not have any of these
2157 foreach ($access as $roleid => $perm) {
2158 if ($perm == CAP_PROHIBIT) {
2159 unset($needed[$roleid]);
2160 $prohibited[$roleid] = true;
2161 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2162 $needed[$roleid] = true;
2166 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2167 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2169 $nobody = false;
2171 if ($isfrontpage) {
2172 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2173 $nobody = true;
2174 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2175 // everybody not having prohibit has the capability
2176 $needed = array();
2177 } else if (empty($needed)) {
2178 $nobody = true;
2180 } else {
2181 if (!empty($prohibited[$defaultuserroleid])) {
2182 $nobody = true;
2183 } else if (!empty($needed[$defaultuserroleid])) {
2184 // everybody not having prohibit has the capability
2185 $needed = array();
2186 } else if (empty($needed)) {
2187 $nobody = true;
2191 if ($nobody) {
2192 // nobody can match so return some SQL that does not return any results
2193 $wheres[] = "1 = 2";
2195 } else {
2197 if ($needed) {
2198 $ctxids = implode(',', $contextids);
2199 $roleids = implode(',', array_keys($needed));
2200 $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))";
2203 if ($prohibited) {
2204 $ctxids = implode(',', $contextids);
2205 $roleids = implode(',', array_keys($prohibited));
2206 $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))";
2207 $wheres[] = "{$prefix}ra4.id IS NULL";
2210 if ($groupid) {
2211 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2212 $params["{$prefix}gmid"] = $groupid;
2216 } else {
2217 if ($groupid) {
2218 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2219 $params["{$prefix}gmid"] = $groupid;
2223 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2224 $params["{$prefix}guestid"] = $CFG->siteguest;
2226 if ($isfrontpage) {
2227 // all users are "enrolled" on the frontpage
2228 } else {
2229 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2230 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2231 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2233 if ($onlyactive) {
2234 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2235 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2236 $now = round(time(), -2); // rounding helps caching in DB
2237 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2238 $prefix.'active'=>ENROL_USER_ACTIVE,
2239 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2243 $joins = implode("\n", $joins);
2244 $wheres = "WHERE ".implode(" AND ", $wheres);
2246 $sql = "SELECT DISTINCT {$prefix}u.id
2247 FROM {user} {$prefix}u
2248 $joins
2249 $wheres";
2251 return array($sql, $params);
2255 * Returns list of users enrolled into course.
2257 * @param context $context
2258 * @param string $withcapability
2259 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2260 * @param string $userfields requested user record fields
2261 * @param string $orderby
2262 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2263 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2264 * @return array of user records
2266 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
2267 global $DB;
2269 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2270 $sql = "SELECT $userfields
2271 FROM {user} u
2272 JOIN ($esql) je ON je.id = u.id
2273 WHERE u.deleted = 0";
2275 if ($orderby) {
2276 $sql = "$sql ORDER BY $orderby";
2277 } else {
2278 $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
2281 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2285 * Counts list of users enrolled into course (as per above function)
2287 * @param context $context
2288 * @param string $withcapability
2289 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2290 * @return array of user records
2292 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0) {
2293 global $DB;
2295 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2296 $sql = "SELECT count(u.id)
2297 FROM {user} u
2298 JOIN ($esql) je ON je.id = u.id
2299 WHERE u.deleted = 0";
2301 return $DB->count_records_sql($sql, $params);
2305 * Loads the capability definitions for the component (from file).
2307 * Loads the capability definitions for the component (from file). If no
2308 * capabilities are defined for the component, we simply return an empty array.
2310 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2311 * @return array array of capabilities
2313 function load_capability_def($component) {
2314 $defpath = get_component_directory($component).'/db/access.php';
2316 $capabilities = array();
2317 if (file_exists($defpath)) {
2318 require($defpath);
2319 if (!empty(${$component.'_capabilities'})) {
2320 // BC capability array name
2321 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2322 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2323 $capabilities = ${$component.'_capabilities'};
2327 return $capabilities;
2331 * Gets the capabilities that have been cached in the database for this component.
2333 * @param string $component - examples: 'moodle', 'mod_forum'
2334 * @return array array of capabilities
2336 function get_cached_capabilities($component = 'moodle') {
2337 global $DB;
2338 return $DB->get_records('capabilities', array('component'=>$component));
2342 * Returns default capabilities for given role archetype.
2344 * @param string $archetype role archetype
2345 * @return array
2347 function get_default_capabilities($archetype) {
2348 global $DB;
2350 if (!$archetype) {
2351 return array();
2354 $alldefs = array();
2355 $defaults = array();
2356 $components = array();
2357 $allcaps = $DB->get_records('capabilities');
2359 foreach ($allcaps as $cap) {
2360 if (!in_array($cap->component, $components)) {
2361 $components[] = $cap->component;
2362 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2365 foreach($alldefs as $name=>$def) {
2366 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2367 if (isset($def['archetypes'])) {
2368 if (isset($def['archetypes'][$archetype])) {
2369 $defaults[$name] = $def['archetypes'][$archetype];
2371 // 'legacy' is for backward compatibility with 1.9 access.php
2372 } else {
2373 if (isset($def['legacy'][$archetype])) {
2374 $defaults[$name] = $def['legacy'][$archetype];
2379 return $defaults;
2383 * Reset role capabilities to default according to selected role archetype.
2384 * If no archetype selected, removes all capabilities.
2386 * @param int $roleid
2387 * @return void
2389 function reset_role_capabilities($roleid) {
2390 global $DB;
2392 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2393 $defaultcaps = get_default_capabilities($role->archetype);
2395 $systemcontext = context_system::instance();
2397 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2399 foreach($defaultcaps as $cap=>$permission) {
2400 assign_capability($cap, $permission, $roleid, $systemcontext->id);
2405 * Updates the capabilities table with the component capability definitions.
2406 * If no parameters are given, the function updates the core moodle
2407 * capabilities.
2409 * Note that the absence of the db/access.php capabilities definition file
2410 * will cause any stored capabilities for the component to be removed from
2411 * the database.
2413 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2414 * @return boolean true if success, exception in case of any problems
2416 function update_capabilities($component = 'moodle') {
2417 global $DB, $OUTPUT;
2419 $storedcaps = array();
2421 $filecaps = load_capability_def($component);
2422 foreach($filecaps as $capname=>$unused) {
2423 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2424 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2428 $cachedcaps = get_cached_capabilities($component);
2429 if ($cachedcaps) {
2430 foreach ($cachedcaps as $cachedcap) {
2431 array_push($storedcaps, $cachedcap->name);
2432 // update risk bitmasks and context levels in existing capabilities if needed
2433 if (array_key_exists($cachedcap->name, $filecaps)) {
2434 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2435 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2437 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2438 $updatecap = new stdClass();
2439 $updatecap->id = $cachedcap->id;
2440 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2441 $DB->update_record('capabilities', $updatecap);
2443 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2444 $updatecap = new stdClass();
2445 $updatecap->id = $cachedcap->id;
2446 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2447 $DB->update_record('capabilities', $updatecap);
2450 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2451 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2453 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2454 $updatecap = new stdClass();
2455 $updatecap->id = $cachedcap->id;
2456 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2457 $DB->update_record('capabilities', $updatecap);
2463 // Are there new capabilities in the file definition?
2464 $newcaps = array();
2466 foreach ($filecaps as $filecap => $def) {
2467 if (!$storedcaps ||
2468 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2469 if (!array_key_exists('riskbitmask', $def)) {
2470 $def['riskbitmask'] = 0; // no risk if not specified
2472 $newcaps[$filecap] = $def;
2475 // Add new capabilities to the stored definition.
2476 foreach ($newcaps as $capname => $capdef) {
2477 $capability = new stdClass();
2478 $capability->name = $capname;
2479 $capability->captype = $capdef['captype'];
2480 $capability->contextlevel = $capdef['contextlevel'];
2481 $capability->component = $component;
2482 $capability->riskbitmask = $capdef['riskbitmask'];
2484 $DB->insert_record('capabilities', $capability, false);
2486 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
2487 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2488 foreach ($rolecapabilities as $rolecapability){
2489 //assign_capability will update rather than insert if capability exists
2490 if (!assign_capability($capname, $rolecapability->permission,
2491 $rolecapability->roleid, $rolecapability->contextid, true)){
2492 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2496 // we ignore archetype key if we have cloned permissions
2497 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2498 assign_legacy_capabilities($capname, $capdef['archetypes']);
2499 // 'legacy' is for backward compatibility with 1.9 access.php
2500 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2501 assign_legacy_capabilities($capname, $capdef['legacy']);
2504 // Are there any capabilities that have been removed from the file
2505 // definition that we need to delete from the stored capabilities and
2506 // role assignments?
2507 capabilities_cleanup($component, $filecaps);
2509 // reset static caches
2510 accesslib_clear_all_caches(false);
2512 return true;
2516 * Deletes cached capabilities that are no longer needed by the component.
2517 * Also unassigns these capabilities from any roles that have them.
2519 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2520 * @param array $newcapdef array of the new capability definitions that will be
2521 * compared with the cached capabilities
2522 * @return int number of deprecated capabilities that have been removed
2524 function capabilities_cleanup($component, $newcapdef = null) {
2525 global $DB;
2527 $removedcount = 0;
2529 if ($cachedcaps = get_cached_capabilities($component)) {
2530 foreach ($cachedcaps as $cachedcap) {
2531 if (empty($newcapdef) ||
2532 array_key_exists($cachedcap->name, $newcapdef) === false) {
2534 // Remove from capabilities cache.
2535 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2536 $removedcount++;
2537 // Delete from roles.
2538 if ($roles = get_roles_with_capability($cachedcap->name)) {
2539 foreach($roles as $role) {
2540 if (!unassign_capability($cachedcap->name, $role->id)) {
2541 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2545 } // End if.
2548 return $removedcount;
2552 * Returns an array of all the known types of risk
2553 * The array keys can be used, for example as CSS class names, or in calls to
2554 * print_risk_icon. The values are the corresponding RISK_ constants.
2556 * @return array all the known types of risk.
2558 function get_all_risks() {
2559 return array(
2560 'riskmanagetrust' => RISK_MANAGETRUST,
2561 'riskconfig' => RISK_CONFIG,
2562 'riskxss' => RISK_XSS,
2563 'riskpersonal' => RISK_PERSONAL,
2564 'riskspam' => RISK_SPAM,
2565 'riskdataloss' => RISK_DATALOSS,
2570 * Return a link to moodle docs for a given capability name
2572 * @param object $capability a capability - a row from the mdl_capabilities table.
2573 * @return string the human-readable capability name as a link to Moodle Docs.
2575 function get_capability_docs_link($capability) {
2576 $url = get_docs_url('Capabilities/' . $capability->name);
2577 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2581 * This function pulls out all the resolved capabilities (overrides and
2582 * defaults) of a role used in capability overrides in contexts at a given
2583 * context.
2585 * @param context $context
2586 * @param int $roleid
2587 * @param string $cap capability, optional, defaults to ''
2588 * @return array of capabilities
2590 function role_context_capabilities($roleid, context $context, $cap = '') {
2591 global $DB;
2593 $contexts = $context->get_parent_context_ids(true);
2594 $contexts = '('.implode(',', $contexts).')';
2596 $params = array($roleid);
2598 if ($cap) {
2599 $search = " AND rc.capability = ? ";
2600 $params[] = $cap;
2601 } else {
2602 $search = '';
2605 $sql = "SELECT rc.*
2606 FROM {role_capabilities} rc, {context} c
2607 WHERE rc.contextid in $contexts
2608 AND rc.roleid = ?
2609 AND rc.contextid = c.id $search
2610 ORDER BY c.contextlevel DESC, rc.capability DESC";
2612 $capabilities = array();
2614 if ($records = $DB->get_records_sql($sql, $params)) {
2615 // We are traversing via reverse order.
2616 foreach ($records as $record) {
2617 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2618 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2619 $capabilities[$record->capability] = $record->permission;
2623 return $capabilities;
2627 * Constructs array with contextids as first parameter and context paths,
2628 * in both cases bottom top including self.
2630 * @private
2631 * @param context $context
2632 * @return array
2634 function get_context_info_list(context $context) {
2635 $contextids = explode('/', ltrim($context->path, '/'));
2636 $contextpaths = array();
2637 $contextids2 = $contextids;
2638 while ($contextids2) {
2639 $contextpaths[] = '/' . implode('/', $contextids2);
2640 array_pop($contextids2);
2642 return array($contextids, $contextpaths);
2646 * Check if context is the front page context or a context inside it
2648 * Returns true if this context is the front page context, or a context inside it,
2649 * otherwise false.
2651 * @param context $context a context object.
2652 * @return bool
2654 function is_inside_frontpage(context $context) {
2655 $frontpagecontext = context_course::instance(SITEID);
2656 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2660 * Returns capability information (cached)
2662 * @param string $capabilityname
2663 * @return object or null if capability not found
2665 function get_capability_info($capabilityname) {
2666 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2668 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2670 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2671 $ACCESSLIB_PRIVATE->capabilities = array();
2672 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2673 foreach ($caps as $cap) {
2674 $capname = $cap->name;
2675 unset($cap->id);
2676 unset($cap->name);
2677 $cap->riskbitmask = (int)$cap->riskbitmask;
2678 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2682 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2686 * Returns the human-readable, translated version of the capability.
2687 * Basically a big switch statement.
2689 * @param string $capabilityname e.g. mod/choice:readresponses
2690 * @return string
2692 function get_capability_string($capabilityname) {
2694 // Typical capability name is 'plugintype/pluginname:capabilityname'
2695 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2697 if ($type === 'moodle') {
2698 $component = 'core_role';
2699 } else if ($type === 'quizreport') {
2700 //ugly hack!!
2701 $component = 'quiz_'.$name;
2702 } else {
2703 $component = $type.'_'.$name;
2706 $stringname = $name.':'.$capname;
2708 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2709 return get_string($stringname, $component);
2712 $dir = get_component_directory($component);
2713 if (!file_exists($dir)) {
2714 // plugin broken or does not exist, do not bother with printing of debug message
2715 return $capabilityname.' ???';
2718 // something is wrong in plugin, better print debug
2719 return get_string($stringname, $component);
2723 * This gets the mod/block/course/core etc strings.
2725 * @param string $component
2726 * @param int $contextlevel
2727 * @return string|bool String is success, false if failed
2729 function get_component_string($component, $contextlevel) {
2731 if ($component === 'moodle' or $component === 'core') {
2732 switch ($contextlevel) {
2733 // TODO: this should probably use context level names instead
2734 case CONTEXT_SYSTEM: return get_string('coresystem');
2735 case CONTEXT_USER: return get_string('users');
2736 case CONTEXT_COURSECAT: return get_string('categories');
2737 case CONTEXT_COURSE: return get_string('course');
2738 case CONTEXT_MODULE: return get_string('activities');
2739 case CONTEXT_BLOCK: return get_string('block');
2740 default: print_error('unknowncontext');
2744 list($type, $name) = normalize_component($component);
2745 $dir = get_plugin_directory($type, $name);
2746 if (!file_exists($dir)) {
2747 // plugin not installed, bad luck, there is no way to find the name
2748 return $component.' ???';
2751 switch ($type) {
2752 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2753 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2754 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2755 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2756 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2757 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2758 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2759 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2760 case 'mod':
2761 if (get_string_manager()->string_exists('pluginname', $component)) {
2762 return get_string('activity').': '.get_string('pluginname', $component);
2763 } else {
2764 return get_string('activity').': '.get_string('modulename', $component);
2766 default: return get_string('pluginname', $component);
2771 * Gets the list of roles assigned to this context and up (parents)
2772 * from the list of roles that are visible on user profile page
2773 * and participants page.
2775 * @param context $context
2776 * @return array
2778 function get_profile_roles(context $context) {
2779 global $CFG, $DB;
2781 if (empty($CFG->profileroles)) {
2782 return array();
2785 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2786 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2787 $params = array_merge($params, $cparams);
2789 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2790 FROM {role_assignments} ra, {role} r
2791 WHERE r.id = ra.roleid
2792 AND ra.contextid $contextlist
2793 AND r.id $rallowed
2794 ORDER BY r.sortorder ASC";
2796 return $DB->get_records_sql($sql, $params);
2800 * Gets the list of roles assigned to this context and up (parents)
2802 * @param context $context
2803 * @return array
2805 function get_roles_used_in_context(context $context) {
2806 global $DB;
2808 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true));
2810 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2811 FROM {role_assignments} ra, {role} r
2812 WHERE r.id = ra.roleid
2813 AND ra.contextid $contextlist
2814 ORDER BY r.sortorder ASC";
2816 return $DB->get_records_sql($sql, $params);
2820 * This function is used to print roles column in user profile page.
2821 * It is using the CFG->profileroles to limit the list to only interesting roles.
2822 * (The permission tab has full details of user role assignments.)
2824 * @param int $userid
2825 * @param int $courseid
2826 * @return string
2828 function get_user_roles_in_course($userid, $courseid) {
2829 global $CFG, $DB;
2831 if (empty($CFG->profileroles)) {
2832 return '';
2835 if ($courseid == SITEID) {
2836 $context = context_system::instance();
2837 } else {
2838 $context = context_course::instance($courseid);
2841 if (empty($CFG->profileroles)) {
2842 return array();
2845 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2846 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2847 $params = array_merge($params, $cparams);
2849 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2850 FROM {role_assignments} ra, {role} r
2851 WHERE r.id = ra.roleid
2852 AND ra.contextid $contextlist
2853 AND r.id $rallowed
2854 AND ra.userid = :userid
2855 ORDER BY r.sortorder ASC";
2856 $params['userid'] = $userid;
2858 $rolestring = '';
2860 if ($roles = $DB->get_records_sql($sql, $params)) {
2861 foreach ($roles as $userrole) {
2862 $rolenames[$userrole->id] = $userrole->name;
2865 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
2867 foreach ($rolenames as $roleid => $rolename) {
2868 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
2870 $rolestring = implode(',', $rolenames);
2873 return $rolestring;
2877 * Checks if a user can assign users to a particular role in this context
2879 * @param context $context
2880 * @param int $targetroleid - the id of the role you want to assign users to
2881 * @return boolean
2883 function user_can_assign(context $context, $targetroleid) {
2884 global $DB;
2886 // first check if user has override capability
2887 // if not return false;
2888 if (!has_capability('moodle/role:assign', $context)) {
2889 return false;
2891 // pull out all active roles of this user from this context(or above)
2892 if ($userroles = get_user_roles($context)) {
2893 foreach ($userroles as $userrole) {
2894 // if any in the role_allow_override table, then it's ok
2895 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2896 return true;
2901 return false;
2905 * Returns all site roles in correct sort order.
2907 * @return array
2909 function get_all_roles() {
2910 global $DB;
2911 return $DB->get_records('role', null, 'sortorder ASC');
2915 * Returns roles of a specified archetype
2917 * @param string $archetype
2918 * @return array of full role records
2920 function get_archetype_roles($archetype) {
2921 global $DB;
2922 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2926 * Gets all the user roles assigned in this context, or higher contexts
2927 * this is mainly used when checking if a user can assign a role, or overriding a role
2928 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2929 * allow_override tables
2931 * @param context $context
2932 * @param int $userid
2933 * @param bool $checkparentcontexts defaults to true
2934 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2935 * @return array
2937 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2938 global $USER, $DB;
2940 if (empty($userid)) {
2941 if (empty($USER->id)) {
2942 return array();
2944 $userid = $USER->id;
2947 if ($checkparentcontexts) {
2948 $contextids = $context->get_parent_context_ids();
2949 } else {
2950 $contextids = array();
2952 $contextids[] = $context->id;
2954 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2956 array_unshift($params, $userid);
2958 $sql = "SELECT ra.*, r.name, r.shortname
2959 FROM {role_assignments} ra, {role} r, {context} c
2960 WHERE ra.userid = ?
2961 AND ra.roleid = r.id
2962 AND ra.contextid = c.id
2963 AND ra.contextid $contextids
2964 ORDER BY $order";
2966 return $DB->get_records_sql($sql ,$params);
2970 * Creates a record in the role_allow_override table
2972 * @param int $sroleid source roleid
2973 * @param int $troleid target roleid
2974 * @return void
2976 function allow_override($sroleid, $troleid) {
2977 global $DB;
2979 $record = new stdClass();
2980 $record->roleid = $sroleid;
2981 $record->allowoverride = $troleid;
2982 $DB->insert_record('role_allow_override', $record);
2986 * Creates a record in the role_allow_assign table
2988 * @param int $fromroleid source roleid
2989 * @param int $targetroleid target roleid
2990 * @return void
2992 function allow_assign($fromroleid, $targetroleid) {
2993 global $DB;
2995 $record = new stdClass();
2996 $record->roleid = $fromroleid;
2997 $record->allowassign = $targetroleid;
2998 $DB->insert_record('role_allow_assign', $record);
3002 * Creates a record in the role_allow_switch table
3004 * @param int $fromroleid source roleid
3005 * @param int $targetroleid target roleid
3006 * @return void
3008 function allow_switch($fromroleid, $targetroleid) {
3009 global $DB;
3011 $record = new stdClass();
3012 $record->roleid = $fromroleid;
3013 $record->allowswitch = $targetroleid;
3014 $DB->insert_record('role_allow_switch', $record);
3018 * Gets a list of roles that this user can assign in this context
3020 * @param context $context the context.
3021 * @param int $rolenamedisplay the type of role name to display. One of the
3022 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3023 * @param bool $withusercounts if true, count the number of users with each role.
3024 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3025 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3026 * if $withusercounts is true, returns a list of three arrays,
3027 * $rolenames, $rolecounts, and $nameswithcounts.
3029 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3030 global $USER, $DB;
3032 // make sure there is a real user specified
3033 if ($user === null) {
3034 $userid = isset($USER->id) ? $USER->id : 0;
3035 } else {
3036 $userid = is_object($user) ? $user->id : $user;
3039 if (!has_capability('moodle/role:assign', $context, $userid)) {
3040 if ($withusercounts) {
3041 return array(array(), array(), array());
3042 } else {
3043 return array();
3047 $parents = $context->get_parent_context_ids(true);
3048 $contexts = implode(',' , $parents);
3050 $params = array();
3051 $extrafields = '';
3052 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT or $rolenamedisplay == ROLENAME_SHORT) {
3053 $extrafields .= ', r.shortname';
3056 if ($withusercounts) {
3057 $extrafields = ', (SELECT count(u.id)
3058 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3059 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3060 ) AS usercount';
3061 $params['conid'] = $context->id;
3064 if (is_siteadmin($userid)) {
3065 // show all roles allowed in this context to admins
3066 $assignrestriction = "";
3067 } else {
3068 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3069 FROM {role_allow_assign} raa
3070 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3071 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3072 ) ar ON ar.id = r.id";
3073 $params['userid'] = $userid;
3075 $params['contextlevel'] = $context->contextlevel;
3076 $sql = "SELECT r.id, r.name $extrafields
3077 FROM {role} r
3078 $assignrestriction
3079 JOIN {role_context_levels} rcl ON r.id = rcl.roleid
3080 WHERE rcl.contextlevel = :contextlevel
3081 ORDER BY r.sortorder ASC";
3082 $roles = $DB->get_records_sql($sql, $params);
3084 $rolenames = array();
3085 foreach ($roles as $role) {
3086 if ($rolenamedisplay == ROLENAME_SHORT) {
3087 $rolenames[$role->id] = $role->shortname;
3088 continue;
3090 $rolenames[$role->id] = $role->name;
3091 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3092 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3095 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT and $rolenamedisplay != ROLENAME_SHORT) {
3096 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3099 if (!$withusercounts) {
3100 return $rolenames;
3103 $rolecounts = array();
3104 $nameswithcounts = array();
3105 foreach ($roles as $role) {
3106 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3107 $rolecounts[$role->id] = $roles[$role->id]->usercount;
3109 return array($rolenames, $rolecounts, $nameswithcounts);
3113 * Gets a list of roles that this user can switch to in a context
3115 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3116 * This function just process the contents of the role_allow_switch table. You also need to
3117 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3119 * @param context $context a context.
3120 * @return array an array $roleid => $rolename.
3122 function get_switchable_roles(context $context) {
3123 global $USER, $DB;
3125 $params = array();
3126 $extrajoins = '';
3127 $extrawhere = '';
3128 if (!is_siteadmin()) {
3129 // Admins are allowed to switch to any role with.
3130 // Others are subject to the additional constraint that the switch-to role must be allowed by
3131 // 'role_allow_switch' for some role they have assigned in this context or any parent.
3132 $parents = $context->get_parent_context_ids(true);
3133 $contexts = implode(',' , $parents);
3135 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3136 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3137 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3138 $params['userid'] = $USER->id;
3141 $query = "
3142 SELECT r.id, r.name
3143 FROM (SELECT DISTINCT rc.roleid
3144 FROM {role_capabilities} rc
3145 $extrajoins
3146 $extrawhere) idlist
3147 JOIN {role} r ON r.id = idlist.roleid
3148 ORDER BY r.sortorder";
3150 $rolenames = $DB->get_records_sql_menu($query, $params);
3151 return role_fix_names($rolenames, $context, ROLENAME_ALIAS);
3155 * Gets a list of roles that this user can override in this context.
3157 * @param context $context the context.
3158 * @param int $rolenamedisplay the type of role name to display. One of the
3159 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3160 * @param bool $withcounts if true, count the number of overrides that are set for each role.
3161 * @return array if $withcounts is false, then an array $roleid => $rolename.
3162 * if $withusercounts is true, returns a list of three arrays,
3163 * $rolenames, $rolecounts, and $nameswithcounts.
3165 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3166 global $USER, $DB;
3168 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3169 if ($withcounts) {
3170 return array(array(), array(), array());
3171 } else {
3172 return array();
3176 $parents = $context->get_parent_context_ids(true);
3177 $contexts = implode(',' , $parents);
3179 $params = array();
3180 $extrafields = '';
3181 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3182 $extrafields .= ', ro.shortname';
3185 $params['userid'] = $USER->id;
3186 if ($withcounts) {
3187 $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3188 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3189 $params['conid'] = $context->id;
3192 if (is_siteadmin()) {
3193 // show all roles to admins
3194 $roles = $DB->get_records_sql("
3195 SELECT ro.id, ro.name$extrafields
3196 FROM {role} ro
3197 ORDER BY ro.sortorder ASC", $params);
3199 } else {
3200 $roles = $DB->get_records_sql("
3201 SELECT ro.id, ro.name$extrafields
3202 FROM {role} ro
3203 JOIN (SELECT DISTINCT r.id
3204 FROM {role} r
3205 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3206 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3207 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3208 ) inline_view ON ro.id = inline_view.id
3209 ORDER BY ro.sortorder ASC", $params);
3212 $rolenames = array();
3213 foreach ($roles as $role) {
3214 $rolenames[$role->id] = $role->name;
3215 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3216 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3219 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT) {
3220 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3223 if (!$withcounts) {
3224 return $rolenames;
3227 $rolecounts = array();
3228 $nameswithcounts = array();
3229 foreach ($roles as $role) {
3230 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3231 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3233 return array($rolenames, $rolecounts, $nameswithcounts);
3237 * Create a role menu suitable for default role selection in enrol plugins.
3238 * @param context $context
3239 * @param int $addroleid current or default role - always added to list
3240 * @return array roleid=>localised role name
3242 function get_default_enrol_roles(context $context, $addroleid = null) {
3243 global $DB;
3245 $params = array('contextlevel'=>CONTEXT_COURSE);
3246 if ($addroleid) {
3247 $addrole = "OR r.id = :addroleid";
3248 $params['addroleid'] = $addroleid;
3249 } else {
3250 $addrole = "";
3252 $sql = "SELECT r.id, r.name
3253 FROM {role} r
3254 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3255 WHERE rcl.id IS NOT NULL $addrole
3256 ORDER BY sortorder DESC";
3258 $roles = $DB->get_records_sql_menu($sql, $params);
3259 $roles = role_fix_names($roles, $context, ROLENAME_BOTH);
3261 return $roles;
3265 * Return context levels where this role is assignable.
3266 * @param integer $roleid the id of a role.
3267 * @return array list of the context levels at which this role may be assigned.
3269 function get_role_contextlevels($roleid) {
3270 global $DB;
3271 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3272 'contextlevel', 'id,contextlevel');
3276 * Return roles suitable for assignment at the specified context level.
3278 * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3280 * @param integer $contextlevel a contextlevel.
3281 * @return array list of role ids that are assignable at this context level.
3283 function get_roles_for_contextlevels($contextlevel) {
3284 global $DB;
3285 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3286 '', 'id,roleid');
3290 * Returns default context levels where roles can be assigned.
3292 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3293 * from the array returned by get_role_archetypes();
3294 * @return array list of the context levels at which this type of role may be assigned by default.
3296 function get_default_contextlevels($rolearchetype) {
3297 static $defaults = array(
3298 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3299 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3300 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3301 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3302 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3303 'guest' => array(),
3304 'user' => array(),
3305 'frontpage' => array());
3307 if (isset($defaults[$rolearchetype])) {
3308 return $defaults[$rolearchetype];
3309 } else {
3310 return array();
3315 * Set the context levels at which a particular role can be assigned.
3316 * Throws exceptions in case of error.
3318 * @param integer $roleid the id of a role.
3319 * @param array $contextlevels the context levels at which this role should be assignable,
3320 * duplicate levels are removed.
3321 * @return void
3323 function set_role_contextlevels($roleid, array $contextlevels) {
3324 global $DB;
3325 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3326 $rcl = new stdClass();
3327 $rcl->roleid = $roleid;
3328 $contextlevels = array_unique($contextlevels);
3329 foreach ($contextlevels as $level) {
3330 $rcl->contextlevel = $level;
3331 $DB->insert_record('role_context_levels', $rcl, false, true);
3336 * Who has this capability in this context?
3338 * This can be a very expensive call - use sparingly and keep
3339 * the results if you are going to need them again soon.
3341 * Note if $fields is empty this function attempts to get u.*
3342 * which can get rather large - and has a serious perf impact
3343 * on some DBs.
3345 * @param context $context
3346 * @param string|array $capability - capability name(s)
3347 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3348 * @param string $sort - the sort order. Default is lastaccess time.
3349 * @param mixed $limitfrom - number of records to skip (offset)
3350 * @param mixed $limitnum - number of records to fetch
3351 * @param string|array $groups - single group or array of groups - only return
3352 * users who are in one of these group(s).
3353 * @param string|array $exceptions - list of users to exclude, comma separated or array
3354 * @param bool $doanything_ignored not used any more, admin accounts are never returned
3355 * @param bool $view_ignored - use get_enrolled_sql() instead
3356 * @param bool $useviewallgroups if $groups is set the return users who
3357 * have capability both $capability and moodle/site:accessallgroups
3358 * in this context, as well as users who have $capability and who are
3359 * in $groups.
3360 * @return mixed
3362 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3363 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3364 global $CFG, $DB;
3366 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3367 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3369 $ctxids = trim($context->path, '/');
3370 $ctxids = str_replace('/', ',', $ctxids);
3372 // Context is the frontpage
3373 $iscoursepage = false; // coursepage other than fp
3374 $isfrontpage = false;
3375 if ($context->contextlevel == CONTEXT_COURSE) {
3376 if ($context->instanceid == SITEID) {
3377 $isfrontpage = true;
3378 } else {
3379 $iscoursepage = true;
3382 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3384 $caps = (array)$capability;
3386 // construct list of context paths bottom-->top
3387 list($contextids, $paths) = get_context_info_list($context);
3389 // we need to find out all roles that have these capabilities either in definition or in overrides
3390 $defs = array();
3391 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3392 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3393 $params = array_merge($params, $params2);
3394 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3395 FROM {role_capabilities} rc
3396 JOIN {context} ctx on rc.contextid = ctx.id
3397 WHERE rc.contextid $incontexts AND rc.capability $incaps";
3399 $rcs = $DB->get_records_sql($sql, $params);
3400 foreach ($rcs as $rc) {
3401 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3404 // go through the permissions bottom-->top direction to evaluate the current permission,
3405 // first one wins (prohibit is an exception that always wins)
3406 $access = array();
3407 foreach ($caps as $cap) {
3408 foreach ($paths as $path) {
3409 if (empty($defs[$cap][$path])) {
3410 continue;
3412 foreach($defs[$cap][$path] as $roleid => $perm) {
3413 if ($perm == CAP_PROHIBIT) {
3414 $access[$cap][$roleid] = CAP_PROHIBIT;
3415 continue;
3417 if (!isset($access[$cap][$roleid])) {
3418 $access[$cap][$roleid] = (int)$perm;
3424 // make lists of roles that are needed and prohibited in this context
3425 $needed = array(); // one of these is enough
3426 $prohibited = array(); // must not have any of these
3427 foreach ($caps as $cap) {
3428 if (empty($access[$cap])) {
3429 continue;
3431 foreach ($access[$cap] as $roleid => $perm) {
3432 if ($perm == CAP_PROHIBIT) {
3433 unset($needed[$cap][$roleid]);
3434 $prohibited[$cap][$roleid] = true;
3435 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3436 $needed[$cap][$roleid] = true;
3439 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3440 // easy, nobody has the permission
3441 unset($needed[$cap]);
3442 unset($prohibited[$cap]);
3443 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3444 // everybody is disqualified on the frontapge
3445 unset($needed[$cap]);
3446 unset($prohibited[$cap]);
3448 if (empty($prohibited[$cap])) {
3449 unset($prohibited[$cap]);
3453 if (empty($needed)) {
3454 // there can not be anybody if no roles match this request
3455 return array();
3458 if (empty($prohibited)) {
3459 // we can compact the needed roles
3460 $n = array();
3461 foreach ($needed as $cap) {
3462 foreach ($cap as $roleid=>$unused) {
3463 $n[$roleid] = true;
3466 $needed = array('any'=>$n);
3467 unset($n);
3470 /// ***** Set up default fields ******
3471 if (empty($fields)) {
3472 if ($iscoursepage) {
3473 $fields = 'u.*, ul.timeaccess AS lastaccess';
3474 } else {
3475 $fields = 'u.*';
3477 } else {
3478 if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3479 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3483 /// Set up default sort
3484 if (empty($sort)) { // default to course lastaccess or just lastaccess
3485 if ($iscoursepage) {
3486 $sort = 'ul.timeaccess';
3487 } else {
3488 $sort = 'u.lastaccess';
3492 // Prepare query clauses
3493 $wherecond = array();
3494 $params = array();
3495 $joins = array();
3497 // User lastaccess JOIN
3498 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3499 // user_lastaccess is not required MDL-13810
3500 } else {
3501 if ($iscoursepage) {
3502 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3503 } else {
3504 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3508 /// We never return deleted users or guest account.
3509 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3510 $params['guestid'] = $CFG->siteguest;
3512 /// Groups
3513 if ($groups) {
3514 $groups = (array)$groups;
3515 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3516 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3517 $params = array_merge($params, $grpparams);
3519 if ($useviewallgroups) {
3520 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3521 if (!empty($viewallgroupsusers)) {
3522 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3523 } else {
3524 $wherecond[] = "($grouptest)";
3526 } else {
3527 $wherecond[] = "($grouptest)";
3531 /// User exceptions
3532 if (!empty($exceptions)) {
3533 $exceptions = (array)$exceptions;
3534 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3535 $params = array_merge($params, $exparams);
3536 $wherecond[] = "u.id $exsql";
3539 // now add the needed and prohibited roles conditions as joins
3540 if (!empty($needed['any'])) {
3541 // simple case - there are no prohibits involved
3542 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3543 // everybody
3544 } else {
3545 $joins[] = "JOIN (SELECT DISTINCT userid
3546 FROM {role_assignments}
3547 WHERE contextid IN ($ctxids)
3548 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3549 ) ra ON ra.userid = u.id";
3551 } else {
3552 $unions = array();
3553 $everybody = false;
3554 foreach ($needed as $cap=>$unused) {
3555 if (empty($prohibited[$cap])) {
3556 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3557 $everybody = true;
3558 break;
3559 } else {
3560 $unions[] = "SELECT userid
3561 FROM {role_assignments}
3562 WHERE contextid IN ($ctxids)
3563 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3565 } else {
3566 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3567 // nobody can have this cap because it is prevented in default roles
3568 continue;
3570 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3571 // everybody except the prohibitted - hiding does not matter
3572 $unions[] = "SELECT id AS userid
3573 FROM {user}
3574 WHERE id NOT IN (SELECT userid
3575 FROM {role_assignments}
3576 WHERE contextid IN ($ctxids)
3577 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3579 } else {
3580 $unions[] = "SELECT userid
3581 FROM {role_assignments}
3582 WHERE contextid IN ($ctxids)
3583 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3584 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3588 if (!$everybody) {
3589 if ($unions) {
3590 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3591 } else {
3592 // only prohibits found - nobody can be matched
3593 $wherecond[] = "1 = 2";
3598 // Collect WHERE conditions and needed joins
3599 $where = implode(' AND ', $wherecond);
3600 if ($where !== '') {
3601 $where = 'WHERE ' . $where;
3603 $joins = implode("\n", $joins);
3605 /// Ok, let's get the users!
3606 $sql = "SELECT $fields
3607 FROM {user} u
3608 $joins
3609 $where
3610 ORDER BY $sort";
3612 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3616 * Re-sort a users array based on a sorting policy
3618 * Will re-sort a $users results array (from get_users_by_capability(), usually)
3619 * based on a sorting policy. This is to support the odd practice of
3620 * sorting teachers by 'authority', where authority was "lowest id of the role
3621 * assignment".
3623 * Will execute 1 database query. Only suitable for small numbers of users, as it
3624 * uses an u.id IN() clause.
3626 * Notes about the sorting criteria.
3628 * As a default, we cannot rely on role.sortorder because then
3629 * admins/coursecreators will always win. That is why the sane
3630 * rule "is locality matters most", with sortorder as 2nd
3631 * consideration.
3633 * If you want role.sortorder, use the 'sortorder' policy, and
3634 * name explicitly what roles you want to cover. It's probably
3635 * a good idea to see what roles have the capabilities you want
3636 * (array_diff() them against roiles that have 'can-do-anything'
3637 * to weed out admin-ish roles. Or fetch a list of roles from
3638 * variables like $CFG->coursecontact .
3640 * @param array $users Users array, keyed on userid
3641 * @param context $context
3642 * @param array $roles ids of the roles to include, optional
3643 * @param string $sortpolicy defaults to locality, more about
3644 * @return array sorted copy of the array
3646 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3647 global $DB;
3649 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3650 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3651 if (empty($roles)) {
3652 $roleswhere = '';
3653 } else {
3654 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
3657 $sql = "SELECT ra.userid
3658 FROM {role_assignments} ra
3659 JOIN {role} r
3660 ON ra.roleid=r.id
3661 JOIN {context} ctx
3662 ON ra.contextid=ctx.id
3663 WHERE $userswhere
3664 $contextwhere
3665 $roleswhere";
3667 // Default 'locality' policy -- read PHPDoc notes
3668 // about sort policies...
3669 $orderby = 'ORDER BY '
3670 .'ctx.depth DESC, ' /* locality wins */
3671 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3672 .'ra.id'; /* role assignment order tie-breaker */
3673 if ($sortpolicy === 'sortorder') {
3674 $orderby = 'ORDER BY '
3675 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
3676 .'ra.id'; /* role assignment order tie-breaker */
3679 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
3680 $sortedusers = array();
3681 $seen = array();
3683 foreach ($sortedids as $id) {
3684 // Avoid duplicates
3685 if (isset($seen[$id])) {
3686 continue;
3688 $seen[$id] = true;
3690 // assign
3691 $sortedusers[$id] = $users[$id];
3693 return $sortedusers;
3697 * Gets all the users assigned this role in this context or higher
3699 * @param int $roleid (can also be an array of ints!)
3700 * @param context $context
3701 * @param bool $parent if true, get list of users assigned in higher context too
3702 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
3703 * @param string $sort sort from user (u.) , role assignment (ra) or role (r.)
3704 * @param bool $gethidden_ignored use enrolments instead
3705 * @param string $group defaults to ''
3706 * @param mixed $limitfrom defaults to ''
3707 * @param mixed $limitnum defaults to ''
3708 * @param string $extrawheretest defaults to ''
3709 * @param string|array $whereparams defaults to ''
3710 * @return array
3712 function get_role_users($roleid, context $context, $parent = false, $fields = '',
3713 $sort = 'u.lastname, u.firstname', $gethidden_ignored = null, $group = '',
3714 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereparams = array()) {
3715 global $DB;
3717 if (empty($fields)) {
3718 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3719 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
3720 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3721 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder';
3724 $parentcontexts = '';
3725 if ($parent) {
3726 $parentcontexts = substr($context->path, 1); // kill leading slash
3727 $parentcontexts = str_replace('/', ',', $parentcontexts);
3728 if ($parentcontexts !== '') {
3729 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
3733 if ($roleid) {
3734 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3735 $roleselect = "AND ra.roleid $rids";
3736 } else {
3737 $params = array();
3738 $roleselect = '';
3741 if ($group) {
3742 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
3743 $groupselect = " AND gm.groupid = ? ";
3744 $params[] = $group;
3745 } else {
3746 $groupjoin = '';
3747 $groupselect = '';
3750 array_unshift($params, $context->id);
3752 if ($extrawheretest) {
3753 $extrawheretest = ' AND ' . $extrawheretest;
3754 $params = array_merge($params, $whereparams);
3757 $sql = "SELECT DISTINCT $fields, ra.roleid
3758 FROM {role_assignments} ra
3759 JOIN {user} u ON u.id = ra.userid
3760 JOIN {role} r ON ra.roleid = r.id
3761 $groupjoin
3762 WHERE (ra.contextid = ? $parentcontexts)
3763 $roleselect
3764 $groupselect
3765 $extrawheretest
3766 ORDER BY $sort"; // join now so that we can just use fullname() later
3768 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3772 * Counts all the users assigned this role in this context or higher
3774 * @param int|array $roleid either int or an array of ints
3775 * @param context $context
3776 * @param bool $parent if true, get list of users assigned in higher context too
3777 * @return int Returns the result count
3779 function count_role_users($roleid, context $context, $parent = false) {
3780 global $DB;
3782 if ($parent) {
3783 if ($contexts = $context->get_parent_context_ids()) {
3784 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
3785 } else {
3786 $parentcontexts = '';
3788 } else {
3789 $parentcontexts = '';
3792 if ($roleid) {
3793 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
3794 $roleselect = "AND r.roleid $rids";
3795 } else {
3796 $params = array();
3797 $roleselect = '';
3800 array_unshift($params, $context->id);
3802 $sql = "SELECT COUNT(u.id)
3803 FROM {role_assignments} r
3804 JOIN {user} u ON u.id = r.userid
3805 WHERE (r.contextid = ? $parentcontexts)
3806 $roleselect
3807 AND u.deleted = 0";
3809 return $DB->count_records_sql($sql, $params);
3813 * This function gets the list of courses that this user has a particular capability in.
3814 * It is still not very efficient.
3816 * @param string $capability Capability in question
3817 * @param int $userid User ID or null for current user
3818 * @param bool $doanything True if 'doanything' is permitted (default)
3819 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
3820 * otherwise use a comma-separated list of the fields you require, not including id
3821 * @param string $orderby If set, use a comma-separated list of fields from course
3822 * table with sql modifiers (DESC) if needed
3823 * @return array Array of courses, may have zero entries. Or false if query failed.
3825 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
3826 global $DB;
3828 // Convert fields list and ordering
3829 $fieldlist = '';
3830 if ($fieldsexceptid) {
3831 $fields = explode(',', $fieldsexceptid);
3832 foreach($fields as $field) {
3833 $fieldlist .= ',c.'.$field;
3836 if ($orderby) {
3837 $fields = explode(',', $orderby);
3838 $orderby = '';
3839 foreach($fields as $field) {
3840 if ($orderby) {
3841 $orderby .= ',';
3843 $orderby .= 'c.'.$field;
3845 $orderby = 'ORDER BY '.$orderby;
3848 // Obtain a list of everything relevant about all courses including context.
3849 // Note the result can be used directly as a context (we are going to), the course
3850 // fields are just appended.
3852 $courses = array();
3853 $rs = $DB->get_recordset_sql("SELECT x.*, c.id AS courseid $fieldlist
3854 FROM {course} c
3855 INNER JOIN {context} x
3856 ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
3857 $orderby");
3858 // Check capability for each course in turn
3859 foreach ($rs as $coursecontext) {
3860 if (has_capability($capability, $coursecontext, $userid, $doanything)) {
3861 // We've got the capability. Make the record look like a course record
3862 // and store it
3863 $coursecontext->id = $coursecontext->courseid;
3864 unset($coursecontext->courseid);
3865 unset($coursecontext->contextlevel);
3866 unset($coursecontext->instanceid);
3867 $courses[] = $coursecontext;
3870 $rs->close();
3871 return empty($courses) ? false : $courses;
3875 * This function finds the roles assigned directly to this context only
3876 * i.e. no roles in parent contexts
3878 * @param context $context
3879 * @return array
3881 function get_roles_on_exact_context(context $context) {
3882 global $DB;
3884 return $DB->get_records_sql("SELECT r.*
3885 FROM {role_assignments} ra, {role} r
3886 WHERE ra.roleid = r.id AND ra.contextid = ?",
3887 array($context->id));
3891 * Switches the current user to another role for the current session and only
3892 * in the given context.
3894 * The caller *must* check
3895 * - that this op is allowed
3896 * - that the requested role can be switched to in this context (use get_switchable_roles)
3897 * - that the requested role is NOT $CFG->defaultuserroleid
3899 * To "unswitch" pass 0 as the roleid.
3901 * This function *will* modify $USER->access - beware
3903 * @param integer $roleid the role to switch to.
3904 * @param context $context the context in which to perform the switch.
3905 * @return bool success or failure.
3907 function role_switch($roleid, context $context) {
3908 global $USER;
3911 // Plan of action
3913 // - Add the ghost RA to $USER->access
3914 // as $USER->access['rsw'][$path] = $roleid
3916 // - Make sure $USER->access['rdef'] has the roledefs
3917 // it needs to honour the switcherole
3919 // Roledefs will get loaded "deep" here - down to the last child
3920 // context. Note that
3922 // - When visiting subcontexts, our selective accessdata loading
3923 // will still work fine - though those ra/rdefs will be ignored
3924 // appropriately while the switch is in place
3926 // - If a switcherole happens at a category with tons of courses
3927 // (that have many overrides for switched-to role), the session
3928 // will get... quite large. Sometimes you just can't win.
3930 // To un-switch just unset($USER->access['rsw'][$path])
3932 // Note: it is not possible to switch to roles that do not have course:view
3934 // Add the switch RA
3935 if (!isset($USER->access['rsw'])) {
3936 $USER->access['rsw'] = array();
3939 if ($roleid == 0) {
3940 unset($USER->access['rsw'][$context->path]);
3941 if (empty($USER->access['rsw'])) {
3942 unset($USER->access['rsw']);
3944 return true;
3947 $USER->access['rsw'][$context->path] = $roleid;
3949 // Load roledefs
3950 load_role_access_by_context($roleid, $context, $USER->access);
3952 return true;
3956 * Checks if the user has switched roles within the given course.
3958 * Note: You can only switch roles within the course, hence it takes a courseid
3959 * rather than a context. On that note Petr volunteered to implement this across
3960 * all other contexts, all requests for this should be forwarded to him ;)
3962 * @param int $courseid The id of the course to check
3963 * @return bool True if the user has switched roles within the course.
3965 function is_role_switched($courseid) {
3966 global $USER;
3967 $context = context_course::instance($courseid, MUST_EXIST);
3968 return (!empty($USER->access['rsw'][$context->path]));
3972 * Get any role that has an override on exact context
3974 * @param context $context The context to check
3975 * @return array An array of roles
3977 function get_roles_with_override_on_context(context $context) {
3978 global $DB;
3980 return $DB->get_records_sql("SELECT r.*
3981 FROM {role_capabilities} rc, {role} r
3982 WHERE rc.roleid = r.id AND rc.contextid = ?",
3983 array($context->id));
3987 * Get all capabilities for this role on this context (overrides)
3989 * @param stdClass $role
3990 * @param context $context
3991 * @return array
3993 function get_capabilities_from_role_on_context($role, context $context) {
3994 global $DB;
3996 return $DB->get_records_sql("SELECT *
3997 FROM {role_capabilities}
3998 WHERE contextid = ? AND roleid = ?",
3999 array($context->id, $role->id));
4003 * Find out which roles has assignment on this context
4005 * @param context $context
4006 * @return array
4009 function get_roles_with_assignment_on_context(context $context) {
4010 global $DB;
4012 return $DB->get_records_sql("SELECT r.*
4013 FROM {role_assignments} ra, {role} r
4014 WHERE ra.roleid = r.id AND ra.contextid = ?",
4015 array($context->id));
4019 * Find all user assignment of users for this role, on this context
4021 * @param stdClass $role
4022 * @param context $context
4023 * @return array
4025 function get_users_from_role_on_context($role, context $context) {
4026 global $DB;
4028 return $DB->get_records_sql("SELECT *
4029 FROM {role_assignments}
4030 WHERE contextid = ? AND roleid = ?",
4031 array($context->id, $role->id));
4035 * Simple function returning a boolean true if user has roles
4036 * in context or parent contexts, otherwise false.
4038 * @param int $userid
4039 * @param int $roleid
4040 * @param int $contextid empty means any context
4041 * @return bool
4043 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
4044 global $DB;
4046 if ($contextid) {
4047 if (!$context = context::instance_by_id($contextid, IGNORE_MISSING)) {
4048 return false;
4050 $parents = $context->get_parent_context_ids(true);
4051 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
4052 $params['userid'] = $userid;
4053 $params['roleid'] = $roleid;
4055 $sql = "SELECT COUNT(ra.id)
4056 FROM {role_assignments} ra
4057 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
4059 $count = $DB->get_field_sql($sql, $params);
4060 return ($count > 0);
4062 } else {
4063 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
4068 * Get role name or alias if exists and format the text.
4070 * @param stdClass $role role object
4071 * @param context_course $coursecontext
4072 * @return string name of role in course context
4074 function role_get_name($role, context_course $coursecontext) {
4075 global $DB;
4077 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
4078 return strip_tags(format_string($r->name));
4079 } else {
4080 return strip_tags(format_string($role->name));
4085 * Prepare list of roles for display, apply aliases and format text
4087 * @param array $roleoptions array roleid => rolename or roleid => roleobject
4088 * @param context $context a context
4089 * @param int $rolenamedisplay
4090 * @return array Array of context-specific role names, or role objexts with a ->localname field added.
4092 function role_fix_names($roleoptions, context $context, $rolenamedisplay = ROLENAME_ALIAS) {
4093 global $DB;
4095 // Make sure we have a course context.
4096 $coursecontext = $context->get_course_context(false);
4098 // Make sure we are working with an array roleid => name. Normally we
4099 // want to use the unlocalised name if the localised one is not present.
4100 $newnames = array();
4101 foreach ($roleoptions as $rid => $roleorname) {
4102 if ($rolenamedisplay != ROLENAME_ALIAS_RAW) {
4103 if (is_object($roleorname)) {
4104 $newnames[$rid] = $roleorname->name;
4105 } else {
4106 $newnames[$rid] = $roleorname;
4108 } else {
4109 $newnames[$rid] = '';
4113 // If necessary, get the localised names.
4114 if ($rolenamedisplay != ROLENAME_ORIGINAL && !empty($coursecontext->id)) {
4115 // The get the relevant renames, and use them.
4116 $aliasnames = $DB->get_records('role_names', array('contextid'=>$coursecontext->id));
4117 foreach ($aliasnames as $alias) {
4118 if (isset($newnames[$alias->roleid])) {
4119 if ($rolenamedisplay == ROLENAME_ALIAS || $rolenamedisplay == ROLENAME_ALIAS_RAW) {
4120 $newnames[$alias->roleid] = $alias->name;
4121 } else if ($rolenamedisplay == ROLENAME_BOTH) {
4122 $newnames[$alias->roleid] = $alias->name . ' (' . $roleoptions[$alias->roleid] . ')';
4128 // Finally, apply format_string and put the result in the right place.
4129 foreach ($roleoptions as $rid => $roleorname) {
4130 if ($rolenamedisplay != ROLENAME_ALIAS_RAW) {
4131 $newnames[$rid] = strip_tags(format_string($newnames[$rid]));
4133 if (is_object($roleorname)) {
4134 $roleoptions[$rid]->localname = $newnames[$rid];
4135 } else {
4136 $roleoptions[$rid] = $newnames[$rid];
4139 return $roleoptions;
4143 * Aids in detecting if a new line is required when reading a new capability
4145 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
4146 * when we read in a new capability.
4147 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
4148 * but when we are in grade, all reports/import/export capabilities should be together
4150 * @param string $cap component string a
4151 * @param string $comp component string b
4152 * @param int $contextlevel
4153 * @return bool whether 2 component are in different "sections"
4155 function component_level_changed($cap, $comp, $contextlevel) {
4157 if (strstr($cap->component, '/') && strstr($comp, '/')) {
4158 $compsa = explode('/', $cap->component);
4159 $compsb = explode('/', $comp);
4161 // list of system reports
4162 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
4163 return false;
4166 // we are in gradebook, still
4167 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
4168 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
4169 return false;
4172 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
4173 return false;
4177 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
4181 * Fix the roles.sortorder field in the database, so it contains sequential integers,
4182 * and return an array of roleids in order.
4184 * @param array $allroles array of roles, as returned by get_all_roles();
4185 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
4187 function fix_role_sortorder($allroles) {
4188 global $DB;
4190 $rolesort = array();
4191 $i = 0;
4192 foreach ($allroles as $role) {
4193 $rolesort[$i] = $role->id;
4194 if ($role->sortorder != $i) {
4195 $r = new stdClass();
4196 $r->id = $role->id;
4197 $r->sortorder = $i;
4198 $DB->update_record('role', $r);
4199 $allroles[$role->id]->sortorder = $i;
4201 $i++;
4203 return $rolesort;
4207 * Switch the sort order of two roles (used in admin/roles/manage.php).
4209 * @param object $first The first role. Actually, only ->sortorder is used.
4210 * @param object $second The second role. Actually, only ->sortorder is used.
4211 * @return boolean success or failure
4213 function switch_roles($first, $second) {
4214 global $DB;
4215 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
4216 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
4217 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
4218 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
4219 return $result;
4223 * Duplicates all the base definitions of a role
4225 * @param object $sourcerole role to copy from
4226 * @param int $targetrole id of role to copy to
4228 function role_cap_duplicate($sourcerole, $targetrole) {
4229 global $DB;
4231 $systemcontext = context_system::instance();
4232 $caps = $DB->get_records_sql("SELECT *
4233 FROM {role_capabilities}
4234 WHERE roleid = ? AND contextid = ?",
4235 array($sourcerole->id, $systemcontext->id));
4236 // adding capabilities
4237 foreach ($caps as $cap) {
4238 unset($cap->id);
4239 $cap->roleid = $targetrole;
4240 $DB->insert_record('role_capabilities', $cap);
4245 * Returns two lists, this can be used to find out if user has capability.
4246 * Having any needed role and no forbidden role in this context means
4247 * user has this capability in this context.
4248 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
4250 * @param object $context
4251 * @param string $capability
4252 * @return array($neededroles, $forbiddenroles)
4254 function get_roles_with_cap_in_context($context, $capability) {
4255 global $DB;
4257 $ctxids = trim($context->path, '/'); // kill leading slash
4258 $ctxids = str_replace('/', ',', $ctxids);
4260 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
4261 FROM {role_capabilities} rc
4262 JOIN {context} ctx ON ctx.id = rc.contextid
4263 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
4264 ORDER BY rc.roleid ASC, ctx.depth DESC";
4265 $params = array('cap'=>$capability);
4267 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
4268 // no cap definitions --> no capability
4269 return array(array(), array());
4272 $forbidden = array();
4273 $needed = array();
4274 foreach($capdefs as $def) {
4275 if (isset($forbidden[$def->roleid])) {
4276 continue;
4278 if ($def->permission == CAP_PROHIBIT) {
4279 $forbidden[$def->roleid] = $def->roleid;
4280 unset($needed[$def->roleid]);
4281 continue;
4283 if (!isset($needed[$def->roleid])) {
4284 if ($def->permission == CAP_ALLOW) {
4285 $needed[$def->roleid] = true;
4286 } else if ($def->permission == CAP_PREVENT) {
4287 $needed[$def->roleid] = false;
4291 unset($capdefs);
4293 // remove all those roles not allowing
4294 foreach($needed as $key=>$value) {
4295 if (!$value) {
4296 unset($needed[$key]);
4297 } else {
4298 $needed[$key] = $key;
4302 return array($needed, $forbidden);
4306 * Returns an array of role IDs that have ALL of the the supplied capabilities
4307 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
4309 * @param object $context
4310 * @param array $capabilities An array of capabilities
4311 * @return array of roles with all of the required capabilities
4313 function get_roles_with_caps_in_context($context, $capabilities) {
4314 $neededarr = array();
4315 $forbiddenarr = array();
4316 foreach($capabilities as $caprequired) {
4317 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
4320 $rolesthatcanrate = array();
4321 if (!empty($neededarr)) {
4322 foreach ($neededarr as $needed) {
4323 if (empty($rolesthatcanrate)) {
4324 $rolesthatcanrate = $needed;
4325 } else {
4326 //only want roles that have all caps
4327 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
4331 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
4332 foreach ($forbiddenarr as $forbidden) {
4333 //remove any roles that are forbidden any of the caps
4334 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
4337 return $rolesthatcanrate;
4341 * Returns an array of role names that have ALL of the the supplied capabilities
4342 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
4344 * @param object $context
4345 * @param array $capabilities An array of capabilities
4346 * @return array of roles with all of the required capabilities
4348 function get_role_names_with_caps_in_context($context, $capabilities) {
4349 global $DB;
4351 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
4353 $allroles = array();
4354 $roles = $DB->get_records('role', null, 'sortorder DESC');
4355 foreach ($roles as $roleid=>$role) {
4356 $allroles[$roleid] = $role->name;
4359 $rolenames = array();
4360 foreach ($rolesthatcanrate as $r) {
4361 $rolenames[$r] = $allroles[$r];
4363 $rolenames = role_fix_names($rolenames, $context);
4364 return $rolenames;
4368 * This function verifies the prohibit comes from this context
4369 * and there are no more prohibits in parent contexts.
4371 * @param int $roleid
4372 * @param context $context
4373 * @param string $capability name
4374 * @return bool
4376 function prohibit_is_removable($roleid, context $context, $capability) {
4377 global $DB;
4379 $ctxids = trim($context->path, '/'); // kill leading slash
4380 $ctxids = str_replace('/', ',', $ctxids);
4382 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
4384 $sql = "SELECT ctx.id
4385 FROM {role_capabilities} rc
4386 JOIN {context} ctx ON ctx.id = rc.contextid
4387 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
4388 ORDER BY ctx.depth DESC";
4390 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
4391 // no prohibits == nothing to remove
4392 return true;
4395 if (count($prohibits) > 1) {
4396 // more prohibints can not be removed
4397 return false;
4400 return !empty($prohibits[$context->id]);
4404 * More user friendly role permission changing,
4405 * it should produce as few overrides as possible.
4406 * @param int $roleid
4407 * @param object $context
4408 * @param string $capname capability name
4409 * @param int $permission
4410 * @return void
4412 function role_change_permission($roleid, $context, $capname, $permission) {
4413 global $DB;
4415 if ($permission == CAP_INHERIT) {
4416 unassign_capability($capname, $roleid, $context->id);
4417 $context->mark_dirty();
4418 return;
4421 $ctxids = trim($context->path, '/'); // kill leading slash
4422 $ctxids = str_replace('/', ',', $ctxids);
4424 $params = array('roleid'=>$roleid, 'cap'=>$capname);
4426 $sql = "SELECT ctx.id, rc.permission, ctx.depth
4427 FROM {role_capabilities} rc
4428 JOIN {context} ctx ON ctx.id = rc.contextid
4429 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
4430 ORDER BY ctx.depth DESC";
4432 if ($existing = $DB->get_records_sql($sql, $params)) {
4433 foreach($existing as $e) {
4434 if ($e->permission == CAP_PROHIBIT) {
4435 // prohibit can not be overridden, no point in changing anything
4436 return;
4439 $lowest = array_shift($existing);
4440 if ($lowest->permission == $permission) {
4441 // permission already set in this context or parent - nothing to do
4442 return;
4444 if ($existing) {
4445 $parent = array_shift($existing);
4446 if ($parent->permission == $permission) {
4447 // permission already set in parent context or parent - just unset in this context
4448 // we do this because we want as few overrides as possible for performance reasons
4449 unassign_capability($capname, $roleid, $context->id);
4450 $context->mark_dirty();
4451 return;
4455 } else {
4456 if ($permission == CAP_PREVENT) {
4457 // nothing means role does not have permission
4458 return;
4462 // assign the needed capability
4463 assign_capability($capname, $permission, $roleid, $context->id, true);
4465 // force cap reloading
4466 $context->mark_dirty();
4471 * Basic moodle context abstraction class.
4473 * @author Petr Skoda
4474 * @since 2.2
4476 * @property-read int $id context id
4477 * @property-read int $contextlevel CONTEXT_SYSTEM, CONTEXT_COURSE, etc.
4478 * @property-read int $instanceid id of related instance in each context
4479 * @property-read string $path path to context, starts with system context
4480 * @property-read dept $depth
4482 abstract class context extends stdClass {
4485 * Google confirms that no other important framework is using "context" class,
4486 * we could use something else like mcontext or moodle_context, but we need to type
4487 * this very often which would be annoying and it would take too much space...
4489 * This class is derived from stdClass for backwards compatibility with
4490 * odl $context record that was returned from DML $DB->get_record()
4493 protected $_id;
4494 protected $_contextlevel;
4495 protected $_instanceid;
4496 protected $_path;
4497 protected $_depth;
4499 /* context caching info */
4501 private static $cache_contextsbyid = array();
4502 private static $cache_contexts = array();
4503 protected static $cache_count = 0; // why do we do count contexts? Because count($array) is horribly slow for large arrays
4505 protected static $cache_preloaded = array();
4506 protected static $systemcontext = null;
4509 * Resets the cache to remove all data.
4510 * @static
4512 protected static function reset_caches() {
4513 self::$cache_contextsbyid = array();
4514 self::$cache_contexts = array();
4515 self::$cache_count = 0;
4516 self::$cache_preloaded = array();
4518 self::$systemcontext = null;
4522 * Adds a context to the cache. If the cache is full, discards a batch of
4523 * older entries.
4525 * @static
4526 * @param context $context New context to add
4527 * @return void
4529 protected static function cache_add(context $context) {
4530 if (isset(self::$cache_contextsbyid[$context->id])) {
4531 // already cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4532 return;
4535 if (self::$cache_count >= CONTEXT_CACHE_MAX_SIZE) {
4536 $i = 0;
4537 foreach(self::$cache_contextsbyid as $ctx) {
4538 $i++;
4539 if ($i <= 100) {
4540 // we want to keep the first contexts to be loaded on this page, hopefully they will be needed again later
4541 continue;
4543 if ($i > (CONTEXT_CACHE_MAX_SIZE / 3)) {
4544 // we remove oldest third of the contexts to make room for more contexts
4545 break;
4547 unset(self::$cache_contextsbyid[$ctx->id]);
4548 unset(self::$cache_contexts[$ctx->contextlevel][$ctx->instanceid]);
4549 self::$cache_count--;
4553 self::$cache_contexts[$context->contextlevel][$context->instanceid] = $context;
4554 self::$cache_contextsbyid[$context->id] = $context;
4555 self::$cache_count++;
4559 * Removes a context from the cache.
4561 * @static
4562 * @param context $context Context object to remove
4563 * @return void
4565 protected static function cache_remove(context $context) {
4566 if (!isset(self::$cache_contextsbyid[$context->id])) {
4567 // not cached, no need to do anything - this is relatively cheap, we do all this because count() is slow
4568 return;
4570 unset(self::$cache_contexts[$context->contextlevel][$context->instanceid]);
4571 unset(self::$cache_contextsbyid[$context->id]);
4573 self::$cache_count--;
4575 if (self::$cache_count < 0) {
4576 self::$cache_count = 0;
4581 * Gets a context from the cache.
4583 * @static
4584 * @param int $contextlevel Context level
4585 * @param int $instance Instance ID
4586 * @return context|bool Context or false if not in cache
4588 protected static function cache_get($contextlevel, $instance) {
4589 if (isset(self::$cache_contexts[$contextlevel][$instance])) {
4590 return self::$cache_contexts[$contextlevel][$instance];
4592 return false;
4596 * Gets a context from the cache based on its id.
4598 * @static
4599 * @param int $id Context ID
4600 * @return context|bool Context or false if not in cache
4602 protected static function cache_get_by_id($id) {
4603 if (isset(self::$cache_contextsbyid[$id])) {
4604 return self::$cache_contextsbyid[$id];
4606 return false;
4610 * Preloads context information from db record and strips the cached info.
4612 * @static
4613 * @param stdClass $rec
4614 * @return void (modifies $rec)
4616 protected static function preload_from_record(stdClass $rec) {
4617 if (empty($rec->ctxid) or empty($rec->ctxlevel) or empty($rec->ctxinstance) or empty($rec->ctxpath) or empty($rec->ctxdepth)) {
4618 // $rec does not have enough data, passed here repeatedly or context does not exist yet
4619 return;
4622 // note: in PHP5 the objects are passed by reference, no need to return $rec
4623 $record = new stdClass();
4624 $record->id = $rec->ctxid; unset($rec->ctxid);
4625 $record->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
4626 $record->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
4627 $record->path = $rec->ctxpath; unset($rec->ctxpath);
4628 $record->depth = $rec->ctxdepth; unset($rec->ctxdepth);
4630 return context::create_instance_from_record($record);
4634 // ====== magic methods =======
4637 * Magic setter method, we do not want anybody to modify properties from the outside
4638 * @param string $name
4639 * @param mixed @value
4641 public function __set($name, $value) {
4642 debugging('Can not change context instance properties!');
4646 * Magic method getter, redirects to read only values.
4647 * @param string $name
4648 * @return mixed
4650 public function __get($name) {
4651 switch ($name) {
4652 case 'id': return $this->_id;
4653 case 'contextlevel': return $this->_contextlevel;
4654 case 'instanceid': return $this->_instanceid;
4655 case 'path': return $this->_path;
4656 case 'depth': return $this->_depth;
4658 default:
4659 debugging('Invalid context property accessed! '.$name);
4660 return null;
4665 * Full support for isset on our magic read only properties.
4666 * @param $name
4667 * @return bool
4669 public function __isset($name) {
4670 switch ($name) {
4671 case 'id': return isset($this->_id);
4672 case 'contextlevel': return isset($this->_contextlevel);
4673 case 'instanceid': return isset($this->_instanceid);
4674 case 'path': return isset($this->_path);
4675 case 'depth': return isset($this->_depth);
4677 default: return false;
4683 * ALl properties are read only, sorry.
4684 * @param string $name
4686 public function __unset($name) {
4687 debugging('Can not unset context instance properties!');
4690 // ====== general context methods ======
4693 * Constructor is protected so that devs are forced to
4694 * use context_xxx::instance() or context::instance_by_id().
4696 * @param stdClass $record
4698 protected function __construct(stdClass $record) {
4699 $this->_id = $record->id;
4700 $this->_contextlevel = (int)$record->contextlevel;
4701 $this->_instanceid = $record->instanceid;
4702 $this->_path = $record->path;
4703 $this->_depth = $record->depth;
4707 * This function is also used to work around 'protected' keyword problems in context_helper.
4708 * @static
4709 * @param stdClass $record
4710 * @return context instance
4712 protected static function create_instance_from_record(stdClass $record) {
4713 $classname = context_helper::get_class_for_level($record->contextlevel);
4715 if ($context = context::cache_get_by_id($record->id)) {
4716 return $context;
4719 $context = new $classname($record);
4720 context::cache_add($context);
4722 return $context;
4726 * Copy prepared new contexts from temp table to context table,
4727 * we do this in db specific way for perf reasons only.
4728 * @static
4730 protected static function merge_context_temp_table() {
4731 global $DB;
4733 /* MDL-11347:
4734 * - mysql does not allow to use FROM in UPDATE statements
4735 * - using two tables after UPDATE works in mysql, but might give unexpected
4736 * results in pg 8 (depends on configuration)
4737 * - using table alias in UPDATE does not work in pg < 8.2
4739 * Different code for each database - mostly for performance reasons
4742 $dbfamily = $DB->get_dbfamily();
4743 if ($dbfamily == 'mysql') {
4744 $updatesql = "UPDATE {context} ct, {context_temp} temp
4745 SET ct.path = temp.path,
4746 ct.depth = temp.depth
4747 WHERE ct.id = temp.id";
4748 } else if ($dbfamily == 'oracle') {
4749 $updatesql = "UPDATE {context} ct
4750 SET (ct.path, ct.depth) =
4751 (SELECT temp.path, temp.depth
4752 FROM {context_temp} temp
4753 WHERE temp.id=ct.id)
4754 WHERE EXISTS (SELECT 'x'
4755 FROM {context_temp} temp
4756 WHERE temp.id = ct.id)";
4757 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
4758 $updatesql = "UPDATE {context}
4759 SET path = temp.path,
4760 depth = temp.depth
4761 FROM {context_temp} temp
4762 WHERE temp.id={context}.id";
4763 } else {
4764 // sqlite and others
4765 $updatesql = "UPDATE {context}
4766 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
4767 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
4768 WHERE id IN (SELECT id FROM {context_temp})";
4771 $DB->execute($updatesql);
4775 * Get a context instance as an object, from a given context id.
4777 * @static
4778 * @param int $id context id
4779 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
4780 * MUST_EXIST means throw exception if no record found
4781 * @return context|bool the context object or false if not found
4783 public static function instance_by_id($id, $strictness = MUST_EXIST) {
4784 global $DB;
4786 if (get_called_class() !== 'context' and get_called_class() !== 'context_helper') {
4787 // some devs might confuse context->id and instanceid, better prevent these mistakes completely
4788 throw new coding_exception('use only context::instance_by_id() for real context levels use ::instance() methods');
4791 if ($id == SYSCONTEXTID) {
4792 return context_system::instance(0, $strictness);
4795 if (is_array($id) or is_object($id) or empty($id)) {
4796 throw new coding_exception('Invalid context id specified context::instance_by_id()');
4799 if ($context = context::cache_get_by_id($id)) {
4800 return $context;
4803 if ($record = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
4804 return context::create_instance_from_record($record);
4807 return false;
4811 * Update context info after moving context in the tree structure.
4813 * @param context $newparent
4814 * @return void
4816 public function update_moved(context $newparent) {
4817 global $DB;
4819 $frompath = $this->_path;
4820 $newpath = $newparent->path . '/' . $this->_id;
4822 $trans = $DB->start_delegated_transaction();
4824 $this->mark_dirty();
4826 $setdepth = '';
4827 if (($newparent->depth +1) != $this->_depth) {
4828 $diff = $newparent->depth - $this->_depth + 1;
4829 $setdepth = ", depth = depth + $diff";
4831 $sql = "UPDATE {context}
4832 SET path = ?
4833 $setdepth
4834 WHERE id = ?";
4835 $params = array($newpath, $this->_id);
4836 $DB->execute($sql, $params);
4838 $this->_path = $newpath;
4839 $this->_depth = $newparent->depth + 1;
4841 $sql = "UPDATE {context}
4842 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
4843 $setdepth
4844 WHERE path LIKE ?";
4845 $params = array($newpath, "{$frompath}/%");
4846 $DB->execute($sql, $params);
4848 $this->mark_dirty();
4850 context::reset_caches();
4852 $trans->allow_commit();
4856 * Remove all context path info and optionally rebuild it.
4858 * @param bool $rebuild
4859 * @return void
4861 public function reset_paths($rebuild = true) {
4862 global $DB;
4864 if ($this->_path) {
4865 $this->mark_dirty();
4867 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$this->_id/%'");
4868 $DB->set_field_select('context', 'path', NULL, "path LIKE '%/$this->_id/%'");
4869 if ($this->_contextlevel != CONTEXT_SYSTEM) {
4870 $DB->set_field('context', 'depth', 0, array('id'=>$this->_id));
4871 $DB->set_field('context', 'path', NULL, array('id'=>$this->_id));
4872 $this->_depth = 0;
4873 $this->_path = null;
4876 if ($rebuild) {
4877 context_helper::build_all_paths(false);
4880 context::reset_caches();
4884 * Delete all data linked to content, do not delete the context record itself
4886 public function delete_content() {
4887 global $CFG, $DB;
4889 blocks_delete_all_for_context($this->_id);
4890 filter_delete_all_for_context($this->_id);
4892 require_once($CFG->dirroot . '/comment/lib.php');
4893 comment::delete_comments(array('contextid'=>$this->_id));
4895 require_once($CFG->dirroot.'/rating/lib.php');
4896 $delopt = new stdclass();
4897 $delopt->contextid = $this->_id;
4898 $rm = new rating_manager();
4899 $rm->delete_ratings($delopt);
4901 // delete all files attached to this context
4902 $fs = get_file_storage();
4903 $fs->delete_area_files($this->_id);
4905 // delete all advanced grading data attached to this context
4906 require_once($CFG->dirroot.'/grade/grading/lib.php');
4907 grading_manager::delete_all_for_context($this->_id);
4909 // now delete stuff from role related tables, role_unassign_all
4910 // and unenrol should be called earlier to do proper cleanup
4911 $DB->delete_records('role_assignments', array('contextid'=>$this->_id));
4912 $DB->delete_records('role_capabilities', array('contextid'=>$this->_id));
4913 $DB->delete_records('role_names', array('contextid'=>$this->_id));
4917 * Delete the context content and the context record itself
4919 public function delete() {
4920 global $DB;
4922 // double check the context still exists
4923 if (!$DB->record_exists('context', array('id'=>$this->_id))) {
4924 context::cache_remove($this);
4925 return;
4928 $this->delete_content();
4929 $DB->delete_records('context', array('id'=>$this->_id));
4930 // purge static context cache if entry present
4931 context::cache_remove($this);
4933 // do not mark dirty contexts if parents unknown
4934 if (!is_null($this->_path) and $this->_depth > 0) {
4935 $this->mark_dirty();
4939 // ====== context level related methods ======
4942 * Utility method for context creation
4944 * @static
4945 * @param int $contextlevel
4946 * @param int $instanceid
4947 * @param string $parentpath
4948 * @return stdClass context record
4950 protected static function insert_context_record($contextlevel, $instanceid, $parentpath) {
4951 global $DB;
4953 $record = new stdClass();
4954 $record->contextlevel = $contextlevel;
4955 $record->instanceid = $instanceid;
4956 $record->depth = 0;
4957 $record->path = null; //not known before insert
4959 $record->id = $DB->insert_record('context', $record);
4961 // now add path if known - it can be added later
4962 if (!is_null($parentpath)) {
4963 $record->path = $parentpath.'/'.$record->id;
4964 $record->depth = substr_count($record->path, '/');
4965 $DB->update_record('context', $record);
4968 return $record;
4972 * Returns human readable context level name.
4974 * @static
4975 * @return string the human readable context level name.
4977 protected static function get_level_name() {
4978 // must be implemented in all context levels
4979 throw new coding_exception('can not get level name of abstract context');
4983 * Returns human readable context identifier.
4985 * @param boolean $withprefix whether to prefix the name of the context with the
4986 * type of context, e.g. User, Course, Forum, etc.
4987 * @param boolean $short whether to use the short name of the thing. Only applies
4988 * to course contexts
4989 * @return string the human readable context name.
4991 public function get_context_name($withprefix = true, $short = false) {
4992 // must be implemented in all context levels
4993 throw new coding_exception('can not get name of abstract context');
4997 * Returns the most relevant URL for this context.
4999 * @return moodle_url
5001 public abstract function get_url();
5004 * Returns array of relevant context capability records.
5006 * @return array
5008 public abstract function get_capabilities();
5011 * Recursive function which, given a context, find all its children context ids.
5013 * For course category contexts it will return immediate children and all subcategory contexts.
5014 * It will NOT recurse into courses or subcategories categories.
5015 * If you want to do that, call it on the returned courses/categories.
5017 * When called for a course context, it will return the modules and blocks
5018 * displayed in the course page and blocks displayed on the module pages.
5020 * If called on a user/course/module context it _will_ populate the cache with the appropriate
5021 * contexts ;-)
5023 * @return array Array of child records
5025 public function get_child_contexts() {
5026 global $DB;
5028 $sql = "SELECT ctx.*
5029 FROM {context} ctx
5030 WHERE ctx.path LIKE ?";
5031 $params = array($this->_path.'/%');
5032 $records = $DB->get_records_sql($sql, $params);
5034 $result = array();
5035 foreach ($records as $record) {
5036 $result[$record->id] = context::create_instance_from_record($record);
5039 return $result;
5043 * Returns parent contexts of this context in reversed order, i.e. parent first,
5044 * then grand parent, etc.
5046 * @param bool $includeself tre means include self too
5047 * @return array of context instances
5049 public function get_parent_contexts($includeself = false) {
5050 if (!$contextids = $this->get_parent_context_ids($includeself)) {
5051 return array();
5054 $result = array();
5055 foreach ($contextids as $contextid) {
5056 $parent = context::instance_by_id($contextid, MUST_EXIST);
5057 $result[$parent->id] = $parent;
5060 return $result;
5064 * Returns parent contexts of this context in reversed order, i.e. parent first,
5065 * then grand parent, etc.
5067 * @param bool $includeself tre means include self too
5068 * @return array of context ids
5070 public function get_parent_context_ids($includeself = false) {
5071 if (empty($this->_path)) {
5072 return array();
5075 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5076 $parentcontexts = explode('/', $parentcontexts);
5077 if (!$includeself) {
5078 array_pop($parentcontexts); // and remove its own id
5081 return array_reverse($parentcontexts);
5085 * Returns parent context
5087 * @return context
5089 public function get_parent_context() {
5090 if (empty($this->_path) or $this->_id == SYSCONTEXTID) {
5091 return false;
5094 $parentcontexts = trim($this->_path, '/'); // kill leading slash
5095 $parentcontexts = explode('/', $parentcontexts);
5096 array_pop($parentcontexts); // self
5097 $contextid = array_pop($parentcontexts); // immediate parent
5099 return context::instance_by_id($contextid, MUST_EXIST);
5103 * Is this context part of any course? If yes return course context.
5105 * @param bool $strict true means throw exception if not found, false means return false if not found
5106 * @return course_context context of the enclosing course, null if not found or exception
5108 public function get_course_context($strict = true) {
5109 if ($strict) {
5110 throw new coding_exception('Context does not belong to any course.');
5111 } else {
5112 return false;
5117 * Returns sql necessary for purging of stale context instances.
5119 * @static
5120 * @return string cleanup SQL
5122 protected static function get_cleanup_sql() {
5123 throw new coding_exception('get_cleanup_sql() method must be implemented in all context levels');
5127 * Rebuild context paths and depths at context level.
5129 * @static
5130 * @param $force
5131 * @return void
5133 protected static function build_paths($force) {
5134 throw new coding_exception('build_paths() method must be implemented in all context levels');
5138 * Create missing context instances at given level
5140 * @static
5141 * @return void
5143 protected static function create_level_instances() {
5144 throw new coding_exception('create_level_instances() method must be implemented in all context levels');
5148 * Reset all cached permissions and definitions if the necessary.
5149 * @return void
5151 public function reload_if_dirty() {
5152 global $ACCESSLIB_PRIVATE, $USER;
5154 // Load dirty contexts list if needed
5155 if (CLI_SCRIPT) {
5156 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5157 // we do not load dirty flags in CLI and cron
5158 $ACCESSLIB_PRIVATE->dirtycontexts = array();
5160 } else {
5161 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5162 if (!isset($USER->access['time'])) {
5163 // nothing was loaded yet, we do not need to check dirty contexts now
5164 return;
5166 // no idea why -2 is there, server cluster time difference maybe... (skodak)
5167 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5171 foreach ($ACCESSLIB_PRIVATE->dirtycontexts as $path=>$unused) {
5172 if ($path === $this->_path or strpos($this->_path, $path.'/') === 0) {
5173 // reload all capabilities of USER and others - preserving loginas, roleswitches, etc
5174 // and then cleanup any marks of dirtyness... at least from our short term memory! :-)
5175 reload_all_capabilities();
5176 break;
5182 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
5184 public function mark_dirty() {
5185 global $CFG, $USER, $ACCESSLIB_PRIVATE;
5187 if (during_initial_install()) {
5188 return;
5191 // only if it is a non-empty string
5192 if (is_string($this->_path) && $this->_path !== '') {
5193 set_cache_flag('accesslib/dirtycontexts', $this->_path, 1, time()+$CFG->sessiontimeout);
5194 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5195 $ACCESSLIB_PRIVATE->dirtycontexts[$this->_path] = 1;
5196 } else {
5197 if (CLI_SCRIPT) {
5198 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5199 } else {
5200 if (isset($USER->access['time'])) {
5201 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
5202 } else {
5203 $ACCESSLIB_PRIVATE->dirtycontexts = array($this->_path => 1);
5205 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
5214 * Context maintenance and helper methods.
5216 * This is "extends context" is a bloody hack that tires to work around the deficiencies
5217 * in the "protected" keyword in PHP, this helps us to hide all the internals of context
5218 * level implementation from the rest of code, the code completion returns what developers need.
5220 * Thank you Tim Hunt for helping me with this nasty trick.
5222 * @author Petr Skoda
5223 * @since 2.2
5225 class context_helper extends context {
5227 private static $alllevels = array(
5228 CONTEXT_SYSTEM => 'context_system',
5229 CONTEXT_USER => 'context_user',
5230 CONTEXT_COURSECAT => 'context_coursecat',
5231 CONTEXT_COURSE => 'context_course',
5232 CONTEXT_MODULE => 'context_module',
5233 CONTEXT_BLOCK => 'context_block',
5237 * Instance does not make sense here, only static use
5239 protected function __construct() {
5243 * Returns a class name of the context level class
5245 * @static
5246 * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
5247 * @return string class name of the context class
5249 public static function get_class_for_level($contextlevel) {
5250 if (isset(self::$alllevels[$contextlevel])) {
5251 return self::$alllevels[$contextlevel];
5252 } else {
5253 throw new coding_exception('Invalid context level specified');
5258 * Returns a list of all context levels
5260 * @static
5261 * @return array int=>string (level=>level class name)
5263 public static function get_all_levels() {
5264 return self::$alllevels;
5268 * Remove stale contexts that belonged to deleted instances.
5269 * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
5271 * @static
5272 * @return void
5274 public static function cleanup_instances() {
5275 global $DB;
5276 $sqls = array();
5277 foreach (self::$alllevels as $level=>$classname) {
5278 $sqls[] = $classname::get_cleanup_sql();
5281 $sql = implode(" UNION ", $sqls);
5283 // it is probably better to use transactions, it might be faster too
5284 $transaction = $DB->start_delegated_transaction();
5286 $rs = $DB->get_recordset_sql($sql);
5287 foreach ($rs as $record) {
5288 $context = context::create_instance_from_record($record);
5289 $context->delete();
5291 $rs->close();
5293 $transaction->allow_commit();
5297 * Create all context instances at the given level and above.
5299 * @static
5300 * @param int $contextlevel null means all levels
5301 * @param bool $buildpaths
5302 * @return void
5304 public static function create_instances($contextlevel = null, $buildpaths = true) {
5305 foreach (self::$alllevels as $level=>$classname) {
5306 if ($contextlevel and $level > $contextlevel) {
5307 // skip potential sub-contexts
5308 continue;
5310 $classname::create_level_instances();
5311 if ($buildpaths) {
5312 $classname::build_paths(false);
5318 * Rebuild paths and depths in all context levels.
5320 * @static
5321 * @param bool $force false means add missing only
5322 * @return void
5324 public static function build_all_paths($force = false) {
5325 foreach (self::$alllevels as $classname) {
5326 $classname::build_paths($force);
5329 // reset static course cache - it might have incorrect cached data
5330 accesslib_clear_all_caches(true);
5334 * Resets the cache to remove all data.
5335 * @static
5337 public static function reset_caches() {
5338 context::reset_caches();
5342 * Returns all fields necessary for context preloading from user $rec.
5344 * This helps with performance when dealing with hundreds of contexts.
5346 * @static
5347 * @param string $tablealias context table alias in the query
5348 * @return array (table.column=>alias, ...)
5350 public static function get_preload_record_columns($tablealias) {
5351 return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
5355 * Returns all fields necessary for context preloading from user $rec.
5357 * This helps with performance when dealing with hundreds of contexts.
5359 * @static
5360 * @param string $tablealias context table alias in the query
5361 * @return string
5363 public static function get_preload_record_columns_sql($tablealias) {
5364 return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5368 * Preloads context information from db record and strips the cached info.
5370 * The db request has to contain all columns from context_helper::get_preload_record_columns().
5372 * @static
5373 * @param stdClass $rec
5374 * @return void (modifies $rec)
5376 public static function preload_from_record(stdClass $rec) {
5377 context::preload_from_record($rec);
5381 * Preload all contexts instances from course.
5383 * To be used if you expect multiple queries for course activities...
5385 * @static
5386 * @param $courseid
5388 public static function preload_course($courseid) {
5389 // Users can call this multiple times without doing any harm
5390 if (isset(context::$cache_preloaded[$courseid])) {
5391 return;
5393 $coursecontext = context_course::instance($courseid);
5394 $coursecontext->get_child_contexts();
5396 context::$cache_preloaded[$courseid] = true;
5400 * Delete context instance
5402 * @static
5403 * @param int $contextlevel
5404 * @param int $instanceid
5405 * @return void
5407 public static function delete_instance($contextlevel, $instanceid) {
5408 global $DB;
5410 // double check the context still exists
5411 if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
5412 $context = context::create_instance_from_record($record);
5413 $context->delete();
5414 } else {
5415 // we should try to purge the cache anyway
5420 * Returns the name of specified context level
5422 * @static
5423 * @param int $contextlevel
5424 * @return string name of the context level
5426 public static function get_level_name($contextlevel) {
5427 $classname = context_helper::get_class_for_level($contextlevel);
5428 return $classname::get_level_name();
5432 * not used
5434 public function get_url() {
5438 * not used
5440 public function get_capabilities() {
5446 * Basic context class
5447 * @author Petr Skoda (http://skodak.org)
5448 * @since 2.2
5450 class context_system extends context {
5452 * Please use context_system::instance() if you need the instance of context.
5454 * @param stdClass $record
5456 protected function __construct(stdClass $record) {
5457 parent::__construct($record);
5458 if ($record->contextlevel != CONTEXT_SYSTEM) {
5459 throw new coding_exception('Invalid $record->contextlevel in context_system constructor.');
5464 * Returns human readable context level name.
5466 * @static
5467 * @return string the human readable context level name.
5469 protected static function get_level_name() {
5470 return get_string('coresystem');
5474 * Returns human readable context identifier.
5476 * @param boolean $withprefix does not apply to system context
5477 * @param boolean $short does not apply to system context
5478 * @return string the human readable context name.
5480 public function get_context_name($withprefix = true, $short = false) {
5481 return self::get_level_name();
5485 * Returns the most relevant URL for this context.
5487 * @return moodle_url
5489 public function get_url() {
5490 return new moodle_url('/');
5494 * Returns array of relevant context capability records.
5496 * @return array
5498 public function get_capabilities() {
5499 global $DB;
5501 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5503 $params = array();
5504 $sql = "SELECT *
5505 FROM {capabilities}";
5507 return $DB->get_records_sql($sql.' '.$sort, $params);
5511 * Create missing context instances at system context
5512 * @static
5514 protected static function create_level_instances() {
5515 // nothing to do here, the system context is created automatically in installer
5516 self::instance(0);
5520 * Returns system context instance.
5522 * @static
5523 * @param int $instanceid
5524 * @param int $strictness
5525 * @param bool $cache
5526 * @return context_system context instance
5528 public static function instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true) {
5529 global $DB;
5531 if ($instanceid != 0) {
5532 debugging('context_system::instance(): invalid $id parameter detected, should be 0');
5535 if (defined('SYSCONTEXTID') and $cache) { // dangerous: define this in config.php to eliminate 1 query/page
5536 if (!isset(context::$systemcontext)) {
5537 $record = new stdClass();
5538 $record->id = SYSCONTEXTID;
5539 $record->contextlevel = CONTEXT_SYSTEM;
5540 $record->instanceid = 0;
5541 $record->path = '/'.SYSCONTEXTID;
5542 $record->depth = 1;
5543 context::$systemcontext = new context_system($record);
5545 return context::$systemcontext;
5549 try {
5550 // we ignore the strictness completely because system context must except except during install
5551 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5552 } catch (dml_exception $e) {
5553 //table or record does not exist
5554 if (!during_initial_install()) {
5555 // do not mess with system context after install, it simply must exist
5556 throw $e;
5558 $record = null;
5561 if (!$record) {
5562 $record = new stdClass();
5563 $record->contextlevel = CONTEXT_SYSTEM;
5564 $record->instanceid = 0;
5565 $record->depth = 1;
5566 $record->path = null; //not known before insert
5568 try {
5569 if ($DB->count_records('context')) {
5570 // contexts already exist, this is very weird, system must be first!!!
5571 return null;
5573 if (defined('SYSCONTEXTID')) {
5574 // this would happen only in unittest on sites that went through weird 1.7 upgrade
5575 $record->id = SYSCONTEXTID;
5576 $DB->import_record('context', $record);
5577 $DB->get_manager()->reset_sequence('context');
5578 } else {
5579 $record->id = $DB->insert_record('context', $record);
5581 } catch (dml_exception $e) {
5582 // can not create context - table does not exist yet, sorry
5583 return null;
5587 if ($record->instanceid != 0) {
5588 // this is very weird, somebody must be messing with context table
5589 debugging('Invalid system context detected');
5592 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5593 // fix path if necessary, initial install or path reset
5594 $record->depth = 1;
5595 $record->path = '/'.$record->id;
5596 $DB->update_record('context', $record);
5599 if (!defined('SYSCONTEXTID')) {
5600 define('SYSCONTEXTID', $record->id);
5603 context::$systemcontext = new context_system($record);
5604 return context::$systemcontext;
5608 * Returns all site contexts except the system context, DO NOT call on production servers!!
5610 * Contexts are not cached.
5612 * @return array
5614 public function get_child_contexts() {
5615 global $DB;
5617 debugging('Fetching of system context child courses is strongly discouraged on production servers (it may eat all available memory)!');
5619 // Just get all the contexts except for CONTEXT_SYSTEM level
5620 // and hope we don't OOM in the process - don't cache
5621 $sql = "SELECT c.*
5622 FROM {context} c
5623 WHERE contextlevel > ".CONTEXT_SYSTEM;
5624 $records = $DB->get_records_sql($sql);
5626 $result = array();
5627 foreach ($records as $record) {
5628 $result[$record->id] = context::create_instance_from_record($record);
5631 return $result;
5635 * Returns sql necessary for purging of stale context instances.
5637 * @static
5638 * @return string cleanup SQL
5640 protected static function get_cleanup_sql() {
5641 $sql = "
5642 SELECT c.*
5643 FROM {context} c
5644 WHERE 1=2
5647 return $sql;
5651 * Rebuild context paths and depths at system context level.
5653 * @static
5654 * @param $force
5656 protected static function build_paths($force) {
5657 global $DB;
5659 /* note: ignore $force here, we always do full test of system context */
5661 // exactly one record must exist
5662 $record = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM), '*', MUST_EXIST);
5664 if ($record->instanceid != 0) {
5665 debugging('Invalid system context detected');
5668 if (defined('SYSCONTEXTID') and $record->id != SYSCONTEXTID) {
5669 debugging('Invalid SYSCONTEXTID detected');
5672 if ($record->depth != 1 or $record->path != '/'.$record->id) {
5673 // fix path if necessary, initial install or path reset
5674 $record->depth = 1;
5675 $record->path = '/'.$record->id;
5676 $DB->update_record('context', $record);
5683 * User context class
5684 * @author Petr Skoda (http://skodak.org)
5685 * @since 2.2
5687 class context_user extends context {
5689 * Please use context_user::instance($userid) if you need the instance of context.
5690 * Alternatively if you know only the context id use context::instance_by_id($contextid)
5692 * @param stdClass $record
5694 protected function __construct(stdClass $record) {
5695 parent::__construct($record);
5696 if ($record->contextlevel != CONTEXT_USER) {
5697 throw new coding_exception('Invalid $record->contextlevel in context_user constructor.');
5702 * Returns human readable context level name.
5704 * @static
5705 * @return string the human readable context level name.
5707 protected static function get_level_name() {
5708 return get_string('user');
5712 * Returns human readable context identifier.
5714 * @param boolean $withprefix whether to prefix the name of the context with User
5715 * @param boolean $short does not apply to user context
5716 * @return string the human readable context name.
5718 public function get_context_name($withprefix = true, $short = false) {
5719 global $DB;
5721 $name = '';
5722 if ($user = $DB->get_record('user', array('id'=>$this->_instanceid, 'deleted'=>0))) {
5723 if ($withprefix){
5724 $name = get_string('user').': ';
5726 $name .= fullname($user);
5728 return $name;
5732 * Returns the most relevant URL for this context.
5734 * @return moodle_url
5736 public function get_url() {
5737 global $COURSE;
5739 if ($COURSE->id == SITEID) {
5740 $url = new moodle_url('/user/profile.php', array('id'=>$this->_instanceid));
5741 } else {
5742 $url = new moodle_url('/user/view.php', array('id'=>$this->_instanceid, 'courseid'=>$COURSE->id));
5744 return $url;
5748 * Returns array of relevant context capability records.
5750 * @return array
5752 public function get_capabilities() {
5753 global $DB;
5755 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5757 $extracaps = array('moodle/grade:viewall');
5758 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
5759 $sql = "SELECT *
5760 FROM {capabilities}
5761 WHERE contextlevel = ".CONTEXT_USER."
5762 OR name $extra";
5764 return $records = $DB->get_records_sql($sql.' '.$sort, $params);
5768 * Returns user context instance.
5770 * @static
5771 * @param int $instanceid
5772 * @param int $strictness
5773 * @return context_user context instance
5775 public static function instance($instanceid, $strictness = MUST_EXIST) {
5776 global $DB;
5778 if ($context = context::cache_get(CONTEXT_USER, $instanceid)) {
5779 return $context;
5782 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_USER, 'instanceid'=>$instanceid))) {
5783 if ($user = $DB->get_record('user', array('id'=>$instanceid, 'deleted'=>0), 'id', $strictness)) {
5784 $record = context::insert_context_record(CONTEXT_USER, $user->id, '/'.SYSCONTEXTID, 0);
5788 if ($record) {
5789 $context = new context_user($record);
5790 context::cache_add($context);
5791 return $context;
5794 return false;
5798 * Create missing context instances at user context level
5799 * @static
5801 protected static function create_level_instances() {
5802 global $DB;
5804 $sql = "INSERT INTO {context} (contextlevel, instanceid)
5805 SELECT ".CONTEXT_USER.", u.id
5806 FROM {user} u
5807 WHERE u.deleted = 0
5808 AND NOT EXISTS (SELECT 'x'
5809 FROM {context} cx
5810 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
5811 $DB->execute($sql);
5815 * Returns sql necessary for purging of stale context instances.
5817 * @static
5818 * @return string cleanup SQL
5820 protected static function get_cleanup_sql() {
5821 $sql = "
5822 SELECT c.*
5823 FROM {context} c
5824 LEFT OUTER JOIN {user} u ON (c.instanceid = u.id AND u.deleted = 0)
5825 WHERE u.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
5828 return $sql;
5832 * Rebuild context paths and depths at user context level.
5834 * @static
5835 * @param $force
5837 protected static function build_paths($force) {
5838 global $DB;
5840 // first update normal users
5841 $sql = "UPDATE {context}
5842 SET depth = 2,
5843 path = ".$DB->sql_concat("'/".SYSCONTEXTID."/'", 'id')."
5844 WHERE contextlevel=".CONTEXT_USER;
5845 $DB->execute($sql);
5851 * Course category context class
5852 * @author Petr Skoda (http://skodak.org)
5853 * @since 2.2
5855 class context_coursecat extends context {
5857 * Please use context_coursecat::instance($coursecatid) if you need the instance of context.
5858 * Alternatively if you know only the context id use context::instance_by_id($contextid)
5860 * @param stdClass $record
5862 protected function __construct(stdClass $record) {
5863 parent::__construct($record);
5864 if ($record->contextlevel != CONTEXT_COURSECAT) {
5865 throw new coding_exception('Invalid $record->contextlevel in context_coursecat constructor.');
5870 * Returns human readable context level name.
5872 * @static
5873 * @return string the human readable context level name.
5875 protected static function get_level_name() {
5876 return get_string('category');
5880 * Returns human readable context identifier.
5882 * @param boolean $withprefix whether to prefix the name of the context with Category
5883 * @param boolean $short does not apply to course categories
5884 * @return string the human readable context name.
5886 public function get_context_name($withprefix = true, $short = false) {
5887 global $DB;
5889 $name = '';
5890 if ($category = $DB->get_record('course_categories', array('id'=>$this->_instanceid))) {
5891 if ($withprefix){
5892 $name = get_string('category').': ';
5894 $name .= format_string($category->name, true, array('context' => $this));
5896 return $name;
5900 * Returns the most relevant URL for this context.
5902 * @return moodle_url
5904 public function get_url() {
5905 return new moodle_url('/course/category.php', array('id'=>$this->_instanceid));
5909 * Returns array of relevant context capability records.
5911 * @return array
5913 public function get_capabilities() {
5914 global $DB;
5916 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
5918 $params = array();
5919 $sql = "SELECT *
5920 FROM {capabilities}
5921 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
5923 return $DB->get_records_sql($sql.' '.$sort, $params);
5927 * Returns course category context instance.
5929 * @static
5930 * @param int $instanceid
5931 * @param int $strictness
5932 * @return context_coursecat context instance
5934 public static function instance($instanceid, $strictness = MUST_EXIST) {
5935 global $DB;
5937 if ($context = context::cache_get(CONTEXT_COURSECAT, $instanceid)) {
5938 return $context;
5941 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSECAT, 'instanceid'=>$instanceid))) {
5942 if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), 'id,parent', $strictness)) {
5943 if ($category->parent) {
5944 $parentcontext = context_coursecat::instance($category->parent);
5945 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, $parentcontext->path);
5946 } else {
5947 $record = context::insert_context_record(CONTEXT_COURSECAT, $category->id, '/'.SYSCONTEXTID, 0);
5952 if ($record) {
5953 $context = new context_coursecat($record);
5954 context::cache_add($context);
5955 return $context;
5958 return false;
5962 * Returns immediate child contexts of category and all subcategories,
5963 * children of subcategories and courses are not returned.
5965 * @return array
5967 public function get_child_contexts() {
5968 global $DB;
5970 $sql = "SELECT ctx.*
5971 FROM {context} ctx
5972 WHERE ctx.path LIKE ? AND (ctx.depth = ? OR ctx.contextlevel = ?)";
5973 $params = array($this->_path.'/%', $this->depth+1, CONTEXT_COURSECAT);
5974 $records = $DB->get_records_sql($sql, $params);
5976 $result = array();
5977 foreach ($records as $record) {
5978 $result[$record->id] = context::create_instance_from_record($record);
5981 return $result;
5985 * Create missing context instances at course category context level
5986 * @static
5988 protected static function create_level_instances() {
5989 global $DB;
5991 $sql = "INSERT INTO {context} (contextlevel, instanceid)
5992 SELECT ".CONTEXT_COURSECAT.", cc.id
5993 FROM {course_categories} cc
5994 WHERE NOT EXISTS (SELECT 'x'
5995 FROM {context} cx
5996 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
5997 $DB->execute($sql);
6001 * Returns sql necessary for purging of stale context instances.
6003 * @static
6004 * @return string cleanup SQL
6006 protected static function get_cleanup_sql() {
6007 $sql = "
6008 SELECT c.*
6009 FROM {context} c
6010 LEFT OUTER JOIN {course_categories} cc ON c.instanceid = cc.id
6011 WHERE cc.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
6014 return $sql;
6018 * Rebuild context paths and depths at course category context level.
6020 * @static
6021 * @param $force
6023 protected static function build_paths($force) {
6024 global $DB;
6026 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSECAT." AND (depth = 0 OR path IS NULL)")) {
6027 if ($force) {
6028 $ctxemptyclause = $emptyclause = '';
6029 } else {
6030 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6031 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6034 $base = '/'.SYSCONTEXTID;
6036 // Normal top level categories
6037 $sql = "UPDATE {context}
6038 SET depth=2,
6039 path=".$DB->sql_concat("'$base/'", 'id')."
6040 WHERE contextlevel=".CONTEXT_COURSECAT."
6041 AND EXISTS (SELECT 'x'
6042 FROM {course_categories} cc
6043 WHERE cc.id = {context}.instanceid AND cc.depth=1)
6044 $emptyclause";
6045 $DB->execute($sql);
6047 // Deeper categories - one query per depthlevel
6048 $maxdepth = $DB->get_field_sql("SELECT MAX(depth) FROM {course_categories}");
6049 for ($n=2; $n<=$maxdepth; $n++) {
6050 $sql = "INSERT INTO {context_temp} (id, path, depth)
6051 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6052 FROM {context} ctx
6053 JOIN {course_categories} cc ON (cc.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSECAT." AND cc.depth = $n)
6054 JOIN {context} pctx ON (pctx.instanceid = cc.parent AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6055 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6056 $ctxemptyclause";
6057 $trans = $DB->start_delegated_transaction();
6058 $DB->delete_records('context_temp');
6059 $DB->execute($sql);
6060 context::merge_context_temp_table();
6061 $DB->delete_records('context_temp');
6062 $trans->allow_commit();
6071 * Course context class
6072 * @author Petr Skoda (http://skodak.org)
6073 * @since 2.2
6075 class context_course extends context {
6077 * Please use context_course::instance($courseid) if you need the instance of context.
6078 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6080 * @param stdClass $record
6082 protected function __construct(stdClass $record) {
6083 parent::__construct($record);
6084 if ($record->contextlevel != CONTEXT_COURSE) {
6085 throw new coding_exception('Invalid $record->contextlevel in context_course constructor.');
6090 * Returns human readable context level name.
6092 * @static
6093 * @return string the human readable context level name.
6095 protected static function get_level_name() {
6096 return get_string('course');
6100 * Returns human readable context identifier.
6102 * @param boolean $withprefix whether to prefix the name of the context with Course
6103 * @param boolean $short whether to use the short name of the thing.
6104 * @return string the human readable context name.
6106 public function get_context_name($withprefix = true, $short = false) {
6107 global $DB;
6109 $name = '';
6110 if ($this->_instanceid == SITEID) {
6111 $name = get_string('frontpage', 'admin');
6112 } else {
6113 if ($course = $DB->get_record('course', array('id'=>$this->_instanceid))) {
6114 if ($withprefix){
6115 $name = get_string('course').': ';
6117 if ($short){
6118 $name .= format_string($course->shortname, true, array('context' => $this));
6119 } else {
6120 $name .= format_string($course->fullname);
6124 return $name;
6128 * Returns the most relevant URL for this context.
6130 * @return moodle_url
6132 public function get_url() {
6133 if ($this->_instanceid != SITEID) {
6134 return new moodle_url('/course/view.php', array('id'=>$this->_instanceid));
6137 return new moodle_url('/');
6141 * Returns array of relevant context capability records.
6143 * @return array
6145 public function get_capabilities() {
6146 global $DB;
6148 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6150 $params = array();
6151 $sql = "SELECT *
6152 FROM {capabilities}
6153 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
6155 return $DB->get_records_sql($sql.' '.$sort, $params);
6159 * Is this context part of any course? If yes return course context.
6161 * @param bool $strict true means throw exception if not found, false means return false if not found
6162 * @return course_context context of the enclosing course, null if not found or exception
6164 public function get_course_context($strict = true) {
6165 return $this;
6169 * Returns course context instance.
6171 * @static
6172 * @param int $instanceid
6173 * @param int $strictness
6174 * @return context_course context instance
6176 public static function instance($instanceid, $strictness = MUST_EXIST) {
6177 global $DB;
6179 if ($context = context::cache_get(CONTEXT_COURSE, $instanceid)) {
6180 return $context;
6183 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>$instanceid))) {
6184 if ($course = $DB->get_record('course', array('id'=>$instanceid), 'id,category', $strictness)) {
6185 if ($course->category) {
6186 $parentcontext = context_coursecat::instance($course->category);
6187 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, $parentcontext->path);
6188 } else {
6189 $record = context::insert_context_record(CONTEXT_COURSE, $course->id, '/'.SYSCONTEXTID, 0);
6194 if ($record) {
6195 $context = new context_course($record);
6196 context::cache_add($context);
6197 return $context;
6200 return false;
6204 * Create missing context instances at course context level
6205 * @static
6207 protected static function create_level_instances() {
6208 global $DB;
6210 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6211 SELECT ".CONTEXT_COURSE.", c.id
6212 FROM {course} c
6213 WHERE NOT EXISTS (SELECT 'x'
6214 FROM {context} cx
6215 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
6216 $DB->execute($sql);
6220 * Returns sql necessary for purging of stale context instances.
6222 * @static
6223 * @return string cleanup SQL
6225 protected static function get_cleanup_sql() {
6226 $sql = "
6227 SELECT c.*
6228 FROM {context} c
6229 LEFT OUTER JOIN {course} co ON c.instanceid = co.id
6230 WHERE co.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
6233 return $sql;
6237 * Rebuild context paths and depths at course context level.
6239 * @static
6240 * @param $force
6242 protected static function build_paths($force) {
6243 global $DB;
6245 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_COURSE." AND (depth = 0 OR path IS NULL)")) {
6246 if ($force) {
6247 $ctxemptyclause = $emptyclause = '';
6248 } else {
6249 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6250 $emptyclause = "AND ({context}.path IS NULL OR {context}.depth = 0)";
6253 $base = '/'.SYSCONTEXTID;
6255 // Standard frontpage
6256 $sql = "UPDATE {context}
6257 SET depth = 2,
6258 path = ".$DB->sql_concat("'$base/'", 'id')."
6259 WHERE contextlevel = ".CONTEXT_COURSE."
6260 AND EXISTS (SELECT 'x'
6261 FROM {course} c
6262 WHERE c.id = {context}.instanceid AND c.category = 0)
6263 $emptyclause";
6264 $DB->execute($sql);
6266 // standard courses
6267 $sql = "INSERT INTO {context_temp} (id, path, depth)
6268 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6269 FROM {context} ctx
6270 JOIN {course} c ON (c.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_COURSE." AND c.category <> 0)
6271 JOIN {context} pctx ON (pctx.instanceid = c.category AND pctx.contextlevel = ".CONTEXT_COURSECAT.")
6272 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6273 $ctxemptyclause";
6274 $trans = $DB->start_delegated_transaction();
6275 $DB->delete_records('context_temp');
6276 $DB->execute($sql);
6277 context::merge_context_temp_table();
6278 $DB->delete_records('context_temp');
6279 $trans->allow_commit();
6286 * Course module context class
6287 * @author Petr Skoda (http://skodak.org)
6288 * @since 2.2
6290 class context_module extends context {
6292 * Please use context_module::instance($cmid) if you need the instance of context.
6293 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6295 * @param stdClass $record
6297 protected function __construct(stdClass $record) {
6298 parent::__construct($record);
6299 if ($record->contextlevel != CONTEXT_MODULE) {
6300 throw new coding_exception('Invalid $record->contextlevel in context_module constructor.');
6305 * Returns human readable context level name.
6307 * @static
6308 * @return string the human readable context level name.
6310 protected static function get_level_name() {
6311 return get_string('activitymodule');
6315 * Returns human readable context identifier.
6317 * @param boolean $withprefix whether to prefix the name of the context with the
6318 * module name, e.g. Forum, Glossary, etc.
6319 * @param boolean $short does not apply to module context
6320 * @return string the human readable context name.
6322 public function get_context_name($withprefix = true, $short = false) {
6323 global $DB;
6325 $name = '';
6326 if ($cm = $DB->get_record_sql("SELECT cm.*, md.name AS modname
6327 FROM {course_modules} cm
6328 JOIN {modules} md ON md.id = cm.module
6329 WHERE cm.id = ?", array($this->_instanceid))) {
6330 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
6331 if ($withprefix){
6332 $name = get_string('modulename', $cm->modname).': ';
6334 $name .= $mod->name;
6337 return $name;
6341 * Returns the most relevant URL for this context.
6343 * @return moodle_url
6345 public function get_url() {
6346 global $DB;
6348 if ($modname = $DB->get_field_sql("SELECT md.name AS modname
6349 FROM {course_modules} cm
6350 JOIN {modules} md ON md.id = cm.module
6351 WHERE cm.id = ?", array($this->_instanceid))) {
6352 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$this->_instanceid));
6355 return new moodle_url('/');
6359 * Returns array of relevant context capability records.
6361 * @return array
6363 public function get_capabilities() {
6364 global $DB, $CFG;
6366 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6368 $cm = $DB->get_record('course_modules', array('id'=>$this->_instanceid));
6369 $module = $DB->get_record('modules', array('id'=>$cm->module));
6371 $subcaps = array();
6372 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
6373 if (file_exists($subpluginsfile)) {
6374 $subplugins = array(); // should be redefined in the file
6375 include($subpluginsfile);
6376 if (!empty($subplugins)) {
6377 foreach (array_keys($subplugins) as $subplugintype) {
6378 foreach (array_keys(get_plugin_list($subplugintype)) as $subpluginname) {
6379 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
6385 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
6386 if (file_exists($modfile)) {
6387 include_once($modfile);
6388 $modfunction = $module->name.'_get_extra_capabilities';
6389 if (function_exists($modfunction)) {
6390 $extracaps = $modfunction();
6393 if (empty($extracaps)) {
6394 $extracaps = array();
6397 $extracaps = array_merge($subcaps, $extracaps);
6399 // All modules allow viewhiddenactivities. This is so you can hide
6400 // the module then override to allow specific roles to see it.
6401 // The actual check is in course page so not module-specific
6402 $extracaps[] = "moodle/course:viewhiddenactivities";
6403 list($extra, $params) = $DB->get_in_or_equal(
6404 $extracaps, SQL_PARAMS_NAMED, 'cap0');
6405 $extra = "OR name $extra";
6407 $sql = "SELECT *
6408 FROM {capabilities}
6409 WHERE (contextlevel = ".CONTEXT_MODULE."
6410 AND component = :component)
6411 $extra";
6412 $params['component'] = "mod_$module->name";
6414 return $DB->get_records_sql($sql.' '.$sort, $params);
6418 * Is this context part of any course? If yes return course context.
6420 * @param bool $strict true means throw exception if not found, false means return false if not found
6421 * @return course_context context of the enclosing course, null if not found or exception
6423 public function get_course_context($strict = true) {
6424 return $this->get_parent_context();
6428 * Returns module context instance.
6430 * @static
6431 * @param int $instanceid
6432 * @param int $strictness
6433 * @return context_module context instance
6435 public static function instance($instanceid, $strictness = MUST_EXIST) {
6436 global $DB;
6438 if ($context = context::cache_get(CONTEXT_MODULE, $instanceid)) {
6439 return $context;
6442 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_MODULE, 'instanceid'=>$instanceid))) {
6443 if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), 'id,course', $strictness)) {
6444 $parentcontext = context_course::instance($cm->course);
6445 $record = context::insert_context_record(CONTEXT_MODULE, $cm->id, $parentcontext->path);
6449 if ($record) {
6450 $context = new context_module($record);
6451 context::cache_add($context);
6452 return $context;
6455 return false;
6459 * Create missing context instances at module context level
6460 * @static
6462 protected static function create_level_instances() {
6463 global $DB;
6465 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6466 SELECT ".CONTEXT_MODULE.", cm.id
6467 FROM {course_modules} cm
6468 WHERE NOT EXISTS (SELECT 'x'
6469 FROM {context} cx
6470 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
6471 $DB->execute($sql);
6475 * Returns sql necessary for purging of stale context instances.
6477 * @static
6478 * @return string cleanup SQL
6480 protected static function get_cleanup_sql() {
6481 $sql = "
6482 SELECT c.*
6483 FROM {context} c
6484 LEFT OUTER JOIN {course_modules} cm ON c.instanceid = cm.id
6485 WHERE cm.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
6488 return $sql;
6492 * Rebuild context paths and depths at module context level.
6494 * @static
6495 * @param $force
6497 protected static function build_paths($force) {
6498 global $DB;
6500 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_MODULE." AND (depth = 0 OR path IS NULL)")) {
6501 if ($force) {
6502 $ctxemptyclause = '';
6503 } else {
6504 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6507 $sql = "INSERT INTO {context_temp} (id, path, depth)
6508 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6509 FROM {context} ctx
6510 JOIN {course_modules} cm ON (cm.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_MODULE.")
6511 JOIN {context} pctx ON (pctx.instanceid = cm.course AND pctx.contextlevel = ".CONTEXT_COURSE.")
6512 WHERE pctx.path IS NOT NULL AND pctx.depth > 0
6513 $ctxemptyclause";
6514 $trans = $DB->start_delegated_transaction();
6515 $DB->delete_records('context_temp');
6516 $DB->execute($sql);
6517 context::merge_context_temp_table();
6518 $DB->delete_records('context_temp');
6519 $trans->allow_commit();
6526 * Block context class
6527 * @author Petr Skoda (http://skodak.org)
6528 * @since 2.2
6530 class context_block extends context {
6532 * Please use context_block::instance($blockinstanceid) if you need the instance of context.
6533 * Alternatively if you know only the context id use context::instance_by_id($contextid)
6535 * @param stdClass $record
6537 protected function __construct(stdClass $record) {
6538 parent::__construct($record);
6539 if ($record->contextlevel != CONTEXT_BLOCK) {
6540 throw new coding_exception('Invalid $record->contextlevel in context_block constructor');
6545 * Returns human readable context level name.
6547 * @static
6548 * @return string the human readable context level name.
6550 protected static function get_level_name() {
6551 return get_string('block');
6555 * Returns human readable context identifier.
6557 * @param boolean $withprefix whether to prefix the name of the context with Block
6558 * @param boolean $short does not apply to block context
6559 * @return string the human readable context name.
6561 public function get_context_name($withprefix = true, $short = false) {
6562 global $DB, $CFG;
6564 $name = '';
6565 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$this->_instanceid))) {
6566 global $CFG;
6567 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
6568 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
6569 $blockname = "block_$blockinstance->blockname";
6570 if ($blockobject = new $blockname()) {
6571 if ($withprefix){
6572 $name = get_string('block').': ';
6574 $name .= $blockobject->title;
6578 return $name;
6582 * Returns the most relevant URL for this context.
6584 * @return moodle_url
6586 public function get_url() {
6587 $parentcontexts = $this->get_parent_context();
6588 return $parentcontexts->get_url();
6592 * Returns array of relevant context capability records.
6594 * @return array
6596 public function get_capabilities() {
6597 global $DB;
6599 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
6601 $params = array();
6602 $bi = $DB->get_record('block_instances', array('id' => $this->_instanceid));
6604 $extra = '';
6605 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
6606 if ($extracaps) {
6607 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
6608 $extra = "OR name $extra";
6611 $sql = "SELECT *
6612 FROM {capabilities}
6613 WHERE (contextlevel = ".CONTEXT_BLOCK."
6614 AND component = :component)
6615 $extra";
6616 $params['component'] = 'block_' . $bi->blockname;
6618 return $DB->get_records_sql($sql.' '.$sort, $params);
6622 * Is this context part of any course? If yes return course context.
6624 * @param bool $strict true means throw exception if not found, false means return false if not found
6625 * @return course_context context of the enclosing course, null if not found or exception
6627 public function get_course_context($strict = true) {
6628 $parentcontext = $this->get_parent_context();
6629 return $parentcontext->get_course_context($strict);
6633 * Returns block context instance.
6635 * @static
6636 * @param int $instanceid
6637 * @param int $strictness
6638 * @return context_block context instance
6640 public static function instance($instanceid, $strictness = MUST_EXIST) {
6641 global $DB;
6643 if ($context = context::cache_get(CONTEXT_BLOCK, $instanceid)) {
6644 return $context;
6647 if (!$record = $DB->get_record('context', array('contextlevel'=>CONTEXT_BLOCK, 'instanceid'=>$instanceid))) {
6648 if ($bi = $DB->get_record('block_instances', array('id'=>$instanceid), 'id,parentcontextid', $strictness)) {
6649 $parentcontext = context::instance_by_id($bi->parentcontextid);
6650 $record = context::insert_context_record(CONTEXT_BLOCK, $bi->id, $parentcontext->path);
6654 if ($record) {
6655 $context = new context_block($record);
6656 context::cache_add($context);
6657 return $context;
6660 return false;
6664 * Block do not have child contexts...
6665 * @return array
6667 public function get_child_contexts() {
6668 return array();
6672 * Create missing context instances at block context level
6673 * @static
6675 protected static function create_level_instances() {
6676 global $DB;
6678 $sql = "INSERT INTO {context} (contextlevel, instanceid)
6679 SELECT ".CONTEXT_BLOCK.", bi.id
6680 FROM {block_instances} bi
6681 WHERE NOT EXISTS (SELECT 'x'
6682 FROM {context} cx
6683 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
6684 $DB->execute($sql);
6688 * Returns sql necessary for purging of stale context instances.
6690 * @static
6691 * @return string cleanup SQL
6693 protected static function get_cleanup_sql() {
6694 $sql = "
6695 SELECT c.*
6696 FROM {context} c
6697 LEFT OUTER JOIN {block_instances} bi ON c.instanceid = bi.id
6698 WHERE bi.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
6701 return $sql;
6705 * Rebuild context paths and depths at block context level.
6707 * @static
6708 * @param $force
6710 protected static function build_paths($force) {
6711 global $DB;
6713 if ($force or $DB->record_exists_select('context', "contextlevel = ".CONTEXT_BLOCK." AND (depth = 0 OR path IS NULL)")) {
6714 if ($force) {
6715 $ctxemptyclause = '';
6716 } else {
6717 $ctxemptyclause = "AND (ctx.path IS NULL OR ctx.depth = 0)";
6720 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
6721 $sql = "INSERT INTO {context_temp} (id, path, depth)
6722 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
6723 FROM {context} ctx
6724 JOIN {block_instances} bi ON (bi.id = ctx.instanceid AND ctx.contextlevel = ".CONTEXT_BLOCK.")
6725 JOIN {context} pctx ON (pctx.id = bi.parentcontextid)
6726 WHERE (pctx.path IS NOT NULL AND pctx.depth > 0)
6727 $ctxemptyclause";
6728 $trans = $DB->start_delegated_transaction();
6729 $DB->delete_records('context_temp');
6730 $DB->execute($sql);
6731 context::merge_context_temp_table();
6732 $DB->delete_records('context_temp');
6733 $trans->allow_commit();
6739 // ============== DEPRECATED FUNCTIONS ==========================================
6740 // Old context related functions were deprecated in 2.0, it is recommended
6741 // to use context classes in new code. Old function can be used when
6742 // creating patches that are supposed to be backported to older stable branches.
6743 // These deprecated functions will not be removed in near future,
6744 // before removing devs will be warned with a debugging message first,
6745 // then we will add error message and only after that we can remove the functions
6746 // completely.
6750 * Not available any more, use load_temp_course_role() instead.
6752 * @deprecated since 2.2
6753 * @param stdClass $context
6754 * @param int $roleid
6755 * @param array $accessdata
6756 * @return array
6758 function load_temp_role($context, $roleid, array $accessdata) {
6759 debugging('load_temp_role() is deprecated, please use load_temp_course_role() instead, temp role not loaded.');
6760 return $accessdata;
6764 * Not available any more, use remove_temp_course_roles() instead.
6766 * @deprecated since 2.2
6767 * @param object $context
6768 * @param array $accessdata
6769 * @return array access data
6771 function remove_temp_roles($context, array $accessdata) {
6772 debugging('remove_temp_role() is deprecated, please use remove_temp_course_roles() instead.');
6773 return $accessdata;
6777 * Returns system context or null if can not be created yet.
6779 * @deprecated since 2.2, use context_system::instance()
6780 * @param bool $cache use caching
6781 * @return context system context (null if context table not created yet)
6783 function get_system_context($cache = true) {
6784 return context_system::instance(0, IGNORE_MISSING, $cache);
6788 * Get the context instance as an object. This function will create the
6789 * context instance if it does not exist yet.
6791 * @deprecated since 2.2, use context_course::instance() or other relevant class instead
6792 * @param integer $contextlevel The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
6793 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
6794 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
6795 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
6796 * MUST_EXIST means throw exception if no record or multiple records found
6797 * @return context The context object.
6799 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
6800 $instances = (array)$instance;
6801 $contexts = array();
6803 $classname = context_helper::get_class_for_level($contextlevel);
6805 // we do not load multiple contexts any more, PAGE should be responsible for any preloading
6806 foreach ($instances as $inst) {
6807 $contexts[$inst] = $classname::instance($inst, $strictness);
6810 if (is_array($instance)) {
6811 return $contexts;
6812 } else {
6813 return $contexts[$instance];
6818 * Get a context instance as an object, from a given context id.
6820 * @deprecated since 2.2, use context::instance_by_id($id) instead
6821 * @param int $id context id
6822 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
6823 * MUST_EXIST means throw exception if no record or multiple records found
6824 * @return context|bool the context object or false if not found.
6826 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
6827 return context::instance_by_id($id, $strictness);
6831 * Recursive function which, given a context, find all parent context ids,
6832 * and return the array in reverse order, i.e. parent first, then grand
6833 * parent, etc.
6835 * @deprecated since 2.2, use $context->get_parent_context_ids() instead
6836 * @param context $context
6837 * @param bool $includeself optional, defaults to false
6838 * @return array
6840 function get_parent_contexts(context $context, $includeself = false) {
6841 return $context->get_parent_context_ids($includeself);
6845 * Return the id of the parent of this context, or false if there is no parent (only happens if this
6846 * is the site context.)
6848 * @deprecated since 2.2, use $context->get_parent_context() instead
6849 * @param context $context
6850 * @return integer the id of the parent context.
6852 function get_parent_contextid(context $context) {
6853 if ($parent = $context->get_parent_context()) {
6854 return $parent->id;
6855 } else {
6856 return false;
6861 * Recursive function which, given a context, find all its children context ids.
6863 * For course category contexts it will return immediate children only categories and courses.
6864 * It will NOT recurse into courses or child categories.
6865 * If you want to do that, call it on the returned courses/categories.
6867 * When called for a course context, it will return the modules and blocks
6868 * displayed in the course page.
6870 * If called on a user/course/module context it _will_ populate the cache with the appropriate
6871 * contexts ;-)
6873 * @deprecated since 2.2, use $context->get_child_contexts() instead
6874 * @param context $context.
6875 * @return array Array of child records
6877 function get_child_contexts(context $context) {
6878 return $context->get_child_contexts();
6882 * Precreates all contexts including all parents
6884 * @deprecated since 2.2
6885 * @param int $contextlevel empty means all
6886 * @param bool $buildpaths update paths and depths
6887 * @return void
6889 function create_contexts($contextlevel = null, $buildpaths = true) {
6890 context_helper::create_instances($contextlevel, $buildpaths);
6894 * Remove stale context records
6896 * @deprecated since 2.2, use context_helper::cleanup_instances() instead
6897 * @return bool
6899 function cleanup_contexts() {
6900 context_helper::cleanup_instances();
6901 return true;
6905 * Populate context.path and context.depth where missing.
6907 * @deprecated since 2.2, use context_helper::build_all_paths() instead
6908 * @param bool $force force a complete rebuild of the path and depth fields, defaults to false
6909 * @return void
6911 function build_context_path($force = false) {
6912 context_helper::build_all_paths($force);
6916 * Rebuild all related context depth and path caches
6918 * @deprecated
6919 * @param array $fixcontexts array of contexts, strongtyped
6920 * @return void
6922 function rebuild_contexts(array $fixcontexts) {
6923 foreach ($fixcontexts as $fixcontext) {
6924 $fixcontext->reset_paths(false);
6926 context_helper::build_all_paths(false);
6930 * Preloads all contexts relating to a course: course, modules. Block contexts
6931 * are no longer loaded here. The contexts for all the blocks on the current
6932 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
6934 * @deprecated since 2.2
6935 * @param int $courseid Course ID
6936 * @return void
6938 function preload_course_contexts($courseid) {
6939 context_helper::preload_course($courseid);
6943 * Preloads context information together with instances.
6944 * Use context_instance_preload() to strip the context info from the record and cache the context instance.
6946 * @deprecated
6947 * @param string $joinon for example 'u.id'
6948 * @param string $contextlevel context level of instance in $joinon
6949 * @param string $tablealias context table alias
6950 * @return array with two values - select and join part
6952 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
6953 $select = ", ".context_helper::get_preload_record_columns_sql($tablealias);
6954 $join = "LEFT JOIN {context} $tablealias ON ($tablealias.instanceid = $joinon AND $tablealias.contextlevel = $contextlevel)";
6955 return array($select, $join);
6959 * Preloads context information from db record and strips the cached info.
6960 * The db request has to contain both the $join and $select from context_instance_preload_sql()
6962 * @deprecated since 2.2
6963 * @param stdClass $rec
6964 * @return void (modifies $rec)
6966 function context_instance_preload(stdClass $rec) {
6967 context_helper::preload_from_record($rec);
6971 * Mark a context as dirty (with timestamp) so as to force reloading of the context.
6973 * @deprecated since 2.2, use $context->mark_dirty() instead
6974 * @param string $path context path
6976 function mark_context_dirty($path) {
6977 global $CFG, $USER, $ACCESSLIB_PRIVATE;
6979 if (during_initial_install()) {
6980 return;
6983 // only if it is a non-empty string
6984 if (is_string($path) && $path !== '') {
6985 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
6986 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
6987 $ACCESSLIB_PRIVATE->dirtycontexts[$path] = 1;
6988 } else {
6989 if (CLI_SCRIPT) {
6990 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
6991 } else {
6992 if (isset($USER->access['time'])) {
6993 $ACCESSLIB_PRIVATE->dirtycontexts = get_cache_flags('accesslib/dirtycontexts', $USER->access['time']-2);
6994 } else {
6995 $ACCESSLIB_PRIVATE->dirtycontexts = array($path => 1);
6997 // flags not loaded yet, it will be done later in $context->reload_if_dirty()
7004 * Update the path field of the context and all dep. subcontexts that follow
7006 * Update the path field of the context and
7007 * all the dependent subcontexts that follow
7008 * the move.
7010 * The most important thing here is to be as
7011 * DB efficient as possible. This op can have a
7012 * massive impact in the DB.
7014 * @deprecated since 2.2
7015 * @param context $context context obj
7016 * @param context $newparent new parent obj
7017 * @return void
7019 function context_moved(context $context, context $newparent) {
7020 $context->update_moved($newparent);
7024 * Remove a context record and any dependent entries,
7025 * removes context from static context cache too
7027 * @deprecated since 2.2, use $context->delete_content() instead
7028 * @param int $contextlevel
7029 * @param int $instanceid
7030 * @param bool $deleterecord false means keep record for now
7031 * @return bool returns true or throws an exception
7033 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
7034 if ($deleterecord) {
7035 context_helper::delete_instance($contextlevel, $instanceid);
7036 } else {
7037 $classname = context_helper::get_class_for_level($contextlevel);
7038 if ($context = $classname::instance($instanceid, IGNORE_MISSING)) {
7039 $context->delete_content();
7043 return true;
7047 * Returns context level name
7048 * @deprecated since 2.2
7049 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
7050 * @return string the name for this type of context.
7052 function get_contextlevel_name($contextlevel) {
7053 return context_helper::get_level_name($contextlevel);
7057 * Prints human readable context identifier.
7059 * @deprecated since 2.2
7060 * @param context $context the context.
7061 * @param boolean $withprefix whether to prefix the name of the context with the
7062 * type of context, e.g. User, Course, Forum, etc.
7063 * @param boolean $short whether to user the short name of the thing. Only applies
7064 * to course contexts
7065 * @return string the human readable context name.
7067 function print_context_name(context $context, $withprefix = true, $short = false) {
7068 return $context->get_context_name($withprefix, $short);
7072 * Get a URL for a context, if there is a natural one. For example, for
7073 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
7074 * user profile page.
7076 * @deprecated since 2.2
7077 * @param context $context the context.
7078 * @return moodle_url
7080 function get_context_url(context $context) {
7081 return $context->get_url();
7085 * Is this context part of any course? if yes return course context,
7086 * if not return null or throw exception.
7088 * @deprecated since 2.2, use $context->get_course_context() instead
7089 * @param context $context
7090 * @return course_context context of the enclosing course, null if not found or exception
7092 function get_course_context(context $context) {
7093 return $context->get_course_context(true);
7097 * Returns current course id or null if outside of course based on context parameter.
7099 * @deprecated since 2.2, use $context->get_course_context instead
7100 * @param context $context
7101 * @return int|bool related course id or false
7103 function get_courseid_from_context(context $context) {
7104 if ($coursecontext = $context->get_course_context(false)) {
7105 return $coursecontext->instanceid;
7106 } else {
7107 return false;
7112 * Get an array of courses where cap requested is available
7113 * and user is enrolled, this can be relatively slow.
7115 * @deprecated since 2.2, use enrol_get_users_courses() instead
7116 * @param int $userid A user id. By default (null) checks the permissions of the current user.
7117 * @param string $cap - name of the capability
7118 * @param array $accessdata_ignored
7119 * @param bool $doanything_ignored
7120 * @param string $sort - sorting fields - prefix each fieldname with "c."
7121 * @param array $fields - additional fields you are interested in...
7122 * @param int $limit_ignored
7123 * @return array $courses - ordered array of course objects - see notes above
7125 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
7127 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
7128 foreach ($courses as $id=>$course) {
7129 $context = context_course::instance($id);
7130 if (!has_capability($cap, $context, $userid)) {
7131 unset($courses[$id]);
7135 return $courses;
7139 * Extracts the relevant capabilities given a contextid.
7140 * All case based, example an instance of forum context.
7141 * Will fetch all forum related capabilities, while course contexts
7142 * Will fetch all capabilities
7144 * capabilities
7145 * `name` varchar(150) NOT NULL,
7146 * `captype` varchar(50) NOT NULL,
7147 * `contextlevel` int(10) NOT NULL,
7148 * `component` varchar(100) NOT NULL,
7150 * @deprecated since 2.2
7151 * @param context $context
7152 * @return array
7154 function fetch_context_capabilities(context $context) {
7155 return $context->get_capabilities();
7159 * Runs get_records select on context table and returns the result
7160 * Does get_records_select on the context table, and returns the results ordered
7161 * by contextlevel, and then the natural sort order within each level.
7162 * for the purpose of $select, you need to know that the context table has been
7163 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
7165 * @deprecated since 2.2
7166 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
7167 * @param array $params any parameters required by $select.
7168 * @return array the requested context records.
7170 function get_sorted_contexts($select, $params = array()) {
7172 //TODO: we should probably rewrite all the code that is using this thing, the trouble is we MUST NOT modify the context instances...
7174 global $DB;
7175 if ($select) {
7176 $select = 'WHERE ' . $select;
7178 return $DB->get_records_sql("
7179 SELECT ctx.*
7180 FROM {context} ctx
7181 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
7182 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
7183 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
7184 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
7185 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
7186 $select
7187 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
7188 ", $params);
7192 * This is really slow!!! do not use above course context level
7194 * @deprecated since 2.2
7195 * @param int $roleid
7196 * @param context $context
7197 * @return array
7199 function get_role_context_caps($roleid, context $context) {
7200 global $DB;
7202 //this is really slow!!!! - do not use above course context level!
7203 $result = array();
7204 $result[$context->id] = array();
7206 // first emulate the parent context capabilities merging into context
7207 $searchcontexts = array_reverse($context->get_parent_context_ids(true));
7208 foreach ($searchcontexts as $cid) {
7209 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7210 foreach ($capabilities as $cap) {
7211 if (!array_key_exists($cap->capability, $result[$context->id])) {
7212 $result[$context->id][$cap->capability] = 0;
7214 $result[$context->id][$cap->capability] += $cap->permission;
7219 // now go through the contexts bellow given context
7220 $searchcontexts = array_keys($context->get_child_contexts());
7221 foreach ($searchcontexts as $cid) {
7222 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
7223 foreach ($capabilities as $cap) {
7224 if (!array_key_exists($cap->contextid, $result)) {
7225 $result[$cap->contextid] = array();
7227 $result[$cap->contextid][$cap->capability] = $cap->permission;
7232 return $result;
7236 * Gets a string for sql calls, searching for stuff in this context or above
7238 * NOTE: use $DB->get_in_or_equal($context->get_parent_context_ids()...
7240 * @deprecated since 2.2, $context->use get_parent_context_ids() instead
7241 * @param context $context
7242 * @return string
7244 function get_related_contexts_string(context $context) {
7246 if ($parents = $context->get_parent_context_ids()) {
7247 return (' IN ('.$context->id.','.implode(',', $parents).')');
7248 } else {
7249 return (' ='.$context->id);