3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * This file contains functions for managing user access
21 * <b>Public API vs internals</b>
23 * General users probably only care about
26 * - get_context_instance()
27 * - get_context_instance_by_id()
28 * - get_parent_contexts()
29 * - get_child_contexts()
31 * Whether the user can do something...
33 * - has_any_capability()
34 * - has_all_capabilities()
35 * - require_capability()
36 * - require_login() (from moodlelib)
38 * What courses has this user access to?
39 * - get_user_courses_bycap()
41 * What users can do X in this context?
42 * - get_users_by_capability()
45 * - enrol_into_course()
46 * - role_assign()/role_unassign()
50 * - load_all_capabilities()
51 * - reload_all_capabilities()
52 * - has_capability_in_accessdata()
54 * - get_user_access_sitewide()
56 * - get_role_access_bycontext()
58 * <b>Name conventions</b>
64 * Access control data is held in the "accessdata" array
65 * which - for the logged-in user, will be in $USER->access
67 * For other users can be generated and passed around (but may also be cached
68 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser.
70 * $accessdata is a multidimensional array, holding
71 * role assignments (RAs), role-capabilities-perm sets
72 * (role defs) and a list of courses we have loaded
75 * Things are keyed on "contextpaths" (the path field of
76 * the context table) for fast walking up/down the tree.
78 * $accessdata[ra][$contextpath]= array($roleid)
79 * [$contextpath]= array($roleid)
80 * [$contextpath]= array($roleid)
83 * Role definitions are stored like this
84 * (no cap merge is done - so it's compact)
87 * $accessdata[rdef][$contextpath:$roleid][mod/forum:viewpost] = 1
88 * [mod/forum:editallpost] = -1
89 * [mod/forum:startdiscussion] = -1000
92 * See how has_capability_in_accessdata() walks up/down the tree.
94 * Normally - specially for the logged-in user, we only load
95 * rdef and ra down to the course level, but not below. This
96 * keeps accessdata small and compact. Below-the-course ra/rdef
97 * are loaded as needed. We keep track of which courses we
98 * have loaded ra/rdef in
100 * $accessdata[loaded] = array($contextpath, $contextpath)
103 * <b>Stale accessdata</b>
105 * For the logged-in user, accessdata is long-lived.
107 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
108 * context paths affected by changes. Any check at-or-below
109 * a dirty context will trigger a transparent reload of accessdata.
111 * Changes at the system level will force the reload for everyone.
113 * <b>Default role caps</b>
114 * The default role assignment is not in the DB, so we
115 * add it manually to accessdata.
117 * This means that functions that work directly off the
118 * DB need to ensure that the default role caps
119 * are dealt with appropriately.
123 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
124 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
127 defined('MOODLE_INTERNAL') || die();
129 /** permission definitions */
130 define('CAP_INHERIT', 0);
131 /** permission definitions */
132 define('CAP_ALLOW', 1);
133 /** permission definitions */
134 define('CAP_PREVENT', -1);
135 /** permission definitions */
136 define('CAP_PROHIBIT', -1000);
138 /** context definitions */
139 define('CONTEXT_SYSTEM', 10);
140 /** context definitions */
141 define('CONTEXT_USER', 30);
142 /** context definitions */
143 define('CONTEXT_COURSECAT', 40);
144 /** context definitions */
145 define('CONTEXT_COURSE', 50);
146 /** context definitions */
147 define('CONTEXT_MODULE', 70);
148 /** context definitions */
149 define('CONTEXT_BLOCK', 80);
151 /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
152 define('RISK_MANAGETRUST', 0x0001);
153 /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
154 define('RISK_CONFIG', 0x0002);
155 /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
156 define('RISK_XSS', 0x0004);
157 /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
158 define('RISK_PERSONAL', 0x0008);
159 /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
160 define('RISK_SPAM', 0x0010);
161 /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
162 define('RISK_DATALOSS', 0x0020);
164 /** rolename displays - the name as defined in the role definition */
165 define('ROLENAME_ORIGINAL', 0);
166 /** rolename displays - the name as defined by a role alias */
167 define('ROLENAME_ALIAS', 1);
168 /** rolename displays - Both, like this: Role alias (Original)*/
169 define('ROLENAME_BOTH', 2);
170 /** rolename displays - the name as defined in the role definition and the shortname in brackets*/
171 define('ROLENAME_ORIGINALANDSHORT', 3);
172 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing*/
173 define('ROLENAME_ALIAS_RAW', 4);
174 /** rolename displays - the name is simply short role name*/
175 define('ROLENAME_SHORT', 5);
177 /** size limit for context cache */
178 if (!defined('MAX_CONTEXT_CACHE_SIZE')) {
179 define('MAX_CONTEXT_CACHE_SIZE', 5000);
183 * Although this looks like a global variable, it isn't really.
185 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
186 * It is used to cache various bits of data between function calls for performance reasons.
187 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
188 * as methods of a class, instead of functions.
190 * @global stdClass $ACCESSLIB_PRIVATE
191 * @name $ACCESSLIB_PRIVATE
193 global $ACCESSLIB_PRIVATE;
194 $ACCESSLIB_PRIVATE = new stdClass;
195 $ACCESSLIB_PRIVATE->contexts = array(); // Cache of context objects by level and instance
196 $ACCESSLIB_PRIVATE->contextsbyid = array(); // Cache of context objects by id
197 $ACCESSLIB_PRIVATE->systemcontext = NULL; // Used in get_system_context
198 $ACCESSLIB_PRIVATE->dirtycontexts = NULL; // Dirty contexts cache
199 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the $accessdata structure for users other than $USER
200 $ACCESSLIB_PRIVATE->roledefinitions = array(); // role definitions cache - helps a lot with mem usage in cron
201 $ACCESSLIB_PRIVATE->croncache = array(); // Used in get_role_access
202 $ACCESSLIB_PRIVATE->preloadedcourses = array(); // Used in preload_course_contexts.
203 $ACCESSLIB_PRIVATE->capabilities = NULL; // detailed information about the capabilities
206 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
208 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
209 * accesslib's private caches. You need to do this before setting up test data,
210 * and also at the end of the tests.
215 function accesslib_clear_all_caches_for_unit_testing() {
216 global $UNITTEST, $USER, $ACCESSLIB_PRIVATE;
217 if (empty($UNITTEST->running)) {
218 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
220 $ACCESSLIB_PRIVATE->contexts = array();
221 $ACCESSLIB_PRIVATE->contextsbyid = array();
222 $ACCESSLIB_PRIVATE->systemcontext = NULL;
223 $ACCESSLIB_PRIVATE->dirtycontexts = NULL;
224 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
225 $ACCESSLIB_PRIVATE->roledefinitions = array();
226 $ACCESSLIB_PRIVATE->croncache = array();
227 $ACCESSLIB_PRIVATE->preloadedcourses = array();
228 $ACCESSLIB_PRIVATE->capabilities = NULL;
230 unset($USER->access);
234 * Private function. Add a context object to accesslib's caches.
236 * @param object $context
238 function cache_context($context) {
239 global $ACCESSLIB_PRIVATE;
241 // If there are too many items in the cache already, remove items until
243 while (count($ACCESSLIB_PRIVATE->contextsbyid) >= MAX_CONTEXT_CACHE_SIZE) {
244 $first = reset($ACCESSLIB_PRIVATE->contextsbyid);
245 unset($ACCESSLIB_PRIVATE->contextsbyid[$first->id]);
246 unset($ACCESSLIB_PRIVATE->contexts[$first->contextlevel][$first->instanceid]);
249 $ACCESSLIB_PRIVATE->contexts[$context->contextlevel][$context->instanceid] = $context;
250 $ACCESSLIB_PRIVATE->contextsbyid[$context->id] = $context;
254 * This is really slow!!! do not use above course context level
258 * @param object $context
261 function get_role_context_caps($roleid, $context) {
264 //this is really slow!!!! - do not use above course context level!
266 $result[$context->id] = array();
268 // first emulate the parent context capabilities merging into context
269 $searchcontexts = array_reverse(get_parent_contexts($context));
270 array_push($searchcontexts, $context->id);
271 foreach ($searchcontexts as $cid) {
272 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
273 foreach ($capabilities as $cap) {
274 if (!array_key_exists($cap->capability, $result[$context->id])) {
275 $result[$context->id][$cap->capability] = 0;
277 $result[$context->id][$cap->capability] += $cap->permission;
282 // now go through the contexts bellow given context
283 $searchcontexts = array_keys(get_child_contexts($context));
284 foreach ($searchcontexts as $cid) {
285 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
286 foreach ($capabilities as $cap) {
287 if (!array_key_exists($cap->contextid, $result)) {
288 $result[$cap->contextid] = array();
290 $result[$cap->contextid][$cap->capability] = $cap->permission;
299 * Gets the accessdata for role "sitewide" (system down to course)
304 * @param array $accessdata defaults to NULL
307 function get_role_access($roleid, $accessdata=NULL) {
311 /* Get it in 1 cheap DB query...
312 * - relevant role caps at the root and down
313 * to the course level - but not below
315 if (is_null($accessdata)) {
316 $accessdata = array(); // named list
317 $accessdata['ra'] = array();
318 $accessdata['rdef'] = array();
319 $accessdata['loaded'] = array();
323 // Overrides for the role IN ANY CONTEXTS
324 // down to COURSE - not below -
326 $sql = "SELECT ctx.path,
327 rc.capability, rc.permission
329 JOIN {role_capabilities} rc
330 ON rc.contextid=ctx.id
332 AND ctx.contextlevel <= ".CONTEXT_COURSE."
333 ORDER BY ctx.depth, ctx.path";
334 $params = array($roleid);
336 // we need extra caching in CLI scripts and cron
338 global $ACCESSLIB_PRIVATE;
340 if (!isset($ACCESSLIB_PRIVATE->croncache[$roleid])) {
341 $ACCESSLIB_PRIVATE->croncache[$roleid] = array();
342 if ($rs = $DB->get_recordset_sql($sql, $params)) {
343 foreach ($rs as $rd) {
344 $ACCESSLIB_PRIVATE->croncache[$roleid][] = $rd;
350 foreach ($ACCESSLIB_PRIVATE->croncache[$roleid] as $rd) {
351 $k = "{$rd->path}:{$roleid}";
352 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
356 if ($rs = $DB->get_recordset_sql($sql, $params)) {
357 foreach ($rs as $rd) {
358 $k = "{$rd->path}:{$roleid}";
359 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
370 * Gets the accessdata for role "sitewide" (system down to course)
375 * @param array $accessdata defaults to NULL
378 function get_default_frontpage_role_access($roleid, $accessdata=NULL) {
382 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
383 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
386 // Overrides for the role in any contexts related to the course
388 $sql = "SELECT ctx.path,
389 rc.capability, rc.permission
391 JOIN {role_capabilities} rc
392 ON rc.contextid=ctx.id
394 AND (ctx.id = ".SYSCONTEXTID." OR ctx.path LIKE ?)
395 AND ctx.contextlevel <= ".CONTEXT_COURSE."
396 ORDER BY ctx.depth, ctx.path";
397 $params = array($roleid, "$base/%");
399 if ($rs = $DB->get_recordset_sql($sql, $params)) {
400 foreach ($rs as $rd) {
401 $k = "{$rd->path}:{$roleid}";
402 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
413 * Get the default guest role
417 * @return object role
419 function get_guest_role() {
422 if (empty($CFG->guestroleid)) {
423 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
424 $guestrole = array_shift($roles); // Pick the first one
425 set_config('guestroleid', $guestrole->id);
428 debugging('Can not find any guest role!');
432 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
435 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
436 set_config('guestroleid', '');
437 return get_guest_role();
443 * Check whether a user has a particular capability in a given context.
446 * $context = get_context_instance(CONTEXT_MODULE, $cm->id);
447 * has_capability('mod/forum:replypost',$context)
449 * By default checks the capabilities of the current user, but you can pass a
450 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
452 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
453 * or capabilities with XSS, config or data loss risks.
455 * @param string $capability the name of the capability to check. For example mod/forum:view
456 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
457 * @param integer|object $user A user id or object. By default (NULL) checks the permissions of the current user.
458 * @param boolean $doanything If false, ignores effect of admin role assignment
459 * @return boolean true if the user has this capability. Otherwise false.
461 function has_capability($capability, $context, $user = NULL, $doanything=true) {
462 global $USER, $CFG, $DB, $SCRIPT, $ACCESSLIB_PRIVATE;
464 if (during_initial_install()) {
465 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cliupgrade.php") {
466 // we are in an installer - roles can not work yet
473 if (strpos($capability, 'moodle/legacy:') === 0) {
474 throw new coding_exception('Legacy capabilities can not be used any more!');
477 // the original $CONTEXT here was hiding serious errors
478 // for security reasons do not reuse previous context
479 if (empty($context)) {
480 debugging('Incorrect context specified');
483 if (!is_bool($doanything)) {
484 throw new coding_exception('Capability parameter "doanything" is wierd ("'.$doanything.'"). This has to be fixed in code.');
487 // make sure there is a real user specified
488 if ($user === NULL) {
489 $userid = !empty($USER->id) ? $USER->id : 0;
491 $userid = !empty($user->id) ? $user->id : $user;
494 // capability must exist
495 if (!$capinfo = get_capability_info($capability)) {
496 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
499 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
500 if (($capinfo->captype === 'write') or ((int)$capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
501 if (isguestuser($userid) or $userid == 0) {
506 if (is_null($context->path) or $context->depth == 0) {
507 //this should not happen
508 $contexts = array(SYSCONTEXTID, $context->id);
509 $context->path = '/'.SYSCONTEXTID.'/'.$context->id;
510 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()', DEBUG_DEVELOPER);
513 $contexts = explode('/', $context->path);
514 array_shift($contexts);
517 if (CLI_SCRIPT && !isset($USER->access)) {
518 // In cron, some modules setup a 'fake' $USER,
519 // ensure we load the appropriate accessdata.
520 if (isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
521 $ACCESSLIB_PRIVATE->dirtycontexts = NULL; //load fresh dirty contexts
523 load_user_accessdata($userid);
524 $ACCESSLIB_PRIVATE->dirtycontexts = array();
526 $USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
528 } else if (isset($USER->id) && ($USER->id == $userid) && !isset($USER->access)) {
529 // caps not loaded yet - better to load them to keep BC with 1.8
530 // not-logged-in user or $USER object set up manually first time here
531 load_all_capabilities();
532 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // reset the cache for other users too, the dirty contexts are empty now
533 $ACCESSLIB_PRIVATE->roledefinitions = array();
536 // Load dirty contexts list if needed
537 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
538 if (isset($USER->access['time'])) {
539 $ACCESSLIB_PRIVATE->dirtycontexts = get_dirty_contexts($USER->access['time']);
542 $ACCESSLIB_PRIVATE->dirtycontexts = array();
546 // Careful check for staleness...
547 if (count($ACCESSLIB_PRIVATE->dirtycontexts) !== 0 and is_contextpath_dirty($contexts, $ACCESSLIB_PRIVATE->dirtycontexts)) {
548 // reload all capabilities - preserving loginas, roleswitches, etc
549 // and then cleanup any marks of dirtyness... at least from our short
551 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
552 $ACCESSLIB_PRIVATE->roledefinitions = array();
555 load_user_accessdata($userid);
556 $USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
557 $ACCESSLIB_PRIVATE->dirtycontexts = array();
560 reload_all_capabilities();
564 // Find out if user is admin - it is not possible to override the doanything in any way
565 // and it is not possible to switch to admin role either.
567 if (is_siteadmin($userid)) {
568 if ($userid != $USER->id) {
571 // make sure switchrole is not used in this context
572 if (empty($USER->access['rsw'])) {
575 $parts = explode('/', trim($context->path, '/'));
578 foreach ($parts as $part) {
579 $path .= '/' . $part;
580 if (!empty($USER->access['rsw'][$path])) {
588 //ok, admin switched role in this context, let's use normal access control rules
592 // divulge how many times we are called
593 //// error_log("has_capability: id:{$context->id} path:{$context->path} userid:$userid cap:$capability");
595 if (isset($USER->id) && ($USER->id == $userid)) { // we must accept strings and integers in $userid
597 // For the logged in user, we have $USER->access
598 // which will have all RAs and caps preloaded for
599 // course and above contexts.
601 // Contexts below courses && contexts that do not
602 // hang from courses are loaded into $USER->access
603 // on demand, and listed in $USER->access[loaded]
605 if ($context->contextlevel <= CONTEXT_COURSE) {
606 // Course and above are always preloaded
607 return has_capability_in_accessdata($capability, $context, $USER->access);
609 // Load accessdata for below-the-course contexts
610 if (!path_inaccessdata($context->path,$USER->access)) {
611 // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
612 // $bt = debug_backtrace();
613 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
614 load_subcontext($USER->id, $context, $USER->access);
616 return has_capability_in_accessdata($capability, $context, $USER->access);
619 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
620 load_user_accessdata($userid);
623 if ($context->contextlevel <= CONTEXT_COURSE) {
624 // Course and above are always preloaded
625 return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
627 // Load accessdata for below-the-course contexts as needed
628 if (!path_inaccessdata($context->path, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
629 // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
630 // $bt = debug_backtrace();
631 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
632 load_subcontext($userid, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
634 return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
638 * Check if the user has any one of several capabilities from a list.
640 * This is just a utility method that calls has_capability in a loop. Try to put
641 * the capabilities that most users are likely to have first in the list for best
644 * There are probably tricks that could be done to improve the performance here, for example,
645 * check the capabilities that are already cached first.
647 * @see has_capability()
648 * @param array $capabilities an array of capability names.
649 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
650 * @param integer $userid A user id. By default (NULL) checks the permissions of the current user.
651 * @param boolean $doanything If false, ignore effect of admin role assignment
652 * @return boolean true if the user has any of these capabilities. Otherwise false.
654 function has_any_capability($capabilities, $context, $userid=NULL, $doanything=true) {
655 if (!is_array($capabilities)) {
656 debugging('Incorrect $capabilities parameter in has_any_capabilities() call - must be an array');
659 foreach ($capabilities as $capability) {
660 if (has_capability($capability, $context, $userid, $doanything)) {
668 * Check if the user has all the capabilities in a list.
670 * This is just a utility method that calls has_capability in a loop. Try to put
671 * the capabilities that fewest users are likely to have first in the list for best
674 * There are probably tricks that could be done to improve the performance here, for example,
675 * check the capabilities that are already cached first.
677 * @see has_capability()
678 * @param array $capabilities an array of capability names.
679 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
680 * @param integer $userid A user id. By default (NULL) checks the permissions of the current user.
681 * @param boolean $doanything If false, ignore effect of admin role assignment
682 * @return boolean true if the user has all of these capabilities. Otherwise false.
684 function has_all_capabilities($capabilities, $context, $userid=NULL, $doanything=true) {
685 if (!is_array($capabilities)) {
686 debugging('Incorrect $capabilities parameter in has_all_capabilities() call - must be an array');
689 foreach ($capabilities as $capability) {
690 if (!has_capability($capability, $context, $userid, $doanything)) {
698 * Check if the user is an admin at the site level.
700 * Please note that use of proper capabilities is always encouraged,
701 * this function is supposed to be used from core or for temporary hacks.
703 * @param int|object $user_or_id user id or user object
704 * @returns bool true if user is one of the administrators, false otherwise
706 function is_siteadmin($user_or_id = NULL) {
709 if ($user_or_id === NULL) {
713 if (empty($user_or_id)) {
716 if (!empty($user_or_id->id)) {
718 $userid = $user_or_id->id;
720 $userid = $user_or_id;
723 $siteadmins = explode(',', $CFG->siteadmins);
724 return in_array($userid, $siteadmins);
728 * Returns true if user has at least one role assign
729 * of 'coursecontact' role (is potentially listed in some course descriptions).
731 * @return unknown_type
733 function has_coursecontact_role($userid) {
736 if (empty($CFG->coursecontact)) {
740 FROM {role_assignments}
741 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
742 return $DB->record_exists_sql($sql, array('userid'=>$userid));
746 * @param string $path
749 function get_course_from_path($path) {
750 // assume that nothing is more than 1 course deep
751 if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
758 * @param string $path
759 * @param array $accessdata
762 function path_inaccessdata($path, $accessdata) {
763 if (empty($accessdata['loaded'])) {
767 // assume that contexts hang from sys or from a course
768 // this will only work well with stuff that hangs from a course
769 if (in_array($path, $accessdata['loaded'], true)) {
770 // error_log("found it!");
773 $base = '/' . SYSCONTEXTID;
774 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
776 if ($path === $base) {
779 if (in_array($path, $accessdata['loaded'], true)) {
787 * Does the user have a capability to do something?
789 * Walk the accessdata array and return true/false.
790 * Deals with prohibits, roleswitching, aggregating
793 * The main feature of here is being FAST and with no
798 * Switch Roles exits early
799 * ------------------------
800 * cap checks within a switchrole need to exit early
801 * in our bottom up processing so they don't "see" that
802 * there are real RAs that can do all sorts of things.
804 * Switch Role merges with default role
805 * ------------------------------------
806 * If you are a teacher in course X, you have at least
807 * teacher-in-X + defaultloggedinuser-sitewide. So in the
808 * course you'll have techer+defaultloggedinuser.
809 * We try to mimic that in switchrole.
811 * Permission evaluation
812 * ---------------------
813 * Originally there was an extremely complicated way
814 * to determine the user access that dealt with
815 * "locality" or role assignments and role overrides.
816 * Now we simply evaluate access for each role separately
817 * and then verify if user has at least one role with allow
818 * and at the same time no role with prohibit.
820 * @param string $capability
821 * @param object $context
822 * @param array $accessdata
825 function has_capability_in_accessdata($capability, $context, array $accessdata) {
828 if (empty($context->id)) {
829 throw new coding_exception('Invalid context specified');
832 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
833 $contextids = explode('/', trim($context->path, '/'));
834 $paths = array($context->path);
835 while ($contextids) {
836 array_pop($contextids);
837 $paths[] = '/' . implode('/', $contextids);
842 $switchedrole = false;
844 // Find out if role switched
845 if (!empty($accessdata['rsw'])) {
846 // From the bottom up...
847 foreach ($paths as $path) {
848 if (isset($accessdata['rsw'][$path])) {
849 // Found a switchrole assignment - check for that role _plus_ the default user role
850 $roles = array($accessdata['rsw'][$path]=>NULL, $CFG->defaultuserroleid=>NULL);
851 $switchedrole = true;
857 if (!$switchedrole) {
858 // get all users roles in this context and above
859 foreach ($paths as $path) {
860 if (isset($accessdata['ra'][$path])) {
861 foreach ($accessdata['ra'][$path] as $roleid) {
862 $roles[$roleid] = NULL;
868 // Now find out what access is given to each role, going bottom-->up direction
869 foreach ($roles as $roleid => $ignored) {
870 foreach ($paths as $path) {
871 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
872 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
873 if ($perm === CAP_PROHIBIT or is_null($roles[$roleid])) {
874 $roles[$roleid] = $perm;
879 // any CAP_PROHIBIT found means no permission for the user
880 if (array_search(CAP_PROHIBIT, $roles) !== false) {
884 // at least one CAP_ALLOW means the user has a permission
885 return (array_search(CAP_ALLOW, $roles) !== false);
889 * @param object $context
890 * @param array $accessdata
893 function aggregate_roles_from_accessdata($context, $accessdata) {
895 $path = $context->path;
897 // build $contexts as a list of "paths" of the current
898 // contexts and parents with the order top-to-bottom
899 $contexts = array($path);
900 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
902 array_unshift($contexts, $path);
905 $cc = count($contexts);
908 // From the bottom up...
909 for ($n=$cc-1;$n>=0;$n--) {
910 $ctxp = $contexts[$n];
911 if (isset($accessdata['ra'][$ctxp]) && count($accessdata['ra'][$ctxp])) {
912 // Found assignments on this leaf
913 $addroles = $accessdata['ra'][$ctxp];
914 $roles = array_merge($roles, $addroles);
918 return array_unique($roles);
922 * A convenience function that tests has_capability, and displays an error if
923 * the user does not have that capability.
925 * NOTE before Moodle 2.0, this function attempted to make an appropriate
926 * require_login call before checking the capability. This is no longer the case.
927 * You must call require_login (or one of its variants) if you want to check the
928 * user is logged in, before you call this function.
930 * @see has_capability()
932 * @param string $capability the name of the capability to check. For example mod/forum:view
933 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
934 * @param integer $userid A user id. By default (NULL) checks the permissions of the current user.
935 * @param bool $doanything If false, ignore effect of admin role assignment
936 * @param string $errorstring The error string to to user. Defaults to 'nopermissions'.
937 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
938 * @return void terminates with an error if the user does not have the given capability.
940 function require_capability($capability, $context, $userid = NULL, $doanything = true,
941 $errormessage = 'nopermissions', $stringfile = '') {
942 if (!has_capability($capability, $context, $userid, $doanything)) {
943 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
948 * Get an array of courses where cap requested is available
949 * and user is enrolled, this can be relatively slow.
951 * @param string $capability - name of the capability
952 * @param array $accessdata_ignored
953 * @param bool $doanything_ignored
954 * @param string $sort - sorting fields - prefix each fieldname with "c."
955 * @param array $fields - additional fields you are interested in...
956 * @param int $limit_ignored
957 * @return array $courses - ordered array of course objects - see notes above
959 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort='c.sortorder ASC', $fields=NULL, $limit_ignored=0) {
961 //TODO: this should be most probably deprecated
963 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
964 foreach ($courses as $id=>$course) {
965 $context = get_context_instance(CONTEXT_COURSE, $id);
966 if (!has_capability($cap, $context, $userid)) {
967 unset($courses[$id]);
976 * Return a nested array showing role assignments
977 * all relevant role capabilities for the user at
978 * site/course_category/course levels
980 * We do _not_ delve deeper than courses because the number of
981 * overrides at the module/block levels is HUGE.
983 * [ra] => [/path/][]=roleid
984 * [rdef] => [/path/:roleid][capability]=permission
985 * [loaded] => array('/path', '/path')
989 * @param $userid integer - the id of the user
991 function get_user_access_sitewide($userid) {
995 /* Get in 3 cheap DB queries...
997 * - relevant role caps
998 * - above and within this user's RAs
999 * - below this user's RAs - limited to course level
1002 $accessdata = array(); // named list
1003 $accessdata['ra'] = array();
1004 $accessdata['rdef'] = array();
1005 $accessdata['loaded'] = array();
1010 $sql = "SELECT ctx.path, ra.roleid
1011 FROM {role_assignments} ra
1012 JOIN {context} ctx ON ctx.id=ra.contextid
1013 WHERE ra.userid = ? AND ctx.contextlevel <= ".CONTEXT_COURSE;
1014 $params = array($userid);
1015 $rs = $DB->get_recordset_sql($sql, $params);
1018 // raparents collects paths & roles we need to walk up
1019 // the parenthood to build the rdef
1021 $raparents = array();
1023 foreach ($rs as $ra) {
1024 // RAs leafs are arrays to support multi
1025 // role assignments...
1026 if (!isset($accessdata['ra'][$ra->path])) {
1027 $accessdata['ra'][$ra->path] = array();
1029 array_push($accessdata['ra'][$ra->path], $ra->roleid);
1031 // Concatenate as string the whole path (all related context)
1032 // for this role. This is damn faster than using array_merge()
1033 // Will unique them later
1034 if (isset($raparents[$ra->roleid])) {
1035 $raparents[$ra->roleid] .= $ra->path;
1037 $raparents[$ra->roleid] = $ra->path;
1044 // Walk up the tree to grab all the roledefs
1045 // of interest to our user...
1047 // NOTE: we use a series of IN clauses here - which
1048 // might explode on huge sites with very convoluted nesting of
1049 // categories... - extremely unlikely that the number of categories
1050 // and roletypes is so large that we hit the limits of IN()
1053 foreach ($raparents as $roleid=>$strcontexts) {
1054 $contexts = implode(',', array_unique(explode('/', trim($strcontexts, '/'))));
1055 if ($contexts ==! '') {
1059 $clauses .= "(roleid=? AND contextid IN ($contexts))";
1060 $cparams[] = $roleid;
1064 if ($clauses !== '') {
1065 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1066 FROM {role_capabilities} rc
1068 ON rc.contextid=ctx.id
1072 $rs = $DB->get_recordset_sql($sql, $cparams);
1075 foreach ($rs as $rd) {
1076 $k = "{$rd->path}:{$rd->roleid}";
1077 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1085 // Overrides for the role assignments IN SUBCONTEXTS
1086 // (though we still do _not_ go below the course level.
1088 // NOTE that the JOIN w sctx is with 3-way triangulation to
1089 // catch overrides to the applicable role in any subcontext, based
1090 // on the path field of the parent.
1092 $sql = "SELECT sctx.path, ra.roleid,
1093 ctx.path AS parentpath,
1094 rco.capability, rco.permission
1095 FROM {role_assignments} ra
1097 ON ra.contextid=ctx.id
1099 ON (sctx.path LIKE " . $DB->sql_concat('ctx.path',"'/%'"). " )
1100 JOIN {role_capabilities} rco
1101 ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
1103 AND ctx.contextlevel <= ".CONTEXT_COURSECAT."
1104 AND sctx.contextlevel <= ".CONTEXT_COURSE."
1105 ORDER BY sctx.depth, sctx.path, ra.roleid";
1106 $params = array($userid);
1107 $rs = $DB->get_recordset_sql($sql, $params);
1109 foreach ($rs as $rd) {
1110 $k = "{$rd->path}:{$rd->roleid}";
1111 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1120 * Add to the access ctrl array the data needed by a user for a given context
1124 * @param integer $userid the id of the user
1125 * @param object $context needs path!
1126 * @param array $accessdata accessdata array
1128 function load_subcontext($userid, $context, &$accessdata) {
1132 /* Get the additional RAs and relevant rolecaps
1133 * - role assignments - with role_caps
1134 * - relevant role caps
1135 * - above this user's RAs
1136 * - below this user's RAs - limited to course level
1139 $base = "/" . SYSCONTEXTID;
1142 // Replace $context with the target context we will
1143 // load. Normally, this will be a course context, but
1144 // may be a different top-level context.
1149 // - BLOCK/PERSON/USER/COURSE(sitecourse) hanging from SYSTEM
1150 // - BLOCK/MODULE/GROUP hanging from a course
1152 // For course contexts, we _already_ have the RAs
1153 // but the cost of re-fetching is minimal so we don't care.
1155 if ($context->contextlevel !== CONTEXT_COURSE
1156 && $context->path !== "$base/{$context->id}") {
1157 // Case BLOCK/MODULE/GROUP hanging from a course
1158 // Assumption: the course _must_ be our parent
1159 // If we ever see stuff nested further this needs to
1160 // change to do 1 query over the exploded path to
1161 // find out which one is the course
1162 $courses = explode('/',get_course_from_path($context->path));
1163 $targetid = array_pop($courses);
1164 $context = get_context_instance_by_id($targetid);
1169 // Role assignments in the context and below
1171 $sql = "SELECT ctx.path, ra.roleid
1172 FROM {role_assignments} ra
1174 ON ra.contextid=ctx.id
1176 AND (ctx.path = ? OR ctx.path LIKE ?)
1177 ORDER BY ctx.depth, ctx.path, ra.roleid";
1178 $params = array($userid, $context->path, $context->path."/%");
1179 $rs = $DB->get_recordset_sql($sql, $params);
1182 // Read in the RAs, preventing duplicates
1185 $localroles = array();
1187 foreach ($rs as $ra) {
1188 if (!isset($accessdata['ra'][$ra->path])) {
1189 $accessdata['ra'][$ra->path] = array();
1191 // only add if is not a repeat caused
1192 // by capability join...
1193 // (this check is cheaper than in_array())
1194 if ($lastseen !== $ra->path.':'.$ra->roleid) {
1195 $lastseen = $ra->path.':'.$ra->roleid;
1196 array_push($accessdata['ra'][$ra->path], $ra->roleid);
1197 array_push($localroles, $ra->roleid);
1204 // Walk up and down the tree to grab all the roledefs
1205 // of interest to our user...
1208 // - we use IN() but the number of roles is very limited.
1210 $courseroles = aggregate_roles_from_accessdata($context, $accessdata);
1212 // Do we have any interesting "local" roles?
1213 $localroles = array_diff($localroles,$courseroles); // only "new" local roles
1214 $wherelocalroles='';
1215 if (count($localroles)) {
1216 // Role defs for local roles in 'higher' contexts...
1217 $contexts = substr($context->path, 1); // kill leading slash
1218 $contexts = str_replace('/', ',', $contexts);
1219 $localroleids = implode(',',$localroles);
1220 $wherelocalroles="OR (rc.roleid IN ({$localroleids})
1221 AND ctx.id IN ($contexts))" ;
1224 // We will want overrides for all of them
1226 if ($roleids = implode(',',array_merge($courseroles,$localroles))) {
1227 $whereroles = "rc.roleid IN ($roleids) AND";
1229 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1230 FROM {role_capabilities} rc
1232 ON rc.contextid=ctx.id
1234 (ctx.id=? OR ctx.path LIKE ?))
1236 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1237 $params = array($context->id, $context->path."/%");
1239 $newrdefs = array();
1240 if ($rs = $DB->get_recordset_sql($sql, $params)) {
1241 foreach ($rs as $rd) {
1242 $k = "{$rd->path}:{$rd->roleid}";
1243 if (!array_key_exists($k, $newrdefs)) {
1244 $newrdefs[$k] = array();
1246 $newrdefs[$k][$rd->capability] = $rd->permission;
1250 debugging('Bad SQL encountered!');
1253 compact_rdefs($newrdefs);
1254 foreach ($newrdefs as $key=>$value) {
1255 $accessdata['rdef'][$key] =& $newrdefs[$key];
1258 // error_log("loaded {$context->path}");
1259 $accessdata['loaded'][] = $context->path;
1263 * Add to the access ctrl array the data needed by a role for a given context.
1265 * The data is added in the rdef key.
1267 * This role-centric function is useful for role_switching
1268 * and to get an overview of what a role gets under a
1269 * given context and below...
1273 * @param integer $roleid the id of the user
1274 * @param object $context needs path!
1275 * @param array $accessdata accessdata array NULL by default
1278 function get_role_access_bycontext($roleid, $context, $accessdata=NULL) {
1282 /* Get the relevant rolecaps into rdef
1283 * - relevant role caps
1284 * - at ctx and above
1288 if (is_null($accessdata)) {
1289 $accessdata = array(); // named list
1290 $accessdata['ra'] = array();
1291 $accessdata['rdef'] = array();
1292 $accessdata['loaded'] = array();
1295 $contexts = substr($context->path, 1); // kill leading slash
1296 $contexts = str_replace('/', ',', $contexts);
1299 // Walk up and down the tree to grab all the roledefs
1300 // of interest to our role...
1302 // NOTE: we use an IN clauses here - which
1303 // might explode on huge sites with very convoluted nesting of
1304 // categories... - extremely unlikely that the number of nested
1305 // categories is so large that we hit the limits of IN()
1307 $sql = "SELECT ctx.path, rc.capability, rc.permission
1308 FROM {role_capabilities} rc
1310 ON rc.contextid=ctx.id
1311 WHERE rc.roleid=? AND
1312 ( ctx.id IN ($contexts) OR
1314 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1315 $params = array($roleid, $context->path."/%");
1317 if ($rs = $DB->get_recordset_sql($sql, $params)) {
1318 foreach ($rs as $rd) {
1319 $k = "{$rd->path}:{$roleid}";
1320 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1329 * Load accessdata for a user into the $ACCESSLIB_PRIVATE->accessdatabyuser global
1331 * Used by has_capability() - but feel free
1332 * to call it if you are about to run a BIG
1333 * cron run across a bazillion users.
1337 * @param int $userid
1338 * @return array returns ACCESSLIB_PRIVATE->accessdatabyuser[userid]
1340 function load_user_accessdata($userid) {
1341 global $CFG, $ACCESSLIB_PRIVATE;
1343 $base = '/'.SYSCONTEXTID;
1345 $accessdata = get_user_access_sitewide($userid);
1346 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1348 // provide "default role" & set 'dr'
1350 if (!empty($CFG->defaultuserroleid)) {
1351 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1352 if (!isset($accessdata['ra'][$base])) {
1353 $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
1355 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
1357 $accessdata['dr'] = $CFG->defaultuserroleid;
1361 // provide "default frontpage role"
1363 if (!empty($CFG->defaultfrontpageroleid)) {
1364 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1365 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1366 if (!isset($accessdata['ra'][$base])) {
1367 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
1369 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
1372 // for dirty timestamps in cron
1373 $accessdata['time'] = time();
1375 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1376 compact_rdefs($ACCESSLIB_PRIVATE->accessdatabyuser[$userid]['rdef']);
1378 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1382 * Use shared copy of role definitions stored in ACCESSLIB_PRIVATE->roledefinitions;
1385 * @param array $rdefs array of role definitions in contexts
1387 function compact_rdefs(&$rdefs) {
1388 global $ACCESSLIB_PRIVATE;
1391 * This is a basic sharing only, we could also
1392 * use md5 sums of values. The main purpose is to
1393 * reduce mem in cron jobs - many users in $ACCESSLIB_PRIVATE->accessdatabyuser array.
1396 foreach ($rdefs as $key => $value) {
1397 if (!array_key_exists($key, $ACCESSLIB_PRIVATE->roledefinitions)) {
1398 $ACCESSLIB_PRIVATE->roledefinitions[$key] = $rdefs[$key];
1400 $rdefs[$key] =& $ACCESSLIB_PRIVATE->roledefinitions[$key];
1405 * A convenience function to completely load all the capabilities
1406 * for the current user. This is what gets called from complete_user_login()
1407 * for example. Call it only _after_ you've setup $USER and called
1408 * check_enrolment_plugins();
1409 * @see check_enrolment_plugins()
1415 function load_all_capabilities() {
1416 global $CFG, $ACCESSLIB_PRIVATE;
1418 //NOTE: we can not use $USER here because it may no be linked to $_SESSION['USER'] yet!
1420 // roles not installed yet - we are in the middle of installation
1421 if (during_initial_install()) {
1425 $base = '/'.SYSCONTEXTID;
1427 if (isguestuser($_SESSION['USER'])) {
1428 $guest = get_guest_role();
1431 $_SESSION['USER']->access = get_role_access($guest->id);
1432 // Put the ghost enrolment in place...
1433 $_SESSION['USER']->access['ra'][$base] = array($guest->id);
1436 } else if (!empty($_SESSION['USER']->id)) { // can not use isloggedin() yet
1438 $accessdata = get_user_access_sitewide($_SESSION['USER']->id);
1441 // provide "default role" & set 'dr'
1443 if (!empty($CFG->defaultuserroleid)) {
1444 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1445 if (!isset($accessdata['ra'][$base])) {
1446 $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
1448 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
1450 $accessdata['dr'] = $CFG->defaultuserroleid;
1453 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1456 // provide "default frontpage role"
1458 if (!empty($CFG->defaultfrontpageroleid)) {
1459 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1460 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1461 if (!isset($accessdata['ra'][$base])) {
1462 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
1464 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
1467 $_SESSION['USER']->access = $accessdata;
1469 } else if (!empty($CFG->notloggedinroleid)) {
1470 $_SESSION['USER']->access = get_role_access($CFG->notloggedinroleid);
1471 $_SESSION['USER']->access['ra'][$base] = array($CFG->notloggedinroleid);
1474 // Timestamp to read dirty context timestamps later
1475 $_SESSION['USER']->access['time'] = time();
1476 $ACCESSLIB_PRIVATE->dirtycontexts = array();
1478 // Clear to force a refresh
1479 unset($_SESSION['USER']->mycourses);
1483 * A convenience function to completely reload all the capabilities
1484 * for the current user when roles have been updated in a relevant
1485 * context -- but PRESERVING switchroles and loginas.
1487 * That is - completely transparent to the user.
1489 * Note: rewrites $USER->access completely.
1494 function reload_all_capabilities() {
1497 // error_log("reloading");
1500 if (isset($USER->access['rsw'])) {
1501 $sw = $USER->access['rsw'];
1502 // error_log(print_r($sw,1));
1505 unset($USER->access);
1506 unset($USER->mycourses);
1508 load_all_capabilities();
1510 foreach ($sw as $path => $roleid) {
1511 $context = $DB->get_record('context', array('path'=>$path));
1512 role_switch($roleid, $context);
1518 * Adds a temp role to an accessdata array.
1520 * Useful for the "temporary guest" access
1521 * we grant to logged-in users.
1523 * Note - assumes a course context!
1525 * @param object $content
1526 * @param int $roleid
1527 * @param array $accessdata
1528 * @return array Returns access data
1530 function load_temp_role($context, $roleid, array $accessdata) {
1534 // Load rdefs for the role in -
1536 // - all the parents
1537 // - and below - IOWs overrides...
1540 // turn the path into a list of context ids
1541 $contexts = substr($context->path, 1); // kill leading slash
1542 $contexts = str_replace('/', ',', $contexts);
1544 $sql = "SELECT ctx.path, rc.capability, rc.permission
1546 JOIN {role_capabilities} rc
1547 ON rc.contextid=ctx.id
1548 WHERE (ctx.id IN ($contexts)
1551 ORDER BY ctx.depth, ctx.path";
1552 $params = array($context->path."/%", $roleid);
1553 if ($rs = $DB->get_recordset_sql($sql, $params)) {
1554 foreach ($rs as $rd) {
1555 $k = "{$rd->path}:{$roleid}";
1556 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1562 // Say we loaded everything for the course context
1563 // - which we just did - if the user gets a proper
1564 // RA in this session, this data will need to be reloaded,
1565 // but that is handled by the complete accessdata reload
1567 array_push($accessdata['loaded'], $context->path);
1572 if (isset($accessdata['ra'][$context->path])) {
1573 array_push($accessdata['ra'][$context->path], $roleid);
1575 $accessdata['ra'][$context->path] = array($roleid);
1582 * Removes any extra guest roels from accessdata
1583 * @param object $context
1584 * @param array $accessdata
1585 * @return array access data
1587 function remove_temp_roles($context, array $accessdata) {
1589 $sql = "SELECT DISTINCT ra.roleid AS id
1590 FROM {role_assignments} ra
1591 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1592 $ras = $DB->get_records_sql($sql, array('contextid'=>$context->id, 'userid'=>$USER->id));
1594 $accessdata['ra'][$context->path] = array_keys($ras);
1599 * Returns array of all role archetypes.
1603 function get_role_archetypes() {
1605 'manager' => 'manager',
1606 'coursecreator' => 'coursecreator',
1607 'editingteacher' => 'editingteacher',
1608 'teacher' => 'teacher',
1609 'student' => 'student',
1612 'frontpage' => 'frontpage'
1617 * Assign the defaults found in this capability definition to roles that have
1618 * the corresponding legacy capabilities assigned to them.
1620 * @param string $capability
1621 * @param array $legacyperms an array in the format (example):
1622 * 'guest' => CAP_PREVENT,
1623 * 'student' => CAP_ALLOW,
1624 * 'teacher' => CAP_ALLOW,
1625 * 'editingteacher' => CAP_ALLOW,
1626 * 'coursecreator' => CAP_ALLOW,
1627 * 'manager' => CAP_ALLOW
1628 * @return boolean success or failure.
1630 function assign_legacy_capabilities($capability, $legacyperms) {
1632 $archetypes = get_role_archetypes();
1634 foreach ($legacyperms as $type => $perm) {
1636 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1637 if ($type === 'admin') {
1638 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1642 if (!array_key_exists($type, $archetypes)) {
1643 print_error('invalidlegacy', '', '', $type);
1646 if ($roles = get_archetype_roles($type)) {
1647 foreach ($roles as $role) {
1648 // Assign a site level capability.
1649 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1659 * @param object $capability a capability - a row from the capabilities table.
1660 * @return boolean whether this capability is safe - that is, whether people with the
1661 * safeoverrides capability should be allowed to change it.
1663 function is_safe_capability($capability) {
1664 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1667 /**********************************
1668 * Context Manipulation functions *
1669 **********************************/
1672 * Context creation - internal implementation.
1674 * Create a new context record for use by all roles-related stuff
1675 * assumes that the caller has done the homework.
1677 * DO NOT CALL THIS DIRECTLY, instead use {@link get_context_instance}!
1679 * @param int $contextlevel
1680 * @param int $instanceid
1681 * @param int $strictness
1682 * @return object newly created context
1684 function create_context($contextlevel, $instanceid, $strictness=IGNORE_MISSING) {
1688 if ($contextlevel == CONTEXT_SYSTEM) {
1689 return get_system_context();
1692 $context = new stdClass();
1693 $context->contextlevel = $contextlevel;
1694 $context->instanceid = $instanceid;
1696 // Define $context->path based on the parent
1697 // context. In other words... Who is your daddy?
1698 $basepath = '/' . SYSCONTEXTID;
1702 $error_message = NULL;
1704 switch ($contextlevel) {
1705 case CONTEXT_COURSECAT:
1706 $sql = "SELECT ctx.path, ctx.depth
1708 JOIN {course_categories} cc
1709 ON (cc.parent=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
1711 $params = array($instanceid);
1712 if ($p = $DB->get_record_sql($sql, $params)) {
1713 $basepath = $p->path;
1714 $basedepth = $p->depth;
1715 } else if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), '*', $strictness)) {
1716 if (empty($category->parent)) {
1717 // ok - this is a top category
1718 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $category->parent)) {
1719 $basepath = $parent->path;
1720 $basedepth = $parent->depth;
1722 // wrong parent category - no big deal, this can be fixed later
1727 // incorrect category id
1728 $error_message = "incorrect course category id ($instanceid)";
1733 case CONTEXT_COURSE:
1734 $sql = "SELECT ctx.path, ctx.depth
1737 ON (c.category=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
1738 WHERE c.id=? AND c.id !=" . SITEID;
1739 $params = array($instanceid);
1740 if ($p = $DB->get_record_sql($sql, $params)) {
1741 $basepath = $p->path;
1742 $basedepth = $p->depth;
1743 } else if ($course = $DB->get_record('course', array('id'=>$instanceid), '*', $strictness)) {
1744 if ($course->id == SITEID) {
1745 //ok - no parent category
1746 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
1747 $basepath = $parent->path;
1748 $basedepth = $parent->depth;
1750 // wrong parent category of course - no big deal, this can be fixed later
1754 } else if ($instanceid == SITEID) {
1755 // no errors for missing site course during installation
1758 // incorrect course id
1759 $error_message = "incorrect course id ($instanceid)";
1764 case CONTEXT_MODULE:
1765 $sql = "SELECT ctx.path, ctx.depth
1767 JOIN {course_modules} cm
1768 ON (cm.course=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
1770 $params = array($instanceid);
1771 if ($p = $DB->get_record_sql($sql, $params)) {
1772 $basepath = $p->path;
1773 $basedepth = $p->depth;
1774 } else if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), '*', $strictness)) {
1775 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course, $strictness)) {
1776 $basepath = $parent->path;
1777 $basedepth = $parent->depth;
1779 // course does not exist - modules can not exist without a course
1780 $error_message = "course does not exist ($cm->course) - modules can not exist without a course";
1784 // cm does not exist
1785 $error_message = "cm with id $instanceid does not exist";
1791 $sql = "SELECT ctx.path, ctx.depth
1793 JOIN {block_instances} bi ON (bi.parentcontextid=ctx.id)
1795 $params = array($instanceid, CONTEXT_COURSE);
1796 if ($p = $DB->get_record_sql($sql, $params, '*', $strictness)) {
1797 $basepath = $p->path;
1798 $basedepth = $p->depth;
1800 // block does not exist
1801 $error_message = 'block or parent context does not exist';
1806 // default to basepath
1810 // if grandparents unknown, maybe rebuild_context_path() will solve it later
1811 if ($basedepth != 0) {
1812 $context->depth = $basedepth+1;
1816 debugging('Error: could not insert new context level "'.
1817 s($contextlevel).'", instance "'.
1818 s($instanceid).'". ' . $error_message);
1823 $id = $DB->insert_record('context', $context);
1824 // can't set the full path till we know the id!
1825 if ($basedepth != 0 and !empty($basepath)) {
1826 $DB->set_field('context', 'path', $basepath.'/'. $id, array('id'=>$id));
1828 return get_context_instance_by_id($id);
1832 * Returns system context or NULL if can not be created yet.
1834 * @todo can not use get_record() because we do not know if query failed :-(
1835 * switch to get_record() later
1839 * @param bool $cache use caching
1840 * @return mixed system context or NULL
1842 function get_system_context($cache=true) {
1843 global $DB, $ACCESSLIB_PRIVATE;
1844 if ($cache and defined('SYSCONTEXTID')) {
1845 if (is_null($ACCESSLIB_PRIVATE->systemcontext)) {
1846 $ACCESSLIB_PRIVATE->systemcontext = new stdClass();
1847 $ACCESSLIB_PRIVATE->systemcontext->id = SYSCONTEXTID;
1848 $ACCESSLIB_PRIVATE->systemcontext->contextlevel = CONTEXT_SYSTEM;
1849 $ACCESSLIB_PRIVATE->systemcontext->instanceid = 0;
1850 $ACCESSLIB_PRIVATE->systemcontext->path = '/'.SYSCONTEXTID;
1851 $ACCESSLIB_PRIVATE->systemcontext->depth = 1;
1853 return $ACCESSLIB_PRIVATE->systemcontext;
1856 $context = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM));
1857 } catch (dml_exception $e) {
1858 //table does not exist yet, sorry
1863 $context = new stdClass();
1864 $context->contextlevel = CONTEXT_SYSTEM;
1865 $context->instanceid = 0;
1866 $context->depth = 1;
1867 $context->path = NULL; //not known before insert
1870 $context->id = $DB->insert_record('context', $context);
1871 } catch (dml_exception $e) {
1872 // can not create context yet, sorry
1877 if (!isset($context->depth) or $context->depth != 1 or $context->instanceid != 0 or $context->path != '/'.$context->id) {
1878 $context->instanceid = 0;
1879 $context->path = '/'.$context->id;
1880 $context->depth = 1;
1881 $DB->update_record('context', $context);
1884 if (!defined('SYSCONTEXTID')) {
1885 define('SYSCONTEXTID', $context->id);
1888 $ACCESSLIB_PRIVATE->systemcontext = $context;
1889 return $ACCESSLIB_PRIVATE->systemcontext;
1893 * Remove a context record and any dependent entries,
1894 * removes context from static context cache too
1897 * @param int $instanceid
1898 * @param bool $deleterecord false means keep record for now
1899 * @return bool returns true or throws an exception
1901 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
1902 global $DB, $ACCESSLIB_PRIVATE, $CFG;
1904 // do not use get_context_instance(), because the related object might not exist,
1905 // or the context does not exist yet and it would be created now
1906 if ($context = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
1907 // delete these first because they might fetch the context and try to recreate it!
1908 blocks_delete_all_for_context($context->id);
1909 filter_delete_all_for_context($context->id);
1911 require_once($CFG->dirroot . '/comment/lib.php');
1912 comment::delete_comments(array('contextid'=>$context->id));
1914 require_once($CFG->dirroot.'/rating/lib.php');
1915 $delopt = new stdclass();
1916 $delopt->contextid = $context->id;
1917 $rm = new rating_manager();
1918 $rm->delete_ratings($delopt);
1920 // delete all files attached to this context
1921 $fs = get_file_storage();
1922 $fs->delete_area_files($context->id);
1924 // now delete stuff from role related tables, role_unassign_all
1925 // and unenrol should be called earlier to do proper cleanup
1926 $DB->delete_records('role_assignments', array('contextid'=>$context->id));
1927 $DB->delete_records('role_capabilities', array('contextid'=>$context->id));
1928 $DB->delete_records('role_names', array('contextid'=>$context->id));
1930 // and finally it is time to delete the context record if requested
1931 if ($deleterecord) {
1932 $DB->delete_records('context', array('id'=>$context->id));
1933 // purge static context cache if entry present
1934 unset($ACCESSLIB_PRIVATE->contexts[$contextlevel][$instanceid]);
1935 unset($ACCESSLIB_PRIVATE->contextsbyid[$context->id]);
1938 // do not mark dirty contexts if parents unknown
1939 if (!is_null($context->path) and $context->depth > 0) {
1940 mark_context_dirty($context->path);
1948 * Precreates all contexts including all parents
1951 * @param int $contextlevel empty means all
1952 * @param bool $buildpaths update paths and depths
1955 function create_contexts($contextlevel=NULL, $buildpaths=true) {
1958 //make sure system context exists
1959 $syscontext = get_system_context(false);
1961 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSECAT
1962 or $contextlevel == CONTEXT_COURSE
1963 or $contextlevel == CONTEXT_MODULE
1964 or $contextlevel == CONTEXT_BLOCK) {
1965 $sql = "INSERT INTO {context} (contextlevel, instanceid)
1966 SELECT ".CONTEXT_COURSECAT.", cc.id
1967 FROM {course}_categories cc
1968 WHERE NOT EXISTS (SELECT 'x'
1970 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
1975 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSE
1976 or $contextlevel == CONTEXT_MODULE
1977 or $contextlevel == CONTEXT_BLOCK) {
1978 $sql = "INSERT INTO {context} (contextlevel, instanceid)
1979 SELECT ".CONTEXT_COURSE.", c.id
1981 WHERE NOT EXISTS (SELECT 'x'
1983 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
1988 if (empty($contextlevel) or $contextlevel == CONTEXT_MODULE
1989 or $contextlevel == CONTEXT_BLOCK) {
1990 $sql = "INSERT INTO {context} (contextlevel, instanceid)
1991 SELECT ".CONTEXT_MODULE.", cm.id
1992 FROM {course}_modules cm
1993 WHERE NOT EXISTS (SELECT 'x'
1995 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
1999 if (empty($contextlevel) or $contextlevel == CONTEXT_USER
2000 or $contextlevel == CONTEXT_BLOCK) {
2001 $sql = "INSERT INTO {context} (contextlevel, instanceid)
2002 SELECT ".CONTEXT_USER.", u.id
2005 AND NOT EXISTS (SELECT 'x'
2007 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
2012 if (empty($contextlevel) or $contextlevel == CONTEXT_BLOCK) {
2013 $sql = "INSERT INTO {context} (contextlevel, instanceid)
2014 SELECT ".CONTEXT_BLOCK.", bi.id
2015 FROM {block_instances} bi
2016 WHERE NOT EXISTS (SELECT 'x'
2018 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
2023 build_context_path(false);
2028 * Remove stale context records
2033 function cleanup_contexts() {
2036 $sql = " SELECT c.contextlevel,
2037 c.instanceid AS instanceid
2039 LEFT OUTER JOIN {course}_categories t
2040 ON c.instanceid = t.id
2041 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
2043 SELECT c.contextlevel,
2046 LEFT OUTER JOIN {course} t
2047 ON c.instanceid = t.id
2048 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
2050 SELECT c.contextlevel,
2053 LEFT OUTER JOIN {course}_modules t
2054 ON c.instanceid = t.id
2055 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
2057 SELECT c.contextlevel,
2060 LEFT OUTER JOIN {user} t
2061 ON c.instanceid = t.id
2062 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
2064 SELECT c.contextlevel,
2067 LEFT OUTER JOIN {block_instances} t
2068 ON c.instanceid = t.id
2069 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
2072 // transactions used only for performance reasons here
2073 $transaction = $DB->start_delegated_transaction();
2075 if ($rs = $DB->get_recordset_sql($sql)) {
2076 foreach ($rs as $ctx) {
2077 delete_context($ctx->contextlevel, $ctx->instanceid);
2082 $transaction->allow_commit();
2087 * Preloads all contexts relating to a course: course, modules. Block contexts
2088 * are no longer loaded here. The contexts for all the blocks on the current
2089 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
2091 * @param int $courseid Course ID
2094 function preload_course_contexts($courseid) {
2095 global $DB, $ACCESSLIB_PRIVATE;
2097 // Users can call this multiple times without doing any harm
2098 global $ACCESSLIB_PRIVATE;
2099 if (array_key_exists($courseid, $ACCESSLIB_PRIVATE->preloadedcourses)) {
2103 $params = array($courseid, $courseid, $courseid);
2104 $sql = "SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
2105 FROM {course_modules} cm
2106 JOIN {context} x ON x.instanceid=cm.id
2107 WHERE cm.course=? AND x.contextlevel=".CONTEXT_MODULE."
2111 SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
2113 WHERE x.instanceid=? AND x.contextlevel=".CONTEXT_COURSE."";
2115 $rs = $DB->get_recordset_sql($sql, $params);
2116 foreach($rs as $context) {
2117 cache_context($context);
2120 $ACCESSLIB_PRIVATE->preloadedcourses[$courseid] = true;
2124 * Get the context instance as an object. This function will create the
2125 * context instance if it does not exist yet.
2127 * @todo Remove code branch from previous fix MDL-9016 which is no longer needed
2129 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2130 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
2131 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
2132 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
2133 * MUST_EXIST means throw exception if no record or multiple records found
2134 * @return object The context object.
2136 function get_context_instance($contextlevel, $instance=0, $strictness=IGNORE_MISSING) {
2138 global $DB, $ACCESSLIB_PRIVATE;
2139 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK);
2141 /// System context has special cache
2142 if ($contextlevel == CONTEXT_SYSTEM) {
2143 return get_system_context();
2146 /// check allowed context levels
2147 if (!in_array($contextlevel, $allowed_contexts)) {
2148 // fatal error, code must be fixed - probably typo or switched parameters
2149 print_error('invalidcourselevel');
2152 if (!is_array($instance)) {
2154 if (isset($ACCESSLIB_PRIVATE->contexts[$contextlevel][$instance])) { // Already cached
2155 return $ACCESSLIB_PRIVATE->contexts[$contextlevel][$instance];
2158 /// Get it from the database, or create it
2159 if (!$context = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instance))) {
2160 $context = create_context($contextlevel, $instance, $strictness);
2163 /// Only add to cache if context isn't empty.
2164 if (!empty($context)) {
2165 cache_context($context);
2172 /// ok, somebody wants to load several contexts to save some db queries ;-)
2173 $instances = $instance;
2176 foreach ($instances as $key=>$instance) {
2177 /// Check the cache first
2178 if (isset($ACCESSLIB_PRIVATE->contexts[$contextlevel][$instance])) { // Already cached
2179 $result[$instance] = $ACCESSLIB_PRIVATE->contexts[$contextlevel][$instance];
2180 unset($instances[$key]);
2186 list($instanceids, $params) = $DB->get_in_or_equal($instances, SQL_PARAMS_QM);
2187 array_unshift($params, $contextlevel);
2188 $sql = "SELECT instanceid, id, contextlevel, path, depth
2190 WHERE contextlevel=? AND instanceid $instanceids";
2192 if (!$contexts = $DB->get_records_sql($sql, $params)) {
2193 $contexts = array();
2196 foreach ($instances as $instance) {
2197 if (isset($contexts[$instance])) {
2198 $context = $contexts[$instance];
2200 $context = create_context($contextlevel, $instance);
2203 if (!empty($context)) {
2204 cache_context($context);
2207 $result[$instance] = $context;
2216 * Get a context instance as an object, from a given context id.
2218 * @param mixed $id a context id or array of ids.
2219 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
2220 * MUST_EXIST means throw exception if no record or multiple records found
2221 * @return mixed object, array of the context object, or false.
2223 function get_context_instance_by_id($id, $strictness=IGNORE_MISSING) {
2224 global $DB, $ACCESSLIB_PRIVATE;
2226 if ($id == SYSCONTEXTID) {
2227 return get_system_context();
2230 if (isset($ACCESSLIB_PRIVATE->contextsbyid[$id])) { // Already cached
2231 return $ACCESSLIB_PRIVATE->contextsbyid[$id];
2234 if ($context = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
2235 cache_context($context);
2244 * Get the local override (if any) for a given capability in a role in a context
2247 * @param int $roleid
2248 * @param int $contextid
2249 * @param string $capability
2251 function get_local_override($roleid, $contextid, $capability) {
2253 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
2257 * Returns context instance plus related course and cm instances
2258 * @param int $contextid
2259 * @return array of ($context, $course, $cm)
2261 function get_context_info_array($contextid) {
2264 $context = get_context_instance_by_id($contextid, MUST_EXIST);
2268 if ($context->contextlevel == CONTEXT_COURSE) {
2269 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
2271 } else if ($context->contextlevel == CONTEXT_MODULE) {
2272 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
2273 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
2275 } else if ($context->contextlevel == CONTEXT_BLOCK) {
2276 $parentcontexts = get_parent_contexts($context, false);
2277 $parent = reset($parentcontexts);
2278 $parent = get_context_instance_by_id($parent);
2280 if ($parent->contextlevel == CONTEXT_COURSE) {
2281 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
2282 } else if ($parent->contextlevel == CONTEXT_MODULE) {
2283 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
2284 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
2288 return array($context, $course, $cm);
2292 * Returns current course id or null if outside of course based on context parameter.
2293 * @param object $context
2294 * @return int|bool related course id or false
2296 function get_courseid_from_context($context) {
2297 if ($context->contextlevel == CONTEXT_COURSE) {
2298 return $context->instanceid;
2301 if ($context->contextlevel < CONTEXT_COURSE) {
2305 if ($context->contextlevel == CONTEXT_MODULE) {
2306 $parentcontexts = get_parent_contexts($context, false);
2307 $parent = reset($parentcontexts);
2308 $parent = get_context_instance_by_id($parent);
2309 return $parent->instanceid;
2312 if ($context->contextlevel == CONTEXT_BLOCK) {
2313 $parentcontexts = get_parent_contexts($context, false);
2314 $parent = reset($parentcontexts);
2315 return get_courseid_from_context($parent);
2322 //////////////////////////////////////
2323 // DB TABLE RELATED FUNCTIONS //
2324 //////////////////////////////////////
2327 * function that creates a role
2330 * @param string $name role name
2331 * @param string $shortname role short name
2332 * @param string $description role description
2333 * @param string $archetype
2334 * @return mixed id or dml_exception
2336 function create_role($name, $shortname, $description, $archetype='') {
2339 if (strpos($archetype, 'moodle/legacy:') !== false) {
2340 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
2343 // verify role archetype actually exists
2344 $archetypes = get_role_archetypes();
2345 if (empty($archetypes[$archetype])) {
2349 // Get the system context.
2350 $context = get_context_instance(CONTEXT_SYSTEM);
2352 // Insert the role record.
2353 $role = new stdClass();
2354 $role->name = $name;
2355 $role->shortname = $shortname;
2356 $role->description = $description;
2357 $role->archetype = $archetype;
2359 //find free sortorder number
2360 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
2361 if (empty($role->sortorder)) {
2362 $role->sortorder = 1;
2364 $id = $DB->insert_record('role', $role);
2370 * Function that deletes a role and cleanups up after it
2372 * @param int $roleid id of role to delete
2373 * @return bool always true
2375 function delete_role($roleid) {
2378 // first unssign all users
2379 role_unassign_all(array('roleid'=>$roleid));
2381 // cleanup all references to this role, ignore errors
2382 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2383 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
2384 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
2385 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
2386 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
2387 $DB->delete_records('role_names', array('roleid'=>$roleid));
2388 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
2390 // finally delete the role itself
2391 // get this before the name is gone for logging
2392 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
2394 $DB->delete_records('role', array('id'=>$roleid));
2396 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
2402 * Function to write context specific overrides, or default capabilities.
2406 * @param string module string name
2407 * @param string capability string name
2408 * @param int contextid context id
2409 * @param int roleid role id
2410 * @param int permission int 1,-1 or -1000 should not be writing if permission is 0
2413 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2416 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
2417 unassign_capability($capability, $roleid, $contextid);
2421 $existing = $DB->get_record('role_capabilities', array('contextid'=>$contextid, 'roleid'=>$roleid, 'capability'=>$capability));
2423 if ($existing and !$overwrite) { // We want to keep whatever is there already
2427 $cap = new stdClass();
2428 $cap->contextid = $contextid;
2429 $cap->roleid = $roleid;
2430 $cap->capability = $capability;
2431 $cap->permission = $permission;
2432 $cap->timemodified = time();
2433 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
2436 $cap->id = $existing->id;
2437 $DB->update_record('role_capabilities', $cap);
2439 $c = $DB->get_record('context', array('id'=>$contextid));
2440 $DB->insert_record('role_capabilities', $cap);
2446 * Unassign a capability from a role.
2449 * @param int $roleid the role id
2450 * @param string $capability the name of the capability
2451 * @return boolean success or failure
2453 function unassign_capability($capability, $roleid, $contextid=NULL) {
2456 if (!empty($contextid)) {
2457 // delete from context rel, if this is the last override in this context
2458 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$contextid));
2460 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
2467 * Get the roles that have a given capability assigned to it
2469 * This function does not resolve the actual permission of the capability.
2470 * It just checks for permissions and overrides.
2471 * Use get_roles_with_cap_in_context() if resolution is required.
2473 * @param string $capability - capability name (string)
2474 * @param string $permission - optional, the permission defined for this capability
2475 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
2476 * @param stdClass $context, null means any
2477 * @return array of role objects
2479 function get_roles_with_capability($capability, $permission = null, $context = null) {
2483 $contexts = get_parent_contexts($context, true);
2484 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx000');
2485 $contextsql = "AND rc.contextid $insql";
2492 $permissionsql = " AND rc.permission = :permission";
2493 $params['permission'] = $permission;
2495 $permissionsql = '';
2500 WHERE r.id IN (SELECT rc.roleid
2501 FROM {role_capabilities} rc
2502 WHERE rc.capability = :capname
2505 $params['capname'] = $capability;
2508 return $DB->get_records_sql($sql, $params);
2513 * This function makes a role-assignment (a role for a user in a particular context)
2515 * @param int $roleid the role of the id
2516 * @param int $userid userid
2517 * @param int $contextid id of the context
2518 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
2519 * @prama int $itemid id of enrolment/auth plugin
2520 * @param string $timemodified defaults to current time
2521 * @return int new/existing id of the assignment
2523 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
2524 global $USER, $CFG, $DB;
2526 // first of all detect if somebody is using old style parameters
2527 if ($contextid === 0 or is_numeric($component)) {
2528 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
2531 // now validate all parameters
2532 if (empty($roleid)) {
2533 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
2536 if (empty($userid)) {
2537 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
2541 if (strpos($component, '_') === false) {
2542 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
2546 if ($component !== '' and strpos($component, '_') === false) {
2547 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
2551 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
2552 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
2556 $context = get_context_instance_by_id($contextid, MUST_EXIST);
2558 if (!$timemodified) {
2559 $timemodified = time();
2562 /// Check for existing entry
2563 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
2566 // role already assigned - this should not happen
2567 if (count($ras) > 1) {
2568 //very weird - remove all duplicates!
2569 $ra = array_shift($ras);
2570 foreach ($ras as $r) {
2571 $DB->delete_records('role_assignments', array('id'=>$r->id));
2577 // actually there is no need to update, reset anything or trigger any event, so just return
2581 // Create a new entry
2582 $ra = new stdClass();
2583 $ra->roleid = $roleid;
2584 $ra->contextid = $context->id;
2585 $ra->userid = $userid;
2586 $ra->component = $component;
2587 $ra->itemid = $itemid;
2588 $ra->timemodified = $timemodified;
2589 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
2591 $ra->id = $DB->insert_record('role_assignments', $ra);
2593 // mark context as dirty - again expensive, but needed
2594 mark_context_dirty($context->path);
2596 if (!empty($USER->id) && $USER->id == $userid) {
2597 // If the user is the current user, then do full reload of capabilities too.
2598 load_all_capabilities();
2601 events_trigger('role_assigned', $ra);
2607 * Removes one role assignment
2609 * @param int $roleid
2610 * @param int $userid
2611 * @param int $contextid
2612 * @param string $component
2613 * @param int $itemid
2616 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
2617 global $USER, $CFG, $DB;
2619 // first make sure the params make sense
2620 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
2621 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
2625 if (strpos($component, '_') === false) {
2626 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
2630 if ($component !== '' and strpos($component, '_') === false) {
2631 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
2635 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
2639 * Removes multiple role assignments, parameters may contain:
2640 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
2642 * @param array $params role assignment parameters
2643 * @param bool $subcontexts unassign in subcontexts too
2644 * @param bool $includmanual include manual role assignments too
2647 function role_unassign_all(array $params, $subcontexts = false, $includemanual=false) {
2648 global $USER, $CFG, $DB;
2651 throw new coding_exception('Missing parameters in role_unsassign_all() call');
2654 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
2655 foreach ($params as $key=>$value) {
2656 if (!in_array($key, $allowed)) {
2657 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
2661 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
2662 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
2665 if ($includemanual) {
2666 if (!isset($params['component']) or $params['component'] === '') {
2667 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
2672 if (empty($params['contextid'])) {
2673 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
2677 $ras = $DB->get_records('role_assignments', $params);
2678 foreach($ras as $ra) {
2679 $DB->delete_records('role_assignments', array('id'=>$ra->id));
2680 if ($context = get_context_instance_by_id($ra->contextid)) {
2681 // this is a bit expensive but necessary
2682 mark_context_dirty($context->path);
2683 /// If the user is the current user, then do full reload of capabilities too.
2684 if (!empty($USER->id) && $USER->id == $ra->userid) {
2685 load_all_capabilities();
2688 events_trigger('role_unassigned', $ra);
2692 // process subcontexts
2693 if ($subcontexts and $context = get_context_instance_by_id($params['contextid'])) {
2694 $contexts = get_child_contexts($context);
2696 foreach($contexts as $context) {
2697 $mparams['contextid'] = $context->id;
2698 $ras = $DB->get_records('role_assignments', $mparams);
2699 foreach($ras as $ra) {
2700 $DB->delete_records('role_assignments', array('id'=>$ra->id));
2701 // this is a bit expensive but necessary
2702 mark_context_dirty($context->path);
2703 /// If the user is the current user, then do full reload of capabilities too.
2704 if (!empty($USER->id) && $USER->id == $ra->userid) {
2705 load_all_capabilities();
2707 events_trigger('role_unassigned', $ra);
2712 // do this once more for all manual role assignments
2713 if ($includemanual) {
2714 $params['component'] = '';
2715 role_unassign_all($params, $subcontexts, false);
2721 * Determines if a user is currently logged in
2725 function isloggedin() {
2728 return (!empty($USER->id));
2732 * Determines if a user is logged in as real guest user with username 'guest'.
2734 * @param int|object $user mixed user object or id, $USER if not specified
2735 * @return bool true if user is the real guest user, false if not logged in or other user
2737 function isguestuser($user = NULL) {
2738 global $USER, $DB, $CFG;
2740 // make sure we have the user id cached in config table, because we are going to use it a lot
2741 if (empty($CFG->siteguest)) {
2742 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
2743 // guest does not exist yet, weird
2746 set_config('siteguest', $guestid);
2748 if ($user === NULL) {
2752 if ($user === NULL) {
2753 // happens when setting the $USER
2756 } else if (is_numeric($user)) {
2757 return ($CFG->siteguest == $user);
2759 } else if (is_object($user)) {
2760 if (empty($user->id)) {
2761 return false; // not logged in means is not be guest
2763 return ($CFG->siteguest == $user->id);
2767 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
2772 * Does user have a (temporary or real) guest access to course?
2774 * @param object $context
2775 * @param object|int $user
2778 function is_guest($context, $user = NULL) {
2781 // first find the course context
2782 $coursecontext = get_course_context($context);
2784 // make sure there is a real user specified
2785 if ($user === NULL) {
2786 $userid = !empty($USER->id) ? $USER->id : 0;
2788 $userid = !empty($user->id) ? $user->id : $user;
2791 if (isguestuser($userid)) {
2792 // can not inspect or be enrolled
2796 if (has_capability('moodle/course:view', $coursecontext, $user)) {
2797 // viewing users appear out of nowhere, they are neither guests nor participants
2801 // consider only real active enrolments here
2802 if (is_enrolled($coursecontext, $user, '', true)) {
2811 * Returns true if the user has moodle/course:view capability in the course,
2812 * this is intended for admins, managers (aka small admins), inspectors, etc.
2814 * @param object $context
2815 * @param int|object $user, if NULL $USER is used
2816 * @param string $withcapability extra capability name
2819 function is_viewing($context, $user = NULL, $withcapability = '') {
2822 // first find the course context
2823 $coursecontext = get_course_context($context);
2825 if (isguestuser($user)) {
2830 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2831 // admins are allowed to inspect courses
2835 if ($withcapability and !has_capability($withcapability, $context, $user)) {
2836 // site admins always have the capability, but the enrolment above blocks
2844 * Returns true if user is enrolled (is participating) in course
2845 * this is intended for students and teachers.
2847 * @param object $context
2848 * @param int|object $user, if NULL $USER is used, otherwise user object or id expected
2849 * @param string $withcapability extra capability name
2850 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2853 function is_enrolled($context, $user = NULL, $withcapability = '', $onlyactive = false) {
2856 // first find the course context
2857 $coursecontext = get_course_context($context);
2859 // make sure there is a real user specified
2860 if ($user === NULL) {
2861 $userid = !empty($USER->id) ? $USER->id : 0;
2863 $userid = !empty($user->id) ? $user->id : $user;
2866 if (empty($userid)) {
2869 } else if (isguestuser($userid)) {
2870 // guest account can not be enrolled anywhere
2874 if ($coursecontext->instanceid == SITEID) {
2875 // everybody participates on frontpage
2879 FROM {user_enrolments} ue
2880 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2881 JOIN {user} u ON u.id = ue.userid
2882 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
2883 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2884 // this result should be very small, better not do the complex time checks in sql for now ;-)
2885 $enrolments = $DB->get_records_sql($sql, $params);
2887 // make sure the enrol period is ok
2889 foreach ($enrolments as $e) {
2890 if ($e->timestart > $now) {
2893 if ($e->timeend and $e->timeend < $now) {
2904 // any enrolment is good for us here, even outdated, disabled or inactive
2906 FROM {user_enrolments} ue
2907 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2908 JOIN {user} u ON u.id = ue.userid
2909 WHERE ue.userid = :userid AND u.deleted = 0";
2910 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2911 if (!$DB->record_exists_sql($sql, $params)) {
2917 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2925 * Returns array with sql code and parameters returning all ids
2926 * of users enrolled into course.
2928 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2930 * @param object $context
2931 * @param string $withcapability
2932 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2933 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2934 * @return array list($sql, $params)
2936 function get_enrolled_sql($context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2939 // use unique prefix just in case somebody makes some SQL magic with the result
2942 $prefix = 'eu'.$i.'_';
2944 // first find the course context
2945 $coursecontext = get_course_context($context);
2947 $isfrontpage = ($coursecontext->instanceid == SITEID);
2953 list($contextids, $contextpaths) = get_context_info_list($context);
2955 // get all relevant capability info for all roles
2956 if ($withcapability) {
2957 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx00');
2958 $cparams['cap'] = $withcapability;
2961 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2962 FROM {role_capabilities} rc
2963 JOIN {context} ctx on rc.contextid = ctx.id
2964 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2965 $rcs = $DB->get_records_sql($sql, $cparams);
2966 foreach ($rcs as $rc) {
2967 $defs[$rc->path][$rc->roleid] = $rc->permission;
2971 if (!empty($defs)) {
2972 foreach ($contextpaths as $path) {
2973 if (empty($defs[$path])) {
2976 foreach($defs[$path] as $roleid => $perm) {
2977 if ($perm == CAP_PROHIBIT) {
2978 $access[$roleid] = CAP_PROHIBIT;
2981 if (!isset($access[$roleid])) {
2982 $access[$roleid] = (int)$perm;
2990 // make lists of roles that are needed and prohibited
2991 $needed = array(); // one of these is enough
2992 $prohibited = array(); // must not have any of these
2993 foreach ($access as $roleid => $perm) {
2994 if ($perm == CAP_PROHIBIT) {
2995 unset($needed[$roleid]);
2996 $prohibited[$roleid] = true;
2997 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2998 $needed[$roleid] = true;
3002 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : NULL;
3003 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : NULL;
3008 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
3010 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
3011 // everybody not having prohibit has the capability
3013 } else if (empty($needed)) {
3017 if (!empty($prohibited[$defaultuserroleid])) {
3019 } else if (!empty($needed[$defaultuserroleid])) {
3020 // everybody not having prohibit has the capability
3022 } else if (empty($needed)) {
3028 // nobody can match so return some SQL that does not return any results
3029 $wheres[] = "1 = 2";
3034 $ctxids = implode(',', $contextids);
3035 $roleids = implode(',', array_keys($needed));
3036 $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))";
3040 $ctxids = implode(',', $contextids);
3041 $roleids = implode(',', array_keys($prohibited));
3042 $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))";
3043 $wheres[] = "{$prefix}ra4.id IS NULL";
3047 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
3048 $params["{$prefix}gmid"] = $groupid;
3054 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
3055 $params["{$prefix}gmid"] = $groupid;
3059 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
3060 $params["{$prefix}guestid"] = $CFG->siteguest;
3063 // all users are "enrolled" on the frontpage
3065 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
3066 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
3067 $params[$prefix.'courseid'] = $coursecontext->instanceid;
3070 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
3071 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
3072 $now = round(time(), -2); // rounding helps caching in DB
3073 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
3074 $prefix.'active'=>ENROL_USER_ACTIVE,
3075 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
3079 $joins = implode("\n", $joins);
3080 $wheres = "WHERE ".implode(" AND ", $wheres);
3082 $sql = "SELECT DISTINCT {$prefix}u.id
3083 FROM {user} {$prefix}u
3087 return array($sql, $params);
3091 * Returns list of users enrolled into course.
3092 * @param object $context
3093 * @param string $withcapability
3094 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
3095 * @param string $userfields requested user record fields
3096 * @param string $orderby
3097 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
3098 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
3099 * @return array of user records
3101 function get_enrolled_users($context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
3104 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
3105 $sql = "SELECT $userfields
3107 JOIN ($esql) je ON je.id = u.id
3108 WHERE u.deleted = 0";
3111 $sql = "$sql ORDER BY $orderby";
3113 $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
3116 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3120 * Counts list of users enrolled into course (as per above function)
3121 * @param object $context
3122 * @param string $withcapability
3123 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
3124 * @return array of user records
3126 function count_enrolled_users($context, $withcapability = '', $groupid = 0) {
3129 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
3130 $sql = "SELECT count(u.id)
3132 JOIN ($esql) je ON je.id = u.id
3133 WHERE u.deleted = 0";
3135 return $DB->count_records_sql($sql, $params);
3140 * Loads the capability definitions for the component (from file).
3142 * Loads the capability definitions for the component (from file). If no
3143 * capabilities are defined for the component, we simply return an empty array.
3146 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
3147 * @return array array of capabilities
3149 function load_capability_def($component) {
3150 $defpath = get_component_directory($component).'/db/access.php';
3152 $capabilities = array();
3153 if (file_exists($defpath)) {
3155 if (!empty(${$component.'_capabilities'})) {
3156 // BC capability array name
3157 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
3158 debugging('componentname_capabilities array is deprecated, please use capabilities array only in access.php files');
3159 $capabilities = ${$component.'_capabilities'};
3163 return $capabilities;
3168 * Gets the capabilities that have been cached in the database for this component.
3169 * @param string $component - examples: 'moodle', 'mod_forum'
3170 * @return array array of capabilities
3172 function get_cached_capabilities($component='moodle') {
3174 return $DB->get_records('capabilities', array('component'=>$component));
3178 * Returns default capabilities for given role archetype.
3179 * @param string $archetype role archetype
3182 function get_default_capabilities($archetype) {
3190 $defaults = array();
3191 $components = array();
3192 $allcaps = $DB->get_records('capabilities');
3194 foreach ($allcaps as $cap) {
3195 if (!in_array($cap->component, $components)) {
3196 $components[] = $cap->component;
3197 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
3200 foreach($alldefs as $name=>$def) {
3201 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
3202 if (isset($def['archetypes'])) {
3203 if (isset($def['archetypes'][$archetype])) {
3204 $defaults[$name] = $def['archetypes'][$archetype];
3206 // 'legacy' is for backward compatibility with 1.9 access.php
3208 if (isset($def['legacy'][$archetype])) {
3209 $defaults[$name] = $def['legacy'][$archetype];
3218 * Reset role capabilities to default according to selected role archetype.
3219 * If no archetype selected, removes all capabilities.
3220 * @param int $roleid
3222 function reset_role_capabilities($roleid) {
3225 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
3226 $defaultcaps = get_default_capabilities($role->archetype);
3228 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
3230 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
3232 foreach($defaultcaps as $cap=>$permission) {
3233 assign_capability($cap, $permission, $roleid, $sitecontext->id);
3238 * Updates the capabilities table with the component capability definitions.
3239 * If no parameters are given, the function updates the core moodle
3242 * Note that the absence of the db/access.php capabilities definition file
3243 * will cause any stored capabilities for the component to be removed from
3247 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
3248 * @return boolean true if success, exception in case of any problems
3250 function update_capabilities($component='moodle') {
3251 global $DB, $OUTPUT, $ACCESSLIB_PRIVATE;
3253 $storedcaps = array();
3255 $filecaps = load_capability_def($component);
3256 $cachedcaps = get_cached_capabilities($component);
3258 foreach ($cachedcaps as $cachedcap) {
3259 array_push($storedcaps, $cachedcap->name);
3260 // update risk bitmasks and context levels in existing capabilities if needed
3261 if (array_key_exists($cachedcap->name, $filecaps)) {
3262 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
3263 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
3265 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
3266 $updatecap = new stdClass();
3267 $updatecap->id = $cachedcap->id;
3268 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
3269 $DB->update_record('capabilities', $updatecap);
3271 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
3272 $updatecap = new stdClass();
3273 $updatecap->id = $cachedcap->id;
3274 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
3275 $DB->update_record('capabilities', $updatecap);
3278 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
3279 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
3281 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
3282 $updatecap = new stdClass();
3283 $updatecap->id = $cachedcap->id;
3284 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
3285 $DB->update_record('capabilities', $updatecap);
3291 // Are there new capabilities in the file definition?
3294 foreach ($filecaps as $filecap => $def) {
3296 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
3297 if (!array_key_exists('riskbitmask', $def)) {
3298 $def['riskbitmask'] = 0; // no risk if not specified
3300 $newcaps[$filecap] = $def;
3303 // Add new capabilities to the stored definition.
3304 foreach ($newcaps as $capname => $capdef) {
3305 $capability = new stdClass();
3306 $capability->name = $capname;
3307 $capability->captype = $capdef['captype'];
3308 $capability->contextlevel = $capdef['contextlevel'];
3309 $capability->component = $component;
3310 $capability->riskbitmask = $capdef['riskbitmask'];
3312 $DB->insert_record('capabilities', $capability, false);
3314 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
3315 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
3316 foreach ($rolecapabilities as $rolecapability){
3317 //assign_capability will update rather than insert if capability exists
3318 if (!assign_capability($capname, $rolecapability->permission,
3319 $rolecapability->roleid, $rolecapability->contextid, true)){
3320 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
3324 // we ignore archetype key if we have cloned permissions
3325 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
3326 assign_legacy_capabilities($capname, $capdef['archetypes']);
3327 // 'legacy' is for backward compatibility with 1.9 access.php
3328 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
3329 assign_legacy_capabilities($capname, $capdef['legacy']);
3332 // Are there any capabilities that have been removed from the file
3333 // definition that we need to delete from the stored capabilities and
3334 // role assignments?
3335 capabilities_cleanup($component, $filecaps);
3337 // reset static caches
3338 $ACCESSLIB_PRIVATE->capabilities = NULL;
3345 * Deletes cached capabilities that are no longer needed by the component.
3346 * Also unassigns these capabilities from any roles that have them.
3349 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
3350 * @param array $newcapdef array of the new capability definitions that will be
3351 * compared with the cached capabilities
3352 * @return int number of deprecated capabilities that have been removed
3354 function capabilities_cleanup($component, $newcapdef=NULL) {
3359 if ($cachedcaps = get_cached_capabilities($component)) {
3360 foreach ($cachedcaps as $cachedcap) {
3361 if (empty($newcapdef) ||
3362 array_key_exists($cachedcap->name, $newcapdef) === false) {
3364 // Remove from capabilities cache.
3365 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
3367 // Delete from roles.
3368 if ($roles = get_roles_with_capability($cachedcap->name)) {
3369 foreach($roles as $role) {
3370 if (!unassign_capability($cachedcap->name, $role->id)) {
3371 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
3378 return $removedcount;
3388 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
3389 * @return string the name for this type of context.
3391 function get_contextlevel_name($contextlevel) {
3392 static $strcontextlevels = NULL;
3393 if (is_null($strcontextlevels)) {
3394 $strcontextlevels = array(
3395 CONTEXT_SYSTEM => get_string('coresystem'),
3396 CONTEXT_USER => get_string('user'),
3397 CONTEXT_COURSECAT => get_string('category'),
3398 CONTEXT_COURSE => get_string('course'),
3399 CONTEXT_MODULE => get_string('activitymodule'),
3400 CONTEXT_BLOCK => get_string('block')
3403 return $strcontextlevels[$contextlevel];
3407 * Prints human readable context identifier.
3410 * @param object $context the context.
3411 * @param boolean $withprefix whether to prefix the name of the context with the
3412 * type of context, e.g. User, Course, Forum, etc.
3413 * @param boolean $short whether to user the short name of the thing. Only applies
3414 * to course contexts
3415 * @return string the human readable context name.
3417 function print_context_name($context, $withprefix = true, $short = false) {
3421 switch ($context->contextlevel) {
3423 case CONTEXT_SYSTEM:
3424 $name = get_string('coresystem');
3428 if ($user = $DB->get_record('user', array('id'=>$context->instanceid))) {
3430 $name = get_string('user').': ';
3432 $name .= fullname($user);
3436 case CONTEXT_COURSECAT:
3437 if ($category = $DB->get_record('course_categories', array('id'=>$context->instanceid))) {
3439 $name = get_string('category').': ';
3441 $name .=format_string($category->name);
3445 case CONTEXT_COURSE:
3446 if ($context->instanceid == SITEID) {
3447 $name = get_string('frontpage', 'admin');
3449 if ($course = $DB->get_record('course', array('id'=>$context->instanceid))) {
3451 $name = get_string('course').': ';
3454 $name .= format_string($course->shortname);
3456 $name .= format_string($course->fullname);
3462 case CONTEXT_MODULE:
3463 if ($cm = $DB->get_record_sql('SELECT cm.*, md.name AS modname FROM {course_modules} cm ' .
3464 'JOIN {modules} md ON md.id = cm.module WHERE cm.id = ?', array($context->instanceid))) {
3465 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
3467 $name = get_string('modulename', $cm->modname).': ';
3469 $name .= $mod->name;
3475 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$context->instanceid))) {
3477 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
3478 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
3479 $blockname = "block_$blockinstance->blockname";
3480 if ($blockobject = new $blockname()) {
3482 $name = get_string('block').': ';
3484 $name .= $blockobject->title;
3490 print_error('unknowncontext');
3498 * Get a URL for a context, if there is a natural one. For example, for
3499 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
3500 * user profile page.
3502 * @param object $context the context.
3503 * @return moodle_url
3505 function get_context_url($context) {
3506 global $COURSE, $DB;
3508 switch ($context->contextlevel) {
3510 if ($COURSE->id == SITEID) {
3511 $url = new moodle_url('/user/profile.php', array('id'=>$context->instanceid));
3513 $url = new moodle_url('/user/view.php', array('id'=>$context->instanceid, 'courseid'=>$COURSE->id));
3517 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
3518 return new moodle_url('/course/category.php', array('id'=>$context->instanceid));
3520 case CONTEXT_COURSE: // 1 to 1 to course cat
3521 if ($context->instanceid != SITEID) {
3522 return new moodle_url('/course/view.php', array('id'=>$context->instanceid));
3526 case CONTEXT_MODULE: // 1 to 1 to course
3527 if ($modname = $DB->get_field_sql('SELECT md.name AS modname FROM {course_modules} cm ' .
3528 'JOIN {modules} md ON md.id = cm.module WHERE cm.id = ?', array($context->instanceid))) {
3529 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$context->instanceid));
3534 $parentcontexts = get_parent_contexts($context, false);
3535 $parent = reset($parentcontexts);
3536 $parent = get_context_instance_by_id($parent);
3537 return get_context_url($parent);
3540 return new moodle_url('/');
3544 * Returns an array of all the known types of risk
3545 * The array keys can be used, for example as CSS class names, or in calls to
3546 * print_risk_icon. The values are the corresponding RISK_ constants.
3548 * @return array all the known types of risk.
3550 function get_all_risks() {
3552 'riskmanagetrust' => RISK_MANAGETRUST,
3553 'riskconfig' => RISK_CONFIG,
3554 'riskxss' => RISK_XSS,
3555 'riskpersonal' => RISK_PERSONAL,
3556 'riskspam' => RISK_SPAM,
3557 'riskdataloss' => RISK_DATALOSS,
3562 * Return a link to moodle docs for a given capability name
3565 * @param object $capability a capability - a row from the mdl_capabilities table.
3566 * @return string the human-readable capability name as a link to Moodle Docs.
3568 function get_capability_docs_link($capability) {
3570 $url = get_docs_url('Capabilities/' . $capability->name);
3571 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
3575 * Extracts the relevant capabilities given a contextid.
3576 * All case based, example an instance of forum context.
3577 * Will fetch all forum related capabilities, while course contexts
3578 * Will fetch all capabilities
3581 * `name` varchar(150) NOT NULL,
3582 * `captype` varchar(50) NOT NULL,
3583 * `contextlevel` int(10) NOT NULL,
3584 * `component` varchar(100) NOT NULL,
3588 * @param object context
3591 function fetch_context_capabilities($context) {
3594 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
3598 switch ($context->contextlevel) {
3600 case CONTEXT_SYSTEM: // all
3602 FROM {capabilities}";
3606 $extracaps = array('moodle/grade:viewall');
3607 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap0');
3610 WHERE contextlevel = ".CONTEXT_USER."
3614 case CONTEXT_COURSECAT: // course category context and bellow
3617 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
3620 case CONTEXT_COURSE: // course context and bellow
3623 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
3626 case CONTEXT_MODULE: // mod caps
3627 $cm = $DB->get_record('course_modules', array('id'=>$context->instanceid));
3628 $module = $DB->get_record('modules', array('id'=>$cm->module));
3630 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
3631 if (file_exists($modfile)) {
3632 include_once($modfile);
3633 $modfunction = $module->name.'_get_extra_capabilities';
3634 if (function_exists($modfunction)) {
3635 $extracaps = $modfunction();
3638 if(empty($extracaps)) {
3639 $extracaps = array();
3642 // All modules allow viewhiddenactivities. This is so you can hide
3643 // the module then override to allow specific roles to see it.
3644 // The actual check is in course page so not module-specific
3645 $extracaps[]="moodle/course:viewhiddenactivities";
3646 list($extra, $params) = $DB->get_in_or_equal(
3647 $extracaps, SQL_PARAMS_NAMED, 'cap0');
3648 $extra = "OR name $extra";
3652 WHERE (contextlevel = ".CONTEXT_MODULE."
3653 AND component = :component)
3655 $params['component'] = "mod_$module->name";
3658 case CONTEXT_BLOCK: // block caps
3659 $bi = $DB->get_record('block_instances', array('id' => $context->instanceid));
3662 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
3664 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap0');
3665 $extra = "OR name $extra";
3670 WHERE (contextlevel = ".CONTEXT_BLOCK."
3671 AND component = :component)
3673 $params['component'] = 'block_' . $bi->blockname;
3680 if (!$records = $DB->get_records_sql($SQL.' '.$sort, $params)) {
3689 * This function pulls out all the resolved capabilities (overrides and
3690 * defaults) of a role used in capability overrides in contexts at a given
3694 * @param obj $context
3695 * @param int $roleid
3696 * @param string $cap capability, optional, defaults to ''
3697 * @param bool if set to true, resolve till this level, else stop at immediate parent level
3700 function role_context_capabilities($roleid, $context, $cap='') {
3703 $contexts = get_parent_contexts($context);
3704 $contexts[] = $context->id;
3705 $contexts = '('.implode(',', $contexts).')';
3707 $params = array($roleid);
3710 $search = " AND rc.capability = ? ";
3717 FROM {role_capabilities} rc, {context} c
3718 WHERE rc.contextid in $contexts
3720 AND rc.contextid = c.id $search
3721 ORDER BY c.contextlevel DESC, rc.capability DESC";
3723 $capabilities = array();
3725 if ($records = $DB->get_records_sql($sql, $params)) {
3726 // We are traversing via reverse order.
3727 foreach ($records as $record) {
3728 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3729 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
3730 $capabilities[$record->capability] = $record->permission;
3734 return $capabilities;
3738 * Recursive function which, given a context, find all parent context ids,
3739 * and return the array in reverse order, i.e. parent first, then grand
3742 * @param object $context
3743 * @param bool $capability optional, defaults to false
3746 function get_parent_contexts($context, $includeself = false) {
3748 if ($context->path == '') {
3752 $parentcontexts = substr($context->path, 1); // kill leading slash
3753 $parentcontexts = explode('/', $parentcontexts);
3754 if (!$includeself) {
3755 array_pop($parentcontexts); // and remove its own id
3758 return array_reverse($parentcontexts);
3762 * Return the id of the parent of this context, or false if there is no parent (only happens if this
3763 * is the site context.)
3765 * @param object $context
3766 * @return integer the id of the parent context.
3768 function get_parent_contextid($context) {
3769 $parentcontexts = get_parent_contexts($context);
3770 if (count($parentcontexts) == 0) {
3773 return array_shift($parentcontexts);
3777 * Constructs array with contextids as first parameter and context paths,
3778 * in both cases bottom top including self.
3780 * @param object $context
3783 function get_context_info_list($context) {
3784 $contextids = explode('/', ltrim($context->path, '/'));
3785 $contextpaths = array();
3786 $contextids2 = $contextids;
3787 while ($contextids2) {
3788 $contextpaths[] = '/' . implode('/', $contextids2);
3789 array_pop($contextids2);
3791 return array($contextids, $contextpaths);
3795 * Find course context
3796 * @param object $context - course or lower context
3797 * @return object context of the enclosing course, throws exception when related course context can not be found
3799 function get_course_context($context) {
3800 if (empty($context->contextlevel)) {
3801 throw new coding_exception('Invalid context parameter.');
3803 } if ($context->contextlevel == CONTEXT_COURSE) {
3806 } else if ($context->contextlevel == CONTEXT_MODULE) {
3807 return get_context_instance_by_id(get_parent_contextid($context, MUST_EXIST));
3809 } else if ($context->contextlevel == CONTEXT_BLOCK) {
3810 $parentcontext = get_context_instance_by_id(get_parent_contextid($context, MUST_EXIST));
3811 if ($parentcontext->contextlevel == CONTEXT_COURSE) {
3812 return $parentcontext;
3813 } else if ($parentcontext->contextlevel == CONTEXT_MODULE) {
3814 return get_context_instance_by_id(get_parent_contextid($parentcontext, MUST_EXIST));
3816 throw new coding_exception('Invalid level of block context parameter.');
3820 throw new coding_exception('Invalid context level of parameter.');
3824 * Check if context is the front page context or a context inside it
3826 * Returns true if this context is the front page context, or a context inside it,
3829 * @param object $context a context object.
3832 function is_inside_frontpage($context) {
3833 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
3834 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
3838 * Runs get_records select on context table and returns the result
3839 * Does get_records_select on the context table, and returns the results ordered
3840 * by contextlevel, and then the natural sort order within each level.
3841 * for the purpose of $select, you need to know that the context table has been
3842 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
3845 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
3846 * @param array $params any parameters required by $select.
3847 * @return array the requested context records.
3849 function get_sorted_contexts($select, $params = array()) {
3852 $select = 'WHERE ' . $select;
3854 return $DB->get_records_sql("
3857 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
3858 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
3859 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
3860 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
3861 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
3863 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
3868 * Recursive function which, given a context, find all its children context ids.
3870 * When called for a course context, it will return the modules and blocks
3871 * displayed in the course page.
3873 * For course category contexts it will return categories and courses. It will
3874 * NOT recurse into courses, nor return blocks on the category pages. If you
3875 * want to do that, call it on the returned courses.
3877 * If called on a course context it _will_ populate the cache with the appropriate
3880 * @param object $context.
3881 * @return array Array of child records
3883 function get_child_contexts($context) {
3885 global $DB, $ACCESSLIB_PRIVATE;
3887 // We *MUST* populate the context_cache as the callers
3888 // will probably ask for the full record anyway soon after
3889 // soon after calling us ;-)
3893 switch ($context->contextlevel) {
3899 case CONTEXT_MODULE:
3901 // - blocks under this context path.
3902 $sql = " SELECT ctx.*
3904 WHERE ctx.path LIKE ?
3905 AND ctx.contextlevel = ".CONTEXT_BLOCK;
3906 $params = array("{$context->path}/%", $context->instanceid);
3907 $records = $DB->get_recordset_sql($sql, $params);
3908 foreach ($records as $rec) {
3909 cache_context($rec);
3910 $array[$rec->id] = $rec;
3914 case CONTEXT_COURSE:
3916 // - modules and blocks under this context path.
3917 $sql = " SELECT ctx.*
3919 WHERE ctx.path LIKE ?
3920 AND ctx.contextlevel IN (".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
3921 $params = array("{$context->path}/%", $context->instanceid);
3922 $records = $DB->get_recordset_sql($sql, $params);
3923 foreach ($records as $rec) {
3924 cache_context($rec);
3925 $array[$rec->id] = $rec;
3929 case CONTEXT_COURSECAT:
3933 $sql = " SELECT ctx.*
3935 WHERE ctx.path LIKE ?
3936 AND ctx.contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.")";
3937 $params = array("{$context->path}/%");
3938 $records = $DB->get_recordset_sql($sql, $params);
3939 foreach ($records as $rec) {
3940 cache_context($rec);
3941 $array[$rec->id] = $rec;
3947 // - blocks under this context path.
3948 $sql = " SELECT ctx.*
3950 WHERE ctx.path LIKE ?
3951 AND ctx.contextlevel = ".CONTEXT_BLOCK;
3952 $params = array("{$context->path}/%", $context->instanceid);
3953 $records = $DB->get_recordset_sql($sql, $params);
3954 foreach ($records as $rec) {
3955 cache_context($rec);
3956 $array[$rec->id] = $rec;
3960 case CONTEXT_SYSTEM:
3961 // Just get all the contexts except for CONTEXT_SYSTEM level
3962 // and hope we don't OOM in the process - don't cache
3965 WHERE contextlevel != ".CONTEXT_SYSTEM;
3967 $records = $DB->get_records_sql($sql);
3968 foreach ($records as $rec) {
3969 $array[$rec->id] = $rec;
3974 print_error('unknowcontext', '', '', $context->contextlevel);
3982 * Gets a string for sql calls, searching for stuff in this context or above
3984 * @param object $context
3987 function get_related_contexts_string($context) {
3988 if ($parents = get_parent_contexts($context)) {
3989 return (' IN ('.$context->id.','.implode(',', $parents).')');
3991 return (' ='.$context->id);
3996 * Returns capability information (cached)
3998 * @param string $capabilityname
3999 * @return object or NULL if capability not found
4001 function get_capability_info($capabilityname) {
4002 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
4004 // TODO: cache this in shared memory if available, use new $CFG->roledefrev for version check
4006 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
4007 $ACCESSLIB_PRIVATE->capabilities = array();
4008 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
4009 foreach ($caps as $cap) {
4010 $capname = $cap->name;
4013 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
4017 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : NULL;
4021 * Returns the human-readable, translated version of the capability.
4022 * Basically a big switch statement.
4024 * @param string $capabilityname e.g. mod/choice:readresponses
4027 function get_capability_string($capabilityname) {
4029 // Typical capability name is 'plugintype/pluginname:capabilityname'
4030 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
4032 if ($type === 'moodle') {
4033 $component = 'core_role';
4034 } else if ($type === 'quizreport') {
4036 $component = 'quiz_'.$name;
4038 $component = $type.'_'.$name;
4041 $stringname = $name.':'.$capname;
4043 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
4044 return get_string($stringname, $component);
4047 $dir = get_component_directory($component);
4048 if (!file_exists($dir)) {
4049 // plugin broken or does not exist, do not bother with printing of debug message
4050 return $capabilityname.' ???';
4053 // something is wrong in plugin, better print debug
4054 return get_string($stringname, $component);
4059 * This gets the mod/block/course/core etc strings.
4061 * @param string $component
4062 * @param int $contextlevel
4063 * @return string|bool String is success, false if failed
4065 function get_component_string($component, $contextlevel) {
4067 if ($component === 'moodle' or $component === 'core') {
4068 switch ($contextlevel) {
4069 case CONTEXT_SYSTEM: return get_string('coresystem');
4070 case CONTEXT_USER: return get_string('users');
4071 case CONTEXT_COURSECAT: return get_string('categories');
4072 case CONTEXT_COURSE: return get_string('course');
4073 case CONTEXT_MODULE: return get_string('activities');
4074 case CONTEXT_BLOCK: return get_string('block');
4075 default: print_error('unknowncontext');
4079 list($type, $name) = normalize_component($component);
4080 $dir = get_plugin_directory($type, $name);
4081 if (!file_exists($dir)) {
4082 // plugin not installed, bad luck, there is no way to find the name
4083 return $component.' ???';
4087 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
4088 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
4089 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
4090 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
4091 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
4092 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
4093 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
4095 if (get_string_manager()->string_exists('pluginname', $component)) {
4096 return get_string('activity').': '.get_string('pluginname', $component);
4098 return get_string('activity').': '.get_string('modulename', $component);
4100 default: return get_string('pluginname', $component);
4105 * Gets the list of roles assigned to this context and up (parents)
4106 * from the list of roles that are visible on user profile page
4107 * and participants page.
4109 * @param object $context
4112 function get_profile_roles($context) {
4115 if (empty($CFG->profileroles)) {
4119 $allowed = explode(',', $CFG->profileroles);
4120 list($rallowed, $params) = $DB->get_in_or_equal($allowed, SQL_PARAMS_NAMED);
4122 $contextlist = get_related_contexts_string($context);
4124 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
4125 FROM {role_assignments} ra, {role} r
4126 WHERE r.id = ra.roleid
4127 AND ra.contextid $contextlist
4129 ORDER BY r.sortorder ASC";
4131 return $DB->get_records_sql($sql, $params);
4135 * Gets the list of roles assigned to this context and up (parents)
4137 * @param object $context
4140 function get_roles_used_in_context($context) {
4143 $contextlist = get_related_contexts_string($context);
4145 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
4146 FROM {role_assignments} ra, {role} r
4147 WHERE r.id = ra.roleid
4148 AND ra.contextid $contextlist
4149 ORDER BY r.sortorder ASC";
4151 return $DB->get_records_sql($sql);
4155 * This function is used to print roles column in user profile page.
4156 * It is using the CFG->profileroles to limit the list to only interesting roles.
4157 * (The permission tab has full details of user role assignments.)
4159 * @param int $userid
4160 * @param int $courseid
4163 function get_user_roles_in_course($userid, $courseid) {
4164 global $CFG, $DB,$USER;
4166 if (empty($CFG->profileroles)) {
4170 if ($courseid == SITEID) {
4171 $context = get_context_instance(CONTEXT_SYSTEM);
4173 $context = get_context_instance(CONTEXT_COURSE, $courseid);
4176 if (empty($CFG->profileroles)) {
4180 $allowed = explode(',', $CFG->profileroles);
4181 list($rallowed, $params) = $DB->get_in_or_equal($allowed, SQL_PARAMS_NAMED);
4183 $contextlist = get_related_contexts_string($context);
4185 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
4186 FROM {role_assignments} ra, {role} r
4187 WHERE r.id = ra.roleid
4188 AND ra.contextid $contextlist
4190 AND ra.userid = :userid
4191 ORDER BY r.sortorder ASC";
4192 $params['userid'] = $userid;
4196 if ($roles = $DB->get_records_sql($sql, $params)) {
4197 foreach ($roles as $userrole) {
4198 $rolenames[$userrole->id] = $userrole->name;
4201 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
4203 foreach ($rolenames as $roleid => $rolename) {
4204 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&roleid='.$roleid.'">'.$rolename.'</a>';
4206 $rolestring = implode(',', $rolenames);
4213 * Checks if a user can assign users to a particular role in this context
4216 * @param object $context
4217 * @param int $targetroleid - the id of the role you want to assign users to
4220 function user_can_assign($context, $targetroleid) {
4223 // first check if user has override capability
4224 // if not return false;
4225 if (!has_capability('moodle/role:assign', $context)) {
4228 // pull out all active roles of this user from this context(or above)
4229 if ($userroles = get_user_roles($context)) {
4230 foreach ($userroles as $userrole) {
4231 // if any in the role_allow_override table, then it's ok
4232 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
4242 * Returns all site roles in correct sort order.
4246 function get_all_roles() {
4248 return $DB->get_records('role', NULL, 'sortorder ASC');
4252 * Returns roles of a specified archetype
4253 * @param string $archetype
4254 * @return array of full role records
4256 function get_archetype_roles($archetype) {
4258 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
4262 * Gets all the user roles assigned in this context, or higher contexts
4263 * this is mainly used when checking if a user can assign a role, or overriding a role
4264 * i.e. we need to know what this user holds, in order to verify against allow_assign and
4265 * allow_override tables
4267 * @param object $context
4268 * @param int $userid
4269 * @param bool $checkparentcontexts defaults to true
4270 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
4273 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC') {
4276 if (empty($userid)) {
4277 if (empty($USER->id)) {
4280 $userid = $USER->id;
4283 if ($checkparentcontexts) {
4284 $contextids = get_parent_contexts($context);
4286 $contextids = array();
4288 $contextids[] = $context->id;
4290 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
4292 array_unshift($params, $userid);
4294 $sql = "SELECT ra.*, r.name, r.shortname
4295 FROM {role_assignments} ra, {role} r, {context} c
4297 AND ra.roleid = r.id
4298 AND ra.contextid = c.id
4299 AND ra.contextid $contextids
4302 return $DB->get_records_sql($sql ,$params);
4306 * Creates a record in the role_allow_override table
4309 * @param int $sroleid source roleid
4310 * @param int $troleid target roleid
4311 * @return int id or false