MDL-27588 Fixed up several bugs with the formal_white theme
[moodle.git] / lib / accesslib.php
blobe4f31b9bf037ba10bc8e2f666d209ddcad6a9a27
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
19 * This file contains functions for managing user access
21 * <b>Public API vs internals</b>
23 * General users probably only care about
25 * Context handling
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...
32 * - has_capability()
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()
44 * Enrol/unenrol
45 * - enrol_into_course()
46 * - role_assign()/role_unassign()
49 * Advanced use
50 * - load_all_capabilities()
51 * - reload_all_capabilities()
52 * - has_capability_in_accessdata()
53 * - is_siteadmin()
54 * - get_user_access_sitewide()
55 * - load_subcontext()
56 * - get_role_access_bycontext()
58 * <b>Name conventions</b>
60 * "ctx" means context
62 * <b>accessdata</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
73 * data for.
75 * Things are keyed on "contextpaths" (the path field of
76 * the context table) for fast walking up/down the tree.
77 * <code>
78 * $accessdata[ra][$contextpath]= array($roleid)
79 * [$contextpath]= array($roleid)
80 * [$contextpath]= array($roleid)
81 * </code>
83 * Role definitions are stored like this
84 * (no cap merge is done - so it's compact)
86 * <code>
87 * $accessdata[rdef][$contextpath:$roleid][mod/forum:viewpost] = 1
88 * [mod/forum:editallpost] = -1
89 * [mod/forum:startdiscussion] = -1000
90 * </code>
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
99 * <code>
100 * $accessdata[loaded] = array($contextpath, $contextpath)
101 * </code>
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.
121 * @package core
122 * @subpackage role
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);
178 * Internal class provides a cache of context information. The cache is
179 * restricted in size.
181 * This cache should NOT be used outside accesslib.php!
183 * @private
184 * @author Sam Marshall
186 class context_cache {
187 private $contextsbyid;
188 private $contexts;
189 private $count;
192 * @var int Maximum number of contexts that will be cached.
194 const MAX_SIZE = 2500;
196 * @var int Once contexts reach maximum number, this many will be removed from cache.
198 const REDUCE_SIZE = 1000;
201 * Initialises (empty)
203 public function __construct() {
204 $this->reset();
208 * Resets the cache to remove all data.
210 public function reset() {
211 $this->contexts = array();
212 $this->contextsbyid = array();
213 $this->count = 0;
217 * Adds a context to the cache. If the cache is full, discards a batch of
218 * older entries.
219 * @param stdClass $context New context to add
221 public function add(stdClass $context) {
222 if ($this->count >= self::MAX_SIZE) {
223 for ($i=0; $i<self::REDUCE_SIZE; $i++) {
224 if ($first = reset($this->contextsbyid)) {
225 unset($this->contextsbyid[$first->id]);
226 unset($this->contexts[$first->contextlevel][$first->instanceid]);
229 $this->count -= self::REDUCE_SIZE;
230 if ($this->count < 0) {
231 // most probably caused by the drift, the reset() above
232 // might have returned false because there might not be any more elements
233 $this->count = 0;
237 $this->contexts[$context->contextlevel][$context->instanceid] = $context;
238 $this->contextsbyid[$context->id] = $context;
240 // Note the count may get out of synch slightly if you cache a context
241 // that is already cached, but it doesn't really matter much and I
242 // didn't think it was worth the performance hit.
243 $this->count++;
247 * Removes a context from the cache.
248 * @param stdClass $context Context object to remove (must include fields
249 * ->id, ->contextlevel, ->instanceid at least)
251 public function remove(stdClass $context) {
252 unset($this->contexts[$context->contextlevel][$context->instanceid]);
253 unset($this->contextsbyid[$context->id]);
255 // Again the count may get a bit out of synch if you remove things
256 // that don't exist
257 $this->count--;
259 if ($this->count < 0) {
260 $this->count = 0;
265 * Gets a context from the cache.
266 * @param int $contextlevel Context level
267 * @param int $instance Instance ID
268 * @return stdClass|bool Context or false if not in cache
270 public function get($contextlevel, $instance) {
271 if (isset($this->contexts[$contextlevel][$instance])) {
272 return $this->contexts[$contextlevel][$instance];
274 return false;
278 * Gets a context from the cache based on its id.
279 * @param int $id Context ID
280 * @return stdClass|bool Context or false if not in cache
282 public function get_by_id($id) {
283 if (isset($this->contextsbyid[$id])) {
284 return $this->contextsbyid[$id];
286 return false;
290 * @return int Count of contexts in cache (approximately)
292 public function get_approx_count() {
293 return $this->count;
298 * Although this looks like a global variable, it isn't really.
300 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
301 * It is used to cache various bits of data between function calls for performance reasons.
302 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
303 * as methods of a class, instead of functions.
305 * @global stdClass $ACCESSLIB_PRIVATE
306 * @name $ACCESSLIB_PRIVATE
308 global $ACCESSLIB_PRIVATE;
309 $ACCESSLIB_PRIVATE = new stdClass();
310 $ACCESSLIB_PRIVATE->contexcache = new context_cache();
311 $ACCESSLIB_PRIVATE->systemcontext = null; // Used in get_system_context
312 $ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache
313 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the $accessdata structure for users other than $USER
314 $ACCESSLIB_PRIVATE->roledefinitions = array(); // role definitions cache - helps a lot with mem usage in cron
315 $ACCESSLIB_PRIVATE->croncache = array(); // Used in get_role_access
316 $ACCESSLIB_PRIVATE->preloadedcourses = array(); // Used in preload_course_contexts.
317 $ACCESSLIB_PRIVATE->capabilities = null; // detailed information about the capabilities
320 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
322 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
323 * accesslib's private caches. You need to do this before setting up test data,
324 * and also at the end of the tests.
326 function accesslib_clear_all_caches_for_unit_testing() {
327 global $UNITTEST, $USER, $ACCESSLIB_PRIVATE;
328 if (empty($UNITTEST->running)) {
329 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
331 $ACCESSLIB_PRIVATE->contexcache = new context_cache();
332 $ACCESSLIB_PRIVATE->systemcontext = null;
333 $ACCESSLIB_PRIVATE->dirtycontexts = null;
334 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
335 $ACCESSLIB_PRIVATE->roledefinitions = array();
336 $ACCESSLIB_PRIVATE->croncache = array();
337 $ACCESSLIB_PRIVATE->preloadedcourses = array();
338 $ACCESSLIB_PRIVATE->capabilities = null;
340 unset($USER->access);
344 * This is really slow!!! do not use above course context level
346 * @param int $roleid
347 * @param object $context
348 * @return array
350 function get_role_context_caps($roleid, $context) {
351 global $DB;
353 //this is really slow!!!! - do not use above course context level!
354 $result = array();
355 $result[$context->id] = array();
357 // first emulate the parent context capabilities merging into context
358 $searchcontexts = array_reverse(get_parent_contexts($context));
359 array_push($searchcontexts, $context->id);
360 foreach ($searchcontexts as $cid) {
361 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
362 foreach ($capabilities as $cap) {
363 if (!array_key_exists($cap->capability, $result[$context->id])) {
364 $result[$context->id][$cap->capability] = 0;
366 $result[$context->id][$cap->capability] += $cap->permission;
371 // now go through the contexts bellow given context
372 $searchcontexts = array_keys(get_child_contexts($context));
373 foreach ($searchcontexts as $cid) {
374 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
375 foreach ($capabilities as $cap) {
376 if (!array_key_exists($cap->contextid, $result)) {
377 $result[$cap->contextid] = array();
379 $result[$cap->contextid][$cap->capability] = $cap->permission;
384 return $result;
388 * Gets the accessdata for role "sitewide" (system down to course)
390 * @param int $roleid
391 * @param array $accessdata defaults to null
392 * @return array
394 function get_role_access($roleid, $accessdata = null) {
395 global $CFG, $DB;
397 /* Get it in 1 cheap DB query...
398 * - relevant role caps at the root and down
399 * to the course level - but not below
401 if (is_null($accessdata)) {
402 $accessdata = array(); // named list
403 $accessdata['ra'] = array();
404 $accessdata['rdef'] = array();
405 $accessdata['loaded'] = array();
409 // Overrides for the role IN ANY CONTEXTS
410 // down to COURSE - not below -
412 $sql = "SELECT ctx.path,
413 rc.capability, rc.permission
414 FROM {context} ctx
415 JOIN {role_capabilities} rc
416 ON rc.contextid=ctx.id
417 WHERE rc.roleid = ?
418 AND ctx.contextlevel <= ".CONTEXT_COURSE."
419 ORDER BY ctx.depth, ctx.path";
420 $params = array($roleid);
422 // we need extra caching in CLI scripts and cron
423 if (CLI_SCRIPT) {
424 global $ACCESSLIB_PRIVATE;
426 if (!isset($ACCESSLIB_PRIVATE->croncache[$roleid])) {
427 $ACCESSLIB_PRIVATE->croncache[$roleid] = array();
428 $rs = $DB->get_recordset_sql($sql, $params);
429 foreach ($rs as $rd) {
430 $ACCESSLIB_PRIVATE->croncache[$roleid][] = $rd;
432 $rs->close();
435 foreach ($ACCESSLIB_PRIVATE->croncache[$roleid] as $rd) {
436 $k = "{$rd->path}:{$roleid}";
437 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
440 } else {
441 $rs = $DB->get_recordset_sql($sql, $params);
442 if ($rs->valid()) {
443 foreach ($rs as $rd) {
444 $k = "{$rd->path}:{$roleid}";
445 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
447 unset($rd);
449 $rs->close();
452 return $accessdata;
456 * Gets the accessdata for role "sitewide" (system down to course)
458 * @param int $roleid
459 * @param array $accessdata defaults to null
460 * @return array
462 function get_default_frontpage_role_access($roleid, $accessdata = null) {
464 global $CFG, $DB;
466 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
467 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
470 // Overrides for the role in any contexts related to the course
472 $sql = "SELECT ctx.path,
473 rc.capability, rc.permission
474 FROM {context} ctx
475 JOIN {role_capabilities} rc
476 ON rc.contextid=ctx.id
477 WHERE rc.roleid = ?
478 AND (ctx.id = ".SYSCONTEXTID." OR ctx.path LIKE ?)
479 AND ctx.contextlevel <= ".CONTEXT_COURSE."
480 ORDER BY ctx.depth, ctx.path";
481 $params = array($roleid, "$base/%");
483 $rs = $DB->get_recordset_sql($sql, $params);
484 if ($rs->valid()) {
485 foreach ($rs as $rd) {
486 $k = "{$rd->path}:{$roleid}";
487 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
489 unset($rd);
491 $rs->close();
493 return $accessdata;
498 * Get the default guest role
500 * @return stdClass role
502 function get_guest_role() {
503 global $CFG, $DB;
505 if (empty($CFG->guestroleid)) {
506 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
507 $guestrole = array_shift($roles); // Pick the first one
508 set_config('guestroleid', $guestrole->id);
509 return $guestrole;
510 } else {
511 debugging('Can not find any guest role!');
512 return false;
514 } else {
515 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
516 return $guestrole;
517 } else {
518 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
519 set_config('guestroleid', '');
520 return get_guest_role();
526 * Check whether a user has a particular capability in a given context.
528 * For example::
529 * $context = get_context_instance(CONTEXT_MODULE, $cm->id);
530 * has_capability('mod/forum:replypost',$context)
532 * By default checks the capabilities of the current user, but you can pass a
533 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
535 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
536 * or capabilities with XSS, config or data loss risks.
538 * @param string $capability the name of the capability to check. For example mod/forum:view
539 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
540 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
541 * @param boolean $doanything If false, ignores effect of admin role assignment
542 * @return boolean true if the user has this capability. Otherwise false.
544 function has_capability($capability, $context, $user = null, $doanything = true) {
545 global $USER, $CFG, $DB, $SCRIPT, $ACCESSLIB_PRIVATE;
547 if (during_initial_install()) {
548 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cliupgrade.php") {
549 // we are in an installer - roles can not work yet
550 return true;
551 } else {
552 return false;
556 if (strpos($capability, 'moodle/legacy:') === 0) {
557 throw new coding_exception('Legacy capabilities can not be used any more!');
560 // the original $CONTEXT here was hiding serious errors
561 // for security reasons do not reuse previous context
562 if (empty($context)) {
563 debugging('Incorrect context specified');
564 return false;
566 if (!is_bool($doanything)) {
567 throw new coding_exception('Capability parameter "doanything" is wierd ("'.$doanything.'"). This has to be fixed in code.');
570 // make sure there is a real user specified
571 if ($user === null) {
572 $userid = !empty($USER->id) ? $USER->id : 0;
573 } else {
574 $userid = !empty($user->id) ? $user->id : $user;
577 // capability must exist
578 if (!$capinfo = get_capability_info($capability)) {
579 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
580 return false;
582 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
583 if (($capinfo->captype === 'write') or ((int)$capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
584 if (isguestuser($userid) or $userid == 0) {
585 return false;
589 if (is_null($context->path) or $context->depth == 0) {
590 //this should not happen
591 $contexts = array(SYSCONTEXTID, $context->id);
592 $context->path = '/'.SYSCONTEXTID.'/'.$context->id;
593 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()', DEBUG_DEVELOPER);
595 } else {
596 $contexts = explode('/', $context->path);
597 array_shift($contexts);
600 if (CLI_SCRIPT && !isset($USER->access)) {
601 // In cron, some modules setup a 'fake' $USER,
602 // ensure we load the appropriate accessdata.
603 if (isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
604 $ACCESSLIB_PRIVATE->dirtycontexts = null; //load fresh dirty contexts
605 } else {
606 load_user_accessdata($userid);
607 $ACCESSLIB_PRIVATE->dirtycontexts = array();
609 $USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
611 } else if (isset($USER->id) && ($USER->id == $userid) && !isset($USER->access)) {
612 // caps not loaded yet - better to load them to keep BC with 1.8
613 // not-logged-in user or $USER object set up manually first time here
614 load_all_capabilities();
615 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // reset the cache for other users too, the dirty contexts are empty now
616 $ACCESSLIB_PRIVATE->roledefinitions = array();
619 // Load dirty contexts list if needed
620 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
621 if (isset($USER->access['time'])) {
622 $ACCESSLIB_PRIVATE->dirtycontexts = get_dirty_contexts($USER->access['time']);
624 else {
625 $ACCESSLIB_PRIVATE->dirtycontexts = array();
629 // Careful check for staleness...
630 if (count($ACCESSLIB_PRIVATE->dirtycontexts) !== 0 and is_contextpath_dirty($contexts, $ACCESSLIB_PRIVATE->dirtycontexts)) {
631 // reload all capabilities - preserving loginas, roleswitches, etc
632 // and then cleanup any marks of dirtyness... at least from our short
633 // term memory! :-)
634 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
635 $ACCESSLIB_PRIVATE->roledefinitions = array();
637 if (CLI_SCRIPT) {
638 load_user_accessdata($userid);
639 $USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
640 $ACCESSLIB_PRIVATE->dirtycontexts = array();
642 } else {
643 reload_all_capabilities();
647 // Find out if user is admin - it is not possible to override the doanything in any way
648 // and it is not possible to switch to admin role either.
649 if ($doanything) {
650 if (is_siteadmin($userid)) {
651 if ($userid != $USER->id) {
652 return true;
654 // make sure switchrole is not used in this context
655 if (empty($USER->access['rsw'])) {
656 return true;
658 $parts = explode('/', trim($context->path, '/'));
659 $path = '';
660 $switched = false;
661 foreach ($parts as $part) {
662 $path .= '/' . $part;
663 if (!empty($USER->access['rsw'][$path])) {
664 $switched = true;
665 break;
668 if (!$switched) {
669 return true;
671 //ok, admin switched role in this context, let's use normal access control rules
675 // divulge how many times we are called
676 //// error_log("has_capability: id:{$context->id} path:{$context->path} userid:$userid cap:$capability");
678 if (isset($USER->id) && ($USER->id == $userid)) { // we must accept strings and integers in $userid
680 // For the logged in user, we have $USER->access
681 // which will have all RAs and caps preloaded for
682 // course and above contexts.
684 // Contexts below courses && contexts that do not
685 // hang from courses are loaded into $USER->access
686 // on demand, and listed in $USER->access[loaded]
688 if ($context->contextlevel <= CONTEXT_COURSE) {
689 // Course and above are always preloaded
690 return has_capability_in_accessdata($capability, $context, $USER->access);
692 // Load accessdata for below-the-course contexts
693 if (!path_inaccessdata($context->path,$USER->access)) {
694 // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
695 // $bt = debug_backtrace();
696 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
697 load_subcontext($USER->id, $context, $USER->access);
699 return has_capability_in_accessdata($capability, $context, $USER->access);
702 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
703 load_user_accessdata($userid);
706 if ($context->contextlevel <= CONTEXT_COURSE) {
707 // Course and above are always preloaded
708 return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
710 // Load accessdata for below-the-course contexts as needed
711 if (!path_inaccessdata($context->path, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
712 // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
713 // $bt = debug_backtrace();
714 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
715 load_subcontext($userid, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
717 return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
721 * Check if the user has any one of several capabilities from a list.
723 * This is just a utility method that calls has_capability in a loop. Try to put
724 * the capabilities that most users are likely to have first in the list for best
725 * performance.
727 * There are probably tricks that could be done to improve the performance here, for example,
728 * check the capabilities that are already cached first.
730 * @see has_capability()
731 * @param array $capabilities an array of capability names.
732 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
733 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
734 * @param boolean $doanything If false, ignore effect of admin role assignment
735 * @return boolean true if the user has any of these capabilities. Otherwise false.
737 function has_any_capability($capabilities, $context, $userid = null, $doanything = true) {
738 if (!is_array($capabilities)) {
739 debugging('Incorrect $capabilities parameter in has_any_capabilities() call - must be an array');
740 return false;
742 foreach ($capabilities as $capability) {
743 if (has_capability($capability, $context, $userid, $doanything)) {
744 return true;
747 return false;
751 * Check if the user has all the capabilities in a list.
753 * This is just a utility method that calls has_capability in a loop. Try to put
754 * the capabilities that fewest users are likely to have first in the list for best
755 * performance.
757 * There are probably tricks that could be done to improve the performance here, for example,
758 * check the capabilities that are already cached first.
760 * @see has_capability()
761 * @param array $capabilities an array of capability names.
762 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
763 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
764 * @param boolean $doanything If false, ignore effect of admin role assignment
765 * @return boolean true if the user has all of these capabilities. Otherwise false.
767 function has_all_capabilities($capabilities, $context, $userid = null, $doanything = true) {
768 if (!is_array($capabilities)) {
769 debugging('Incorrect $capabilities parameter in has_all_capabilities() call - must be an array');
770 return false;
772 foreach ($capabilities as $capability) {
773 if (!has_capability($capability, $context, $userid, $doanything)) {
774 return false;
777 return true;
781 * Check if the user is an admin at the site level.
783 * Please note that use of proper capabilities is always encouraged,
784 * this function is supposed to be used from core or for temporary hacks.
786 * @param int|object $user_or_id user id or user object
787 * @returns bool true if user is one of the administrators, false otherwise
789 function is_siteadmin($user_or_id = null) {
790 global $CFG, $USER;
792 if ($user_or_id === null) {
793 $user_or_id = $USER;
796 if (empty($user_or_id)) {
797 return false;
799 if (!empty($user_or_id->id)) {
800 // we support
801 $userid = $user_or_id->id;
802 } else {
803 $userid = $user_or_id;
806 $siteadmins = explode(',', $CFG->siteadmins);
807 return in_array($userid, $siteadmins);
811 * Returns true if user has at least one role assign
812 * of 'coursecontact' role (is potentially listed in some course descriptions).
814 * @param $userid
815 * @return stdClass
817 function has_coursecontact_role($userid) {
818 global $DB, $CFG;
820 if (empty($CFG->coursecontact)) {
821 return false;
823 $sql = "SELECT 1
824 FROM {role_assignments}
825 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
826 return $DB->record_exists_sql($sql, array('userid'=>$userid));
830 * @param string $path
831 * @return string
833 function get_course_from_path($path) {
834 // assume that nothing is more than 1 course deep
835 if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
836 return $matches[1];
838 return false;
842 * @param string $path
843 * @param array $accessdata
844 * @return bool
846 function path_inaccessdata($path, $accessdata) {
847 if (empty($accessdata['loaded'])) {
848 return false;
851 // assume that contexts hang from sys or from a course
852 // this will only work well with stuff that hangs from a course
853 if (in_array($path, $accessdata['loaded'], true)) {
854 // error_log("found it!");
855 return true;
857 $base = '/' . SYSCONTEXTID;
858 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
859 $path = $matches[1];
860 if ($path === $base) {
861 return false;
863 if (in_array($path, $accessdata['loaded'], true)) {
864 return true;
867 return false;
871 * Does the user have a capability to do something?
873 * Walk the accessdata array and return true/false.
874 * Deals with prohibits, roleswitching, aggregating
875 * capabilities, etc.
877 * The main feature of here is being FAST and with no
878 * side effects.
880 * Notes:
882 * Switch Roles exits early
883 * ------------------------
884 * cap checks within a switchrole need to exit early
885 * in our bottom up processing so they don't "see" that
886 * there are real RAs that can do all sorts of things.
888 * Switch Role merges with default role
889 * ------------------------------------
890 * If you are a teacher in course X, you have at least
891 * teacher-in-X + defaultloggedinuser-sitewide. So in the
892 * course you'll have techer+defaultloggedinuser.
893 * We try to mimic that in switchrole.
895 * Permission evaluation
896 * ---------------------
897 * Originally there was an extremely complicated way
898 * to determine the user access that dealt with
899 * "locality" or role assignments and role overrides.
900 * Now we simply evaluate access for each role separately
901 * and then verify if user has at least one role with allow
902 * and at the same time no role with prohibit.
904 * @param string $capability
905 * @param object $context
906 * @param array $accessdata
907 * @return bool
909 function has_capability_in_accessdata($capability, $context, array $accessdata) {
910 global $CFG;
912 if (empty($context->id)) {
913 throw new coding_exception('Invalid context specified');
916 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
917 $contextids = explode('/', trim($context->path, '/'));
918 $paths = array($context->path);
919 while ($contextids) {
920 array_pop($contextids);
921 $paths[] = '/' . implode('/', $contextids);
923 unset($contextids);
925 $roles = array();
926 $switchedrole = false;
928 // Find out if role switched
929 if (!empty($accessdata['rsw'])) {
930 // From the bottom up...
931 foreach ($paths as $path) {
932 if (isset($accessdata['rsw'][$path])) {
933 // Found a switchrole assignment - check for that role _plus_ the default user role
934 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
935 $switchedrole = true;
936 break;
941 if (!$switchedrole) {
942 // get all users roles in this context and above
943 foreach ($paths as $path) {
944 if (isset($accessdata['ra'][$path])) {
945 foreach ($accessdata['ra'][$path] as $roleid) {
946 $roles[$roleid] = null;
952 // Now find out what access is given to each role, going bottom-->up direction
953 foreach ($roles as $roleid => $ignored) {
954 foreach ($paths as $path) {
955 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
956 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
957 if ($perm === CAP_PROHIBIT or is_null($roles[$roleid])) {
958 $roles[$roleid] = $perm;
963 // any CAP_PROHIBIT found means no permission for the user
964 if (array_search(CAP_PROHIBIT, $roles) !== false) {
965 return false;
968 // at least one CAP_ALLOW means the user has a permission
969 return (array_search(CAP_ALLOW, $roles) !== false);
973 * @param object $context
974 * @param array $accessdata
975 * @return array
977 function aggregate_roles_from_accessdata($context, $accessdata) {
979 $path = $context->path;
981 // build $contexts as a list of "paths" of the current
982 // contexts and parents with the order top-to-bottom
983 $contexts = array($path);
984 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
985 $path = $matches[1];
986 array_unshift($contexts, $path);
989 $cc = count($contexts);
991 $roles = array();
992 // From the bottom up...
993 for ($n=$cc-1; $n>=0; $n--) {
994 $ctxp = $contexts[$n];
995 if (isset($accessdata['ra'][$ctxp]) && count($accessdata['ra'][$ctxp])) {
996 // Found assignments on this leaf
997 $addroles = $accessdata['ra'][$ctxp];
998 $roles = array_merge($roles, $addroles);
1002 return array_unique($roles);
1006 * A convenience function that tests has_capability, and displays an error if
1007 * the user does not have that capability.
1009 * NOTE before Moodle 2.0, this function attempted to make an appropriate
1010 * require_login call before checking the capability. This is no longer the case.
1011 * You must call require_login (or one of its variants) if you want to check the
1012 * user is logged in, before you call this function.
1014 * @see has_capability()
1016 * @param string $capability the name of the capability to check. For example mod/forum:view
1017 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
1018 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
1019 * @param bool $doanything If false, ignore effect of admin role assignment
1020 * @param string $errorstring The error string to to user. Defaults to 'nopermissions'.
1021 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
1022 * @return void terminates with an error if the user does not have the given capability.
1024 function require_capability($capability, $context, $userid = null, $doanything = true,
1025 $errormessage = 'nopermissions', $stringfile = '') {
1026 if (!has_capability($capability, $context, $userid, $doanything)) {
1027 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
1032 * Get an array of courses where cap requested is available
1033 * and user is enrolled, this can be relatively slow.
1035 * @param string $capability - name of the capability
1036 * @param array $accessdata_ignored
1037 * @param bool $doanything_ignored
1038 * @param string $sort - sorting fields - prefix each fieldname with "c."
1039 * @param array $fields - additional fields you are interested in...
1040 * @param int $limit_ignored
1041 * @return array $courses - ordered array of course objects - see notes above
1043 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
1045 //TODO: this should be most probably deprecated
1047 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
1048 foreach ($courses as $id=>$course) {
1049 $context = get_context_instance(CONTEXT_COURSE, $id);
1050 if (!has_capability($cap, $context, $userid)) {
1051 unset($courses[$id]);
1055 return $courses;
1060 * Return a nested array showing role assignments
1061 * all relevant role capabilities for the user at
1062 * site/course_category/course levels
1064 * We do _not_ delve deeper than courses because the number of
1065 * overrides at the module/block levels is HUGE.
1067 * [ra] => [/path/][]=roleid
1068 * [rdef] => [/path/:roleid][capability]=permission
1069 * [loaded] => array('/path', '/path')
1071 * @param int $userid - the id of the user
1072 * @return array
1074 function get_user_access_sitewide($userid) {
1075 global $CFG, $DB;
1077 /* Get in 3 cheap DB queries...
1078 * - role assignments
1079 * - relevant role caps
1080 * - above and within this user's RAs
1081 * - below this user's RAs - limited to course level
1084 $accessdata = array(); // named list
1085 $accessdata['ra'] = array();
1086 $accessdata['rdef'] = array();
1087 $accessdata['loaded'] = array();
1090 // Role assignments
1092 $sql = "SELECT ctx.path, ra.roleid
1093 FROM {role_assignments} ra
1094 JOIN {context} ctx ON ctx.id=ra.contextid
1095 WHERE ra.userid = ? AND ctx.contextlevel <= ".CONTEXT_COURSE;
1096 $params = array($userid);
1097 $rs = $DB->get_recordset_sql($sql, $params);
1100 // raparents collects paths & roles we need to walk up
1101 // the parenthood to build the rdef
1103 $raparents = array();
1104 if ($rs) {
1105 foreach ($rs as $ra) {
1106 // RAs leafs are arrays to support multi
1107 // role assignments...
1108 if (!isset($accessdata['ra'][$ra->path])) {
1109 $accessdata['ra'][$ra->path] = array();
1111 $accessdata['ra'][$ra->path][$ra->roleid] = $ra->roleid;
1113 // Concatenate as string the whole path (all related context)
1114 // for this role. This is damn faster than using array_merge()
1115 // Will unique them later
1116 if (isset($raparents[$ra->roleid])) {
1117 $raparents[$ra->roleid] .= $ra->path;
1118 } else {
1119 $raparents[$ra->roleid] = $ra->path;
1122 unset($ra);
1123 $rs->close();
1126 // Walk up the tree to grab all the roledefs
1127 // of interest to our user...
1129 // NOTE: we use a series of IN clauses here - which
1130 // might explode on huge sites with very convoluted nesting of
1131 // categories... - extremely unlikely that the number of categories
1132 // and roletypes is so large that we hit the limits of IN()
1133 $clauses = '';
1134 $cparams = array();
1135 foreach ($raparents as $roleid=>$strcontexts) {
1136 $contexts = implode(',', array_unique(explode('/', trim($strcontexts, '/'))));
1137 if ($contexts ==! '') {
1138 if ($clauses) {
1139 $clauses .= ' OR ';
1141 $clauses .= "(roleid=? AND contextid IN ($contexts))";
1142 $cparams[] = $roleid;
1146 if ($clauses !== '') {
1147 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1148 FROM {role_capabilities} rc
1149 JOIN {context} ctx ON rc.contextid=ctx.id
1150 WHERE $clauses";
1152 unset($clauses);
1153 $rs = $DB->get_recordset_sql($sql, $cparams);
1155 if ($rs) {
1156 foreach ($rs as $rd) {
1157 $k = "{$rd->path}:{$rd->roleid}";
1158 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1160 unset($rd);
1161 $rs->close();
1166 // Overrides for the role assignments IN SUBCONTEXTS
1167 // (though we still do _not_ go below the course level.
1169 // NOTE that the JOIN w sctx is with 3-way triangulation to
1170 // catch overrides to the applicable role in any subcontext, based
1171 // on the path field of the parent.
1173 $sql = "SELECT sctx.path, ra.roleid,
1174 ctx.path AS parentpath,
1175 rco.capability, rco.permission
1176 FROM {role_assignments} ra
1177 JOIN {context} ctx
1178 ON ra.contextid=ctx.id
1179 JOIN {context} sctx
1180 ON (sctx.path LIKE " . $DB->sql_concat('ctx.path',"'/%'"). " )
1181 JOIN {role_capabilities} rco
1182 ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
1183 WHERE ra.userid = ?
1184 AND ctx.contextlevel <= ".CONTEXT_COURSECAT."
1185 AND sctx.contextlevel <= ".CONTEXT_COURSE."
1186 ORDER BY sctx.depth, sctx.path, ra.roleid";
1187 $params = array($userid);
1188 $rs = $DB->get_recordset_sql($sql, $params);
1189 if ($rs) {
1190 foreach ($rs as $rd) {
1191 $k = "{$rd->path}:{$rd->roleid}";
1192 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1194 unset($rd);
1195 $rs->close();
1197 return $accessdata;
1201 * Add to the access ctrl array the data needed by a user for a given context
1203 * @param integer $userid the id of the user
1204 * @param object $context needs path!
1205 * @param array $accessdata accessdata array
1206 * @return void
1208 function load_subcontext($userid, $context, &$accessdata) {
1209 global $CFG, $DB;
1211 /* Get the additional RAs and relevant rolecaps
1212 * - role assignments - with role_caps
1213 * - relevant role caps
1214 * - above this user's RAs
1215 * - below this user's RAs - limited to course level
1218 $base = "/" . SYSCONTEXTID;
1221 // Replace $context with the target context we will
1222 // load. Normally, this will be a course context, but
1223 // may be a different top-level context.
1225 // We have 3 cases
1227 // - Course
1228 // - BLOCK/PERSON/USER/COURSE(sitecourse) hanging from SYSTEM
1229 // - BLOCK/MODULE/GROUP hanging from a course
1231 // For course contexts, we _already_ have the RAs
1232 // but the cost of re-fetching is minimal so we don't care.
1234 if ($context->contextlevel !== CONTEXT_COURSE
1235 && $context->path !== "$base/{$context->id}") {
1236 // Case BLOCK/MODULE/GROUP hanging from a course
1237 // Assumption: the course _must_ be our parent
1238 // If we ever see stuff nested further this needs to
1239 // change to do 1 query over the exploded path to
1240 // find out which one is the course
1241 $courses = explode('/',get_course_from_path($context->path));
1242 $targetid = array_pop($courses);
1243 $context = get_context_instance_by_id($targetid);
1248 // Role assignments in the context and below
1250 $sql = "SELECT ctx.path, ra.roleid
1251 FROM {role_assignments} ra
1252 JOIN {context} ctx
1253 ON ra.contextid=ctx.id
1254 WHERE ra.userid = ?
1255 AND (ctx.path = ? OR ctx.path LIKE ?)
1256 ORDER BY ctx.depth, ctx.path, ra.roleid";
1257 $params = array($userid, $context->path, $context->path."/%");
1258 $rs = $DB->get_recordset_sql($sql, $params);
1261 // Read in the RAs, preventing duplicates
1263 if ($rs) {
1264 $localroles = array();
1265 $lastseen = '';
1266 foreach ($rs as $ra) {
1267 if (!isset($accessdata['ra'][$ra->path])) {
1268 $accessdata['ra'][$ra->path] = array();
1270 // only add if is not a repeat caused
1271 // by capability join...
1272 // (this check is cheaper than in_array())
1273 if ($lastseen !== $ra->path.':'.$ra->roleid) {
1274 $lastseen = $ra->path.':'.$ra->roleid;
1275 $accessdata['ra'][$ra->path][$ra->roleid] = $ra->roleid;
1276 array_push($localroles, $ra->roleid);
1279 $rs->close();
1283 // Walk up and down the tree to grab all the roledefs
1284 // of interest to our user...
1286 // NOTES
1287 // - we use IN() but the number of roles is very limited.
1289 $courseroles = aggregate_roles_from_accessdata($context, $accessdata);
1291 // Do we have any interesting "local" roles?
1292 $localroles = array_diff($localroles,$courseroles); // only "new" local roles
1293 $wherelocalroles='';
1294 if (count($localroles)) {
1295 // Role defs for local roles in 'higher' contexts...
1296 $contexts = substr($context->path, 1); // kill leading slash
1297 $contexts = str_replace('/', ',', $contexts);
1298 $localroleids = implode(',',$localroles);
1299 $wherelocalroles="OR (rc.roleid IN ({$localroleids})
1300 AND ctx.id IN ($contexts))" ;
1303 // We will want overrides for all of them
1304 $whereroles = '';
1305 if ($roleids = implode(',',array_merge($courseroles,$localroles))) {
1306 $whereroles = "rc.roleid IN ($roleids) AND";
1308 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1309 FROM {role_capabilities} rc
1310 JOIN {context} ctx
1311 ON rc.contextid=ctx.id
1312 WHERE ($whereroles
1313 (ctx.id=? OR ctx.path LIKE ?))
1314 $wherelocalroles
1315 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1316 $params = array($context->id, $context->path."/%");
1318 $newrdefs = array();
1319 $rs = $DB->get_recordset_sql($sql, $params);
1320 foreach ($rs as $rd) {
1321 $k = "{$rd->path}:{$rd->roleid}";
1322 if (!array_key_exists($k, $newrdefs)) {
1323 $newrdefs[$k] = array();
1325 $newrdefs[$k][$rd->capability] = $rd->permission;
1327 $rs->close();
1329 compact_rdefs($newrdefs);
1330 foreach ($newrdefs as $key=>$value) {
1331 $accessdata['rdef'][$key] =& $newrdefs[$key];
1334 // error_log("loaded {$context->path}");
1335 $accessdata['loaded'][] = $context->path;
1339 * Add to the access ctrl array the data needed by a role for a given context.
1341 * The data is added in the rdef key.
1343 * This role-centric function is useful for role_switching
1344 * and to get an overview of what a role gets under a
1345 * given context and below...
1347 * @param integer $roleid the id of the user
1348 * @param object $context needs path!
1349 * @param array $accessdata accessdata array null by default
1350 * @return array
1352 function get_role_access_bycontext($roleid, $context, $accessdata = null) {
1353 global $CFG, $DB;
1355 /* Get the relevant rolecaps into rdef
1356 * - relevant role caps
1357 * - at ctx and above
1358 * - below this ctx
1361 if (is_null($accessdata)) {
1362 $accessdata = array(); // named list
1363 $accessdata['ra'] = array();
1364 $accessdata['rdef'] = array();
1365 $accessdata['loaded'] = array();
1368 $contexts = substr($context->path, 1); // kill leading slash
1369 $contexts = str_replace('/', ',', $contexts);
1372 // Walk up and down the tree to grab all the roledefs
1373 // of interest to our role...
1375 // NOTE: we use an IN clauses here - which
1376 // might explode on huge sites with very convoluted nesting of
1377 // categories... - extremely unlikely that the number of nested
1378 // categories is so large that we hit the limits of IN()
1380 $sql = "SELECT ctx.path, rc.capability, rc.permission
1381 FROM {role_capabilities} rc
1382 JOIN {context} ctx
1383 ON rc.contextid=ctx.id
1384 WHERE rc.roleid=? AND
1385 ( ctx.id IN ($contexts) OR
1386 ctx.path LIKE ? )
1387 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1388 $params = array($roleid, $context->path."/%");
1390 $rs = $DB->get_recordset_sql($sql, $params);
1391 foreach ($rs as $rd) {
1392 $k = "{$rd->path}:{$roleid}";
1393 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1395 $rs->close();
1397 return $accessdata;
1401 * Load accessdata for a user into the $ACCESSLIB_PRIVATE->accessdatabyuser global
1403 * Used by has_capability() - but feel free
1404 * to call it if you are about to run a BIG
1405 * cron run across a bazillion users.
1407 * @param int $userid
1408 * @return array returns ACCESSLIB_PRIVATE->accessdatabyuser[userid]
1410 function load_user_accessdata($userid) {
1411 global $CFG, $ACCESSLIB_PRIVATE;
1413 $base = '/'.SYSCONTEXTID;
1415 $accessdata = get_user_access_sitewide($userid);
1416 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1418 // provide "default role" & set 'dr'
1420 if (!empty($CFG->defaultuserroleid)) {
1421 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1422 if (!isset($accessdata['ra'][$base])) {
1423 $accessdata['ra'][$base] = array();
1425 $accessdata['ra'][$base][$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
1426 $accessdata['dr'] = $CFG->defaultuserroleid;
1430 // provide "default frontpage role"
1432 if (!empty($CFG->defaultfrontpageroleid)) {
1433 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1434 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1435 if (!isset($accessdata['ra'][$base])) {
1436 $accessdata['ra'][$base] = array();
1438 $accessdata['ra'][$base][$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
1440 // for dirty timestamps in cron
1441 $accessdata['time'] = time();
1443 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1444 compact_rdefs($ACCESSLIB_PRIVATE->accessdatabyuser[$userid]['rdef']);
1446 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1450 * Use shared copy of role definitions stored in ACCESSLIB_PRIVATE->roledefinitions;
1452 * @param array $rdefs array of role definitions in contexts
1454 function compact_rdefs(&$rdefs) {
1455 global $ACCESSLIB_PRIVATE;
1458 * This is a basic sharing only, we could also
1459 * use md5 sums of values. The main purpose is to
1460 * reduce mem in cron jobs - many users in $ACCESSLIB_PRIVATE->accessdatabyuser array.
1463 foreach ($rdefs as $key => $value) {
1464 if (!array_key_exists($key, $ACCESSLIB_PRIVATE->roledefinitions)) {
1465 $ACCESSLIB_PRIVATE->roledefinitions[$key] = $rdefs[$key];
1467 $rdefs[$key] =& $ACCESSLIB_PRIVATE->roledefinitions[$key];
1472 * A convenience function to completely load all the capabilities
1473 * for the current user. This is what gets called from complete_user_login()
1474 * for example. Call it only _after_ you've setup $USER and called
1475 * check_enrolment_plugins();
1476 * @see check_enrolment_plugins()
1478 * @return void
1480 function load_all_capabilities() {
1481 global $CFG, $ACCESSLIB_PRIVATE;
1483 //NOTE: we can not use $USER here because it may no be linked to $_SESSION['USER'] yet!
1485 // roles not installed yet - we are in the middle of installation
1486 if (during_initial_install()) {
1487 return;
1490 $base = '/'.SYSCONTEXTID;
1492 if (isguestuser($_SESSION['USER'])) {
1493 $guest = get_guest_role();
1495 // Load the rdefs
1496 $_SESSION['USER']->access = get_role_access($guest->id);
1497 // Put the ghost enrolment in place...
1498 $_SESSION['USER']->access['ra'][$base] = array($guest->id => $guest->id);
1501 } else if (!empty($_SESSION['USER']->id)) { // can not use isloggedin() yet
1503 $accessdata = get_user_access_sitewide($_SESSION['USER']->id);
1506 // provide "default role" & set 'dr'
1508 if (!empty($CFG->defaultuserroleid)) {
1509 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1510 if (!isset($accessdata['ra'][$base])) {
1511 $accessdata['ra'][$base] = array();
1513 $accessdata['ra'][$base][$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
1514 $accessdata['dr'] = $CFG->defaultuserroleid;
1517 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1520 // provide "default frontpage role"
1522 if (!empty($CFG->defaultfrontpageroleid)) {
1523 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1524 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1525 if (!isset($accessdata['ra'][$base])) {
1526 $accessdata['ra'][$base] = array();
1528 $accessdata['ra'][$base][$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
1530 $_SESSION['USER']->access = $accessdata;
1532 } else if (!empty($CFG->notloggedinroleid)) {
1533 $_SESSION['USER']->access = get_role_access($CFG->notloggedinroleid);
1534 $_SESSION['USER']->access['ra'][$base] = array($CFG->notloggedinroleid => $CFG->notloggedinroleid);
1537 // Timestamp to read dirty context timestamps later
1538 $_SESSION['USER']->access['time'] = time();
1539 $ACCESSLIB_PRIVATE->dirtycontexts = array();
1541 // Clear to force a refresh
1542 unset($_SESSION['USER']->mycourses);
1546 * A convenience function to completely reload all the capabilities
1547 * for the current user when roles have been updated in a relevant
1548 * context -- but PRESERVING switchroles and loginas.
1550 * That is - completely transparent to the user.
1552 * Note: rewrites $USER->access completely.
1554 * @return void
1556 function reload_all_capabilities() {
1557 global $USER, $DB;
1559 // error_log("reloading");
1560 // copy switchroles
1561 $sw = array();
1562 if (isset($USER->access['rsw'])) {
1563 $sw = $USER->access['rsw'];
1564 // error_log(print_r($sw,1));
1567 unset($USER->access);
1568 unset($USER->mycourses);
1570 load_all_capabilities();
1572 foreach ($sw as $path => $roleid) {
1573 $context = $DB->get_record('context', array('path'=>$path));
1574 role_switch($roleid, $context);
1580 * Adds a temp role to an accessdata array.
1582 * Useful for the "temporary guest" access
1583 * we grant to logged-in users.
1585 * Note - assumes a course context!
1587 * @param object $content
1588 * @param int $roleid
1589 * @param array $accessdata
1590 * @return array Returns access data
1592 function load_temp_role($context, $roleid, array $accessdata) {
1593 global $CFG, $DB;
1596 // Load rdefs for the role in -
1597 // - this context
1598 // - all the parents
1599 // - and below - IOWs overrides...
1602 // turn the path into a list of context ids
1603 $contexts = substr($context->path, 1); // kill leading slash
1604 $contexts = str_replace('/', ',', $contexts);
1606 $sql = "SELECT ctx.path, rc.capability, rc.permission
1607 FROM {context} ctx
1608 JOIN {role_capabilities} rc
1609 ON rc.contextid=ctx.id
1610 WHERE (ctx.id IN ($contexts)
1611 OR ctx.path LIKE ?)
1612 AND rc.roleid = ?
1613 ORDER BY ctx.depth, ctx.path";
1614 $params = array($context->path."/%", $roleid);
1615 $rs = $DB->get_recordset_sql($sql, $params);
1616 foreach ($rs as $rd) {
1617 $k = "{$rd->path}:{$roleid}";
1618 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1620 $rs->close();
1623 // Say we loaded everything for the course context
1624 // - which we just did - if the user gets a proper
1625 // RA in this session, this data will need to be reloaded,
1626 // but that is handled by the complete accessdata reload
1628 array_push($accessdata['loaded'], $context->path);
1631 // Add the ghost RA
1633 if (!isset($accessdata['ra'][$context->path])) {
1634 $accessdata['ra'][$context->path] = array();
1636 $accessdata['ra'][$context->path][$roleid] = $roleid;
1638 return $accessdata;
1642 * Removes any extra guest roles from accessdata
1643 * @param object $context
1644 * @param array $accessdata
1645 * @return array access data
1647 function remove_temp_roles($context, array $accessdata) {
1648 global $DB, $USER;
1649 $sql = "SELECT DISTINCT ra.roleid AS id
1650 FROM {role_assignments} ra
1651 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1652 $ras = $DB->get_records_sql($sql, array('contextid'=>$context->id, 'userid'=>$USER->id));
1654 if ($ras) {
1655 $accessdata['ra'][$context->path] = array_combine(array_keys($ras), array_keys($ras));
1656 } else {
1657 $accessdata['ra'][$context->path] = array();
1660 return $accessdata;
1664 * Returns array of all role archetypes.
1666 * @return array
1668 function get_role_archetypes() {
1669 return array(
1670 'manager' => 'manager',
1671 'coursecreator' => 'coursecreator',
1672 'editingteacher' => 'editingteacher',
1673 'teacher' => 'teacher',
1674 'student' => 'student',
1675 'guest' => 'guest',
1676 'user' => 'user',
1677 'frontpage' => 'frontpage'
1682 * Assign the defaults found in this capability definition to roles that have
1683 * the corresponding legacy capabilities assigned to them.
1685 * @param string $capability
1686 * @param array $legacyperms an array in the format (example):
1687 * 'guest' => CAP_PREVENT,
1688 * 'student' => CAP_ALLOW,
1689 * 'teacher' => CAP_ALLOW,
1690 * 'editingteacher' => CAP_ALLOW,
1691 * 'coursecreator' => CAP_ALLOW,
1692 * 'manager' => CAP_ALLOW
1693 * @return boolean success or failure.
1695 function assign_legacy_capabilities($capability, $legacyperms) {
1697 $archetypes = get_role_archetypes();
1699 foreach ($legacyperms as $type => $perm) {
1701 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1702 if ($type === 'admin') {
1703 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1704 $type = 'manager';
1707 if (!array_key_exists($type, $archetypes)) {
1708 print_error('invalidlegacy', '', '', $type);
1711 if ($roles = get_archetype_roles($type)) {
1712 foreach ($roles as $role) {
1713 // Assign a site level capability.
1714 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1715 return false;
1720 return true;
1724 * @param object $capability a capability - a row from the capabilities table.
1725 * @return boolean whether this capability is safe - that is, whether people with the
1726 * safeoverrides capability should be allowed to change it.
1728 function is_safe_capability($capability) {
1729 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1732 /**********************************
1733 * Context Manipulation functions *
1734 **********************************/
1737 * Context creation - internal implementation.
1739 * Create a new context record for use by all roles-related stuff
1740 * assumes that the caller has done the homework.
1742 * DO NOT CALL THIS DIRECTLY, instead use {@link get_context_instance}!
1744 * @param int $contextlevel
1745 * @param int $instanceid
1746 * @param int $strictness
1747 * @return object newly created context
1749 function create_context($contextlevel, $instanceid, $strictness = IGNORE_MISSING) {
1750 global $CFG, $DB;
1752 if ($contextlevel == CONTEXT_SYSTEM) {
1753 return get_system_context();
1756 $context = new stdClass();
1757 $context->contextlevel = $contextlevel;
1758 $context->instanceid = $instanceid;
1760 // Define $context->path based on the parent
1761 // context. In other words... Who is your daddy?
1762 $basepath = '/' . SYSCONTEXTID;
1763 $basedepth = 1;
1765 $result = true;
1766 $error_message = null;
1768 switch ($contextlevel) {
1769 case CONTEXT_COURSECAT:
1770 $sql = "SELECT ctx.path, ctx.depth
1771 FROM {context} ctx
1772 JOIN {course_categories} cc
1773 ON (cc.parent=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
1774 WHERE cc.id=?";
1775 $params = array($instanceid);
1776 if ($p = $DB->get_record_sql($sql, $params)) {
1777 $basepath = $p->path;
1778 $basedepth = $p->depth;
1779 } else if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), '*', $strictness)) {
1780 if (empty($category->parent)) {
1781 // ok - this is a top category
1782 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $category->parent)) {
1783 $basepath = $parent->path;
1784 $basedepth = $parent->depth;
1785 } else {
1786 // wrong parent category - no big deal, this can be fixed later
1787 $basepath = null;
1788 $basedepth = 0;
1790 } else {
1791 // incorrect category id
1792 $error_message = "incorrect course category id ($instanceid)";
1793 $result = false;
1795 break;
1797 case CONTEXT_COURSE:
1798 $sql = "SELECT ctx.path, ctx.depth
1799 FROM {context} ctx
1800 JOIN {course} c
1801 ON (c.category=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
1802 WHERE c.id=? AND c.id !=" . SITEID;
1803 $params = array($instanceid);
1804 if ($p = $DB->get_record_sql($sql, $params)) {
1805 $basepath = $p->path;
1806 $basedepth = $p->depth;
1807 } else if ($course = $DB->get_record('course', array('id'=>$instanceid), '*', $strictness)) {
1808 if ($course->id == SITEID) {
1809 //ok - no parent category
1810 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
1811 $basepath = $parent->path;
1812 $basedepth = $parent->depth;
1813 } else {
1814 // wrong parent category of course - no big deal, this can be fixed later
1815 $basepath = null;
1816 $basedepth = 0;
1818 } else if ($instanceid == SITEID) {
1819 // no errors for missing site course during installation
1820 return false;
1821 } else {
1822 // incorrect course id
1823 $error_message = "incorrect course id ($instanceid)";
1824 $result = false;
1826 break;
1828 case CONTEXT_MODULE:
1829 $sql = "SELECT ctx.path, ctx.depth
1830 FROM {context} ctx
1831 JOIN {course_modules} cm
1832 ON (cm.course=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
1833 WHERE cm.id=?";
1834 $params = array($instanceid);
1835 if ($p = $DB->get_record_sql($sql, $params)) {
1836 $basepath = $p->path;
1837 $basedepth = $p->depth;
1838 } else if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), '*', $strictness)) {
1839 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course, $strictness)) {
1840 $basepath = $parent->path;
1841 $basedepth = $parent->depth;
1842 } else {
1843 // course does not exist - modules can not exist without a course
1844 $error_message = "course does not exist ($cm->course) - modules can not exist without a course";
1845 $result = false;
1847 } else {
1848 // cm does not exist
1849 $error_message = "cm with id $instanceid does not exist";
1850 $result = false;
1852 break;
1854 case CONTEXT_BLOCK:
1855 $sql = "SELECT ctx.path, ctx.depth
1856 FROM {context} ctx
1857 JOIN {block_instances} bi ON (bi.parentcontextid=ctx.id)
1858 WHERE bi.id = ?";
1859 $params = array($instanceid, CONTEXT_COURSE);
1860 if ($p = $DB->get_record_sql($sql, $params, '*', $strictness)) {
1861 $basepath = $p->path;
1862 $basedepth = $p->depth;
1863 } else {
1864 // block does not exist
1865 $error_message = 'block or parent context does not exist';
1866 $result = false;
1868 break;
1869 case CONTEXT_USER:
1870 // default to basepath
1871 break;
1874 // if grandparents unknown, maybe rebuild_context_path() will solve it later
1875 if ($basedepth != 0) {
1876 $context->depth = $basedepth+1;
1879 if (!$result) {
1880 debugging('Error: could not insert new context level "'.
1881 s($contextlevel).'", instance "'.
1882 s($instanceid).'". ' . $error_message);
1884 return false;
1887 $id = $DB->insert_record('context', $context);
1888 // can't set the full path till we know the id!
1889 if ($basedepth != 0 and !empty($basepath)) {
1890 $DB->set_field('context', 'path', $basepath.'/'. $id, array('id'=>$id));
1892 return get_context_instance_by_id($id);
1896 * Returns system context or null if can not be created yet.
1898 * @param bool $cache use caching
1899 * @return mixed system context or null
1901 function get_system_context($cache = true) {
1902 global $DB, $ACCESSLIB_PRIVATE;
1903 if ($cache and defined('SYSCONTEXTID')) {
1904 if (is_null($ACCESSLIB_PRIVATE->systemcontext)) {
1905 $ACCESSLIB_PRIVATE->systemcontext = new stdClass();
1906 $ACCESSLIB_PRIVATE->systemcontext->id = SYSCONTEXTID;
1907 $ACCESSLIB_PRIVATE->systemcontext->contextlevel = CONTEXT_SYSTEM;
1908 $ACCESSLIB_PRIVATE->systemcontext->instanceid = 0;
1909 $ACCESSLIB_PRIVATE->systemcontext->path = '/'.SYSCONTEXTID;
1910 $ACCESSLIB_PRIVATE->systemcontext->depth = 1;
1912 return $ACCESSLIB_PRIVATE->systemcontext;
1914 try {
1915 $context = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM));
1916 } catch (dml_exception $e) {
1917 //table does not exist yet, sorry
1918 return null;
1921 if (!$context) {
1922 $context = new stdClass();
1923 $context->contextlevel = CONTEXT_SYSTEM;
1924 $context->instanceid = 0;
1925 $context->depth = 1;
1926 $context->path = null; //not known before insert
1928 try {
1929 $context->id = $DB->insert_record('context', $context);
1930 } catch (dml_exception $e) {
1931 // can not create context yet, sorry
1932 return null;
1936 if (!isset($context->depth) or $context->depth != 1 or $context->instanceid != 0 or $context->path != '/'.$context->id) {
1937 $context->instanceid = 0;
1938 $context->path = '/'.$context->id;
1939 $context->depth = 1;
1940 $DB->update_record('context', $context);
1943 if (!defined('SYSCONTEXTID')) {
1944 define('SYSCONTEXTID', $context->id);
1947 $ACCESSLIB_PRIVATE->systemcontext = $context;
1948 return $ACCESSLIB_PRIVATE->systemcontext;
1952 * Remove a context record and any dependent entries,
1953 * removes context from static context cache too
1955 * @param int $level
1956 * @param int $instanceid
1957 * @param bool $deleterecord false means keep record for now
1958 * @return bool returns true or throws an exception
1960 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
1961 global $DB, $ACCESSLIB_PRIVATE, $CFG;
1963 // do not use get_context_instance(), because the related object might not exist,
1964 // or the context does not exist yet and it would be created now
1965 if ($context = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
1966 // delete these first because they might fetch the context and try to recreate it!
1967 blocks_delete_all_for_context($context->id);
1968 filter_delete_all_for_context($context->id);
1970 require_once($CFG->dirroot . '/comment/lib.php');
1971 comment::delete_comments(array('contextid'=>$context->id));
1973 require_once($CFG->dirroot.'/rating/lib.php');
1974 $delopt = new stdclass();
1975 $delopt->contextid = $context->id;
1976 $rm = new rating_manager();
1977 $rm->delete_ratings($delopt);
1979 // delete all files attached to this context
1980 $fs = get_file_storage();
1981 $fs->delete_area_files($context->id);
1983 // now delete stuff from role related tables, role_unassign_all
1984 // and unenrol should be called earlier to do proper cleanup
1985 $DB->delete_records('role_assignments', array('contextid'=>$context->id));
1986 $DB->delete_records('role_capabilities', array('contextid'=>$context->id));
1987 $DB->delete_records('role_names', array('contextid'=>$context->id));
1989 // and finally it is time to delete the context record if requested
1990 if ($deleterecord) {
1991 $DB->delete_records('context', array('id'=>$context->id));
1992 // purge static context cache if entry present
1993 $ACCESSLIB_PRIVATE->contexcache->remove($context);
1996 // do not mark dirty contexts if parents unknown
1997 if (!is_null($context->path) and $context->depth > 0) {
1998 mark_context_dirty($context->path);
2002 return true;
2006 * Precreates all contexts including all parents
2008 * @param int $contextlevel empty means all
2009 * @param bool $buildpaths update paths and depths
2010 * @return void
2012 function create_contexts($contextlevel = null, $buildpaths = true) {
2013 global $DB;
2015 //make sure system context exists
2016 $syscontext = get_system_context(false);
2018 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSECAT
2019 or $contextlevel == CONTEXT_COURSE
2020 or $contextlevel == CONTEXT_MODULE
2021 or $contextlevel == CONTEXT_BLOCK) {
2022 $sql = "INSERT INTO {context} (contextlevel, instanceid)
2023 SELECT ".CONTEXT_COURSECAT.", cc.id
2024 FROM {course}_categories cc
2025 WHERE NOT EXISTS (SELECT 'x'
2026 FROM {context} cx
2027 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
2028 $DB->execute($sql);
2032 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSE
2033 or $contextlevel == CONTEXT_MODULE
2034 or $contextlevel == CONTEXT_BLOCK) {
2035 $sql = "INSERT INTO {context} (contextlevel, instanceid)
2036 SELECT ".CONTEXT_COURSE.", c.id
2037 FROM {course} c
2038 WHERE NOT EXISTS (SELECT 'x'
2039 FROM {context} cx
2040 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
2041 $DB->execute($sql);
2045 if (empty($contextlevel) or $contextlevel == CONTEXT_MODULE
2046 or $contextlevel == CONTEXT_BLOCK) {
2047 $sql = "INSERT INTO {context} (contextlevel, instanceid)
2048 SELECT ".CONTEXT_MODULE.", cm.id
2049 FROM {course}_modules cm
2050 WHERE NOT EXISTS (SELECT 'x'
2051 FROM {context} cx
2052 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
2053 $DB->execute($sql);
2056 if (empty($contextlevel) or $contextlevel == CONTEXT_USER
2057 or $contextlevel == CONTEXT_BLOCK) {
2058 $sql = "INSERT INTO {context} (contextlevel, instanceid)
2059 SELECT ".CONTEXT_USER.", u.id
2060 FROM {user} u
2061 WHERE u.deleted=0
2062 AND NOT EXISTS (SELECT 'x'
2063 FROM {context} cx
2064 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
2065 $DB->execute($sql);
2069 if (empty($contextlevel) or $contextlevel == CONTEXT_BLOCK) {
2070 $sql = "INSERT INTO {context} (contextlevel, instanceid)
2071 SELECT ".CONTEXT_BLOCK.", bi.id
2072 FROM {block_instances} bi
2073 WHERE NOT EXISTS (SELECT 'x'
2074 FROM {context} cx
2075 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
2076 $DB->execute($sql);
2079 if ($buildpaths) {
2080 build_context_path(false);
2085 * Remove stale context records
2087 * @return bool
2089 function cleanup_contexts() {
2090 global $DB;
2092 $sql = " SELECT c.contextlevel,
2093 c.instanceid AS instanceid
2094 FROM {context} c
2095 LEFT OUTER JOIN {course}_categories t
2096 ON c.instanceid = t.id
2097 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
2098 UNION
2099 SELECT c.contextlevel,
2100 c.instanceid
2101 FROM {context} c
2102 LEFT OUTER JOIN {course} t
2103 ON c.instanceid = t.id
2104 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
2105 UNION
2106 SELECT c.contextlevel,
2107 c.instanceid
2108 FROM {context} c
2109 LEFT OUTER JOIN {course}_modules t
2110 ON c.instanceid = t.id
2111 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
2112 UNION
2113 SELECT c.contextlevel,
2114 c.instanceid
2115 FROM {context} c
2116 LEFT OUTER JOIN {user} t
2117 ON c.instanceid = t.id
2118 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
2119 UNION
2120 SELECT c.contextlevel,
2121 c.instanceid
2122 FROM {context} c
2123 LEFT OUTER JOIN {block_instances} t
2124 ON c.instanceid = t.id
2125 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
2128 // transactions used only for performance reasons here
2129 $transaction = $DB->start_delegated_transaction();
2131 $rs = $DB->get_recordset_sql($sql);
2132 foreach ($rs as $ctx) {
2133 delete_context($ctx->contextlevel, $ctx->instanceid);
2135 $rs->close();
2137 $transaction->allow_commit();
2138 return true;
2142 * Preloads all contexts relating to a course: course, modules. Block contexts
2143 * are no longer loaded here. The contexts for all the blocks on the current
2144 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
2146 * @param int $courseid Course ID
2147 * @return void
2149 function preload_course_contexts($courseid) {
2150 global $DB, $ACCESSLIB_PRIVATE;
2152 // Users can call this multiple times without doing any harm
2153 global $ACCESSLIB_PRIVATE;
2154 if (array_key_exists($courseid, $ACCESSLIB_PRIVATE->preloadedcourses)) {
2155 return;
2158 $params = array($courseid, $courseid, $courseid);
2159 $sql = "SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
2160 FROM {course_modules} cm
2161 JOIN {context} x ON x.instanceid=cm.id
2162 WHERE cm.course=? AND x.contextlevel=".CONTEXT_MODULE."
2164 UNION ALL
2166 SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
2167 FROM {context} x
2168 WHERE x.instanceid=? AND x.contextlevel=".CONTEXT_COURSE."";
2170 $rs = $DB->get_recordset_sql($sql, $params);
2171 foreach($rs as $context) {
2172 $ACCESSLIB_PRIVATE->contexcache->add($context);
2174 $rs->close();
2175 $ACCESSLIB_PRIVATE->preloadedcourses[$courseid] = true;
2179 * Get the context instance as an object. This function will create the
2180 * context instance if it does not exist yet.
2182 * @todo Remove code branch from previous fix MDL-9016 which is no longer needed
2184 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2185 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
2186 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
2187 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
2188 * MUST_EXIST means throw exception if no record or multiple records found
2189 * @return object The context object.
2191 function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
2192 global $DB, $ACCESSLIB_PRIVATE;
2193 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK);
2195 /// System context has special cache
2196 if ($contextlevel == CONTEXT_SYSTEM) {
2197 return get_system_context();
2200 /// check allowed context levels
2201 if (!in_array($contextlevel, $allowed_contexts)) {
2202 // fatal error, code must be fixed - probably typo or switched parameters
2203 print_error('invalidcourselevel');
2206 // Various operations rely on context cache
2207 $cache = $ACCESSLIB_PRIVATE->contexcache;
2209 if (!is_array($instance)) {
2210 /// Check the cache
2211 $context = $cache->get($contextlevel, $instance);
2212 if ($context) {
2213 return $context;
2216 /// Get it from the database, or create it
2217 if (!$context = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instance))) {
2218 $context = create_context($contextlevel, $instance, $strictness);
2221 /// Only add to cache if context isn't empty.
2222 if (!empty($context)) {
2223 $cache->add($context);
2226 return $context;
2230 /// ok, somebody wants to load several contexts to save some db queries ;-)
2231 $instances = $instance;
2232 $result = array();
2234 foreach ($instances as $key=>$instance) {
2235 /// Check the cache first
2236 if ($context = $cache->get($contextlevel, $instance)) { // Already cached
2237 $result[$instance] = $context;
2238 unset($instances[$key]);
2239 continue;
2243 if ($instances) {
2244 list($instanceids, $params) = $DB->get_in_or_equal($instances, SQL_PARAMS_QM);
2245 array_unshift($params, $contextlevel);
2246 $sql = "SELECT instanceid, id, contextlevel, path, depth
2247 FROM {context}
2248 WHERE contextlevel=? AND instanceid $instanceids";
2250 if (!$contexts = $DB->get_records_sql($sql, $params)) {
2251 $contexts = array();
2254 foreach ($instances as $instance) {
2255 if (isset($contexts[$instance])) {
2256 $context = $contexts[$instance];
2257 } else {
2258 $context = create_context($contextlevel, $instance);
2261 if (!empty($context)) {
2262 $cache->add($context);
2265 $result[$instance] = $context;
2269 return $result;
2274 * Get a context instance as an object, from a given context id.
2276 * @param int $id context id
2277 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
2278 * MUST_EXIST means throw exception if no record or multiple records found
2279 * @return stdClass|bool the context object or false if not found.
2281 function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
2282 global $DB, $ACCESSLIB_PRIVATE;
2284 if ($id == SYSCONTEXTID) {
2285 return get_system_context();
2288 $cache = $ACCESSLIB_PRIVATE->contexcache;
2289 if ($context = $cache->get_by_id($id)) {
2290 return $context;
2293 if ($context = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
2294 $cache->add($context);
2295 return $context;
2298 return false;
2303 * Get the local override (if any) for a given capability in a role in a context
2305 * @param int $roleid
2306 * @param int $contextid
2307 * @param string $capability
2309 function get_local_override($roleid, $contextid, $capability) {
2310 global $DB;
2311 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
2315 * Returns context instance plus related course and cm instances
2316 * @param int $contextid
2317 * @return array of ($context, $course, $cm)
2319 function get_context_info_array($contextid) {
2320 global $DB;
2322 $context = get_context_instance_by_id($contextid, MUST_EXIST);
2323 $course = null;
2324 $cm = null;
2326 if ($context->contextlevel == CONTEXT_COURSE) {
2327 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
2329 } else if ($context->contextlevel == CONTEXT_MODULE) {
2330 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
2331 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
2333 } else if ($context->contextlevel == CONTEXT_BLOCK) {
2334 $parentcontexts = get_parent_contexts($context, false);
2335 $parent = reset($parentcontexts);
2336 $parent = get_context_instance_by_id($parent);
2338 if ($parent->contextlevel == CONTEXT_COURSE) {
2339 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
2340 } else if ($parent->contextlevel == CONTEXT_MODULE) {
2341 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
2342 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
2346 return array($context, $course, $cm);
2350 * Returns current course id or null if outside of course based on context parameter.
2351 * @param object $context
2352 * @return int|bool related course id or false
2354 function get_courseid_from_context($context) {
2355 if (empty($context->contextlevel)) {
2356 debugging('Invalid context object specified in get_courseid_from_context() call');
2357 return false;
2359 if ($context->contextlevel == CONTEXT_COURSE) {
2360 return $context->instanceid;
2363 if ($context->contextlevel < CONTEXT_COURSE) {
2364 return false;
2367 if ($context->contextlevel == CONTEXT_MODULE) {
2368 $parentcontexts = get_parent_contexts($context, false);
2369 $parent = reset($parentcontexts);
2370 $parent = get_context_instance_by_id($parent);
2371 return $parent->instanceid;
2374 if ($context->contextlevel == CONTEXT_BLOCK) {
2375 $parentcontexts = get_parent_contexts($context, false);
2376 $parent = reset($parentcontexts);
2377 return get_courseid_from_context(get_context_instance_by_id($parent));
2380 return false;
2384 //////////////////////////////////////
2385 // DB TABLE RELATED FUNCTIONS //
2386 //////////////////////////////////////
2389 * function that creates a role
2391 * @param string $name role name
2392 * @param string $shortname role short name
2393 * @param string $description role description
2394 * @param string $archetype
2395 * @return int id or dml_exception
2397 function create_role($name, $shortname, $description, $archetype = '') {
2398 global $DB;
2400 if (strpos($archetype, 'moodle/legacy:') !== false) {
2401 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
2404 // verify role archetype actually exists
2405 $archetypes = get_role_archetypes();
2406 if (empty($archetypes[$archetype])) {
2407 $archetype = '';
2410 // Get the system context.
2411 $context = get_context_instance(CONTEXT_SYSTEM);
2413 // Insert the role record.
2414 $role = new stdClass();
2415 $role->name = $name;
2416 $role->shortname = $shortname;
2417 $role->description = $description;
2418 $role->archetype = $archetype;
2420 //find free sortorder number
2421 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
2422 if (empty($role->sortorder)) {
2423 $role->sortorder = 1;
2425 $id = $DB->insert_record('role', $role);
2427 return $id;
2431 * Function that deletes a role and cleanups up after it
2433 * @param int $roleid id of role to delete
2434 * @return bool always true
2436 function delete_role($roleid) {
2437 global $CFG, $DB;
2439 // first unssign all users
2440 role_unassign_all(array('roleid'=>$roleid));
2442 // cleanup all references to this role, ignore errors
2443 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2444 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
2445 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
2446 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
2447 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
2448 $DB->delete_records('role_names', array('roleid'=>$roleid));
2449 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
2451 // finally delete the role itself
2452 // get this before the name is gone for logging
2453 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
2455 $DB->delete_records('role', array('id'=>$roleid));
2457 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
2459 return true;
2463 * Function to write context specific overrides, or default capabilities.
2465 * @param string $capability string name
2466 * @param int $permission CAP_ constants
2467 * @param int $roleid role id
2468 * @param int $contextid context id
2469 * @param bool $overwrite
2470 * @return bool always true or exception
2472 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
2473 global $USER, $DB;
2475 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
2476 unassign_capability($capability, $roleid, $contextid);
2477 return true;
2480 $existing = $DB->get_record('role_capabilities', array('contextid'=>$contextid, 'roleid'=>$roleid, 'capability'=>$capability));
2482 if ($existing and !$overwrite) { // We want to keep whatever is there already
2483 return true;
2486 $cap = new stdClass();
2487 $cap->contextid = $contextid;
2488 $cap->roleid = $roleid;
2489 $cap->capability = $capability;
2490 $cap->permission = $permission;
2491 $cap->timemodified = time();
2492 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
2494 if ($existing) {
2495 $cap->id = $existing->id;
2496 $DB->update_record('role_capabilities', $cap);
2497 } else {
2498 $c = $DB->get_record('context', array('id'=>$contextid));
2499 $DB->insert_record('role_capabilities', $cap);
2501 return true;
2505 * Unassign a capability from a role.
2507 * @param string $capability the name of the capability
2508 * @param int $roleid the role id
2509 * @param int $contextid null means all contexts
2510 * @return boolean success or failure
2512 function unassign_capability($capability, $roleid, $contextid = null) {
2513 global $DB;
2515 if (!empty($contextid)) {
2516 // delete from context rel, if this is the last override in this context
2517 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$contextid));
2518 } else {
2519 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
2521 return true;
2526 * Get the roles that have a given capability assigned to it
2528 * This function does not resolve the actual permission of the capability.
2529 * It just checks for permissions and overrides.
2530 * Use get_roles_with_cap_in_context() if resolution is required.
2532 * @param string $capability - capability name (string)
2533 * @param string $permission - optional, the permission defined for this capability
2534 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
2535 * @param stdClass $context, null means any
2536 * @return array of role objects
2538 function get_roles_with_capability($capability, $permission = null, $context = null) {
2539 global $DB;
2541 if ($context) {
2542 $contexts = get_parent_contexts($context, true);
2543 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
2544 $contextsql = "AND rc.contextid $insql";
2545 } else {
2546 $params = array();
2547 $contextsql = '';
2550 if ($permission) {
2551 $permissionsql = " AND rc.permission = :permission";
2552 $params['permission'] = $permission;
2553 } else {
2554 $permissionsql = '';
2557 $sql = "SELECT r.*
2558 FROM {role} r
2559 WHERE r.id IN (SELECT rc.roleid
2560 FROM {role_capabilities} rc
2561 WHERE rc.capability = :capname
2562 $contextsql
2563 $permissionsql)";
2564 $params['capname'] = $capability;
2567 return $DB->get_records_sql($sql, $params);
2572 * This function makes a role-assignment (a role for a user in a particular context)
2574 * @param int $roleid the role of the id
2575 * @param int $userid userid
2576 * @param int $contextid id of the context
2577 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
2578 * @prama int $itemid id of enrolment/auth plugin
2579 * @param string $timemodified defaults to current time
2580 * @return int new/existing id of the assignment
2582 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
2583 global $USER, $CFG, $DB;
2585 // first of all detect if somebody is using old style parameters
2586 if ($contextid === 0 or is_numeric($component)) {
2587 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
2590 // now validate all parameters
2591 if (empty($roleid)) {
2592 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
2595 if (empty($userid)) {
2596 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
2599 if ($itemid) {
2600 if (strpos($component, '_') === false) {
2601 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
2603 } else {
2604 $itemid = 0;
2605 if ($component !== '' and strpos($component, '_') === false) {
2606 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
2610 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
2611 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
2614 $context = get_context_instance_by_id($contextid, MUST_EXIST);
2616 if (!$timemodified) {
2617 $timemodified = time();
2620 /// Check for existing entry
2621 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
2623 if ($ras) {
2624 // role already assigned - this should not happen
2625 if (count($ras) > 1) {
2626 //very weird - remove all duplicates!
2627 $ra = array_shift($ras);
2628 foreach ($ras as $r) {
2629 $DB->delete_records('role_assignments', array('id'=>$r->id));
2631 } else {
2632 $ra = reset($ras);
2635 // actually there is no need to update, reset anything or trigger any event, so just return
2636 return $ra->id;
2639 // Create a new entry
2640 $ra = new stdClass();
2641 $ra->roleid = $roleid;
2642 $ra->contextid = $context->id;
2643 $ra->userid = $userid;
2644 $ra->component = $component;
2645 $ra->itemid = $itemid;
2646 $ra->timemodified = $timemodified;
2647 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
2649 $ra->id = $DB->insert_record('role_assignments', $ra);
2651 // mark context as dirty - again expensive, but needed
2652 mark_context_dirty($context->path);
2654 if (!empty($USER->id) && $USER->id == $userid) {
2655 // If the user is the current user, then do full reload of capabilities too.
2656 load_all_capabilities();
2659 events_trigger('role_assigned', $ra);
2661 return $ra->id;
2665 * Removes one role assignment
2667 * @param int $roleid
2668 * @param int $userid
2669 * @param int $contextid
2670 * @param string $component
2671 * @param int $itemid
2672 * @return void
2674 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
2675 global $USER, $CFG, $DB;
2677 // first make sure the params make sense
2678 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
2679 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
2682 if ($itemid) {
2683 if (strpos($component, '_') === false) {
2684 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
2686 } else {
2687 $itemid = 0;
2688 if ($component !== '' and strpos($component, '_') === false) {
2689 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
2693 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
2697 * Removes multiple role assignments, parameters may contain:
2698 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
2700 * @param array $params role assignment parameters
2701 * @param bool $subcontexts unassign in subcontexts too
2702 * @param bool $includmanual include manual role assignments too
2703 * @return void
2705 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
2706 global $USER, $CFG, $DB;
2708 if (!$params) {
2709 throw new coding_exception('Missing parameters in role_unsassign_all() call');
2712 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
2713 foreach ($params as $key=>$value) {
2714 if (!in_array($key, $allowed)) {
2715 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
2719 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
2720 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
2723 if ($includemanual) {
2724 if (!isset($params['component']) or $params['component'] === '') {
2725 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
2729 if ($subcontexts) {
2730 if (empty($params['contextid'])) {
2731 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
2735 $ras = $DB->get_records('role_assignments', $params);
2736 foreach($ras as $ra) {
2737 $DB->delete_records('role_assignments', array('id'=>$ra->id));
2738 if ($context = get_context_instance_by_id($ra->contextid)) {
2739 // this is a bit expensive but necessary
2740 mark_context_dirty($context->path);
2741 /// If the user is the current user, then do full reload of capabilities too.
2742 if (!empty($USER->id) && $USER->id == $ra->userid) {
2743 load_all_capabilities();
2746 events_trigger('role_unassigned', $ra);
2748 unset($ras);
2750 // process subcontexts
2751 if ($subcontexts and $context = get_context_instance_by_id($params['contextid'])) {
2752 $contexts = get_child_contexts($context);
2753 $mparams = $params;
2754 foreach($contexts as $context) {
2755 $mparams['contextid'] = $context->id;
2756 $ras = $DB->get_records('role_assignments', $mparams);
2757 foreach($ras as $ra) {
2758 $DB->delete_records('role_assignments', array('id'=>$ra->id));
2759 // this is a bit expensive but necessary
2760 mark_context_dirty($context->path);
2761 /// If the user is the current user, then do full reload of capabilities too.
2762 if (!empty($USER->id) && $USER->id == $ra->userid) {
2763 load_all_capabilities();
2765 events_trigger('role_unassigned', $ra);
2770 // do this once more for all manual role assignments
2771 if ($includemanual) {
2772 $params['component'] = '';
2773 role_unassign_all($params, $subcontexts, false);
2779 * Determines if a user is currently logged in
2781 * @return bool
2783 function isloggedin() {
2784 global $USER;
2786 return (!empty($USER->id));
2790 * Determines if a user is logged in as real guest user with username 'guest'.
2792 * @param int|object $user mixed user object or id, $USER if not specified
2793 * @return bool true if user is the real guest user, false if not logged in or other user
2795 function isguestuser($user = null) {
2796 global $USER, $DB, $CFG;
2798 // make sure we have the user id cached in config table, because we are going to use it a lot
2799 if (empty($CFG->siteguest)) {
2800 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
2801 // guest does not exist yet, weird
2802 return false;
2804 set_config('siteguest', $guestid);
2806 if ($user === null) {
2807 $user = $USER;
2810 if ($user === null) {
2811 // happens when setting the $USER
2812 return false;
2814 } else if (is_numeric($user)) {
2815 return ($CFG->siteguest == $user);
2817 } else if (is_object($user)) {
2818 if (empty($user->id)) {
2819 return false; // not logged in means is not be guest
2820 } else {
2821 return ($CFG->siteguest == $user->id);
2824 } else {
2825 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
2830 * Does user have a (temporary or real) guest access to course?
2832 * @param stdClass $context
2833 * @param stdClass|int $user
2834 * @return bool
2836 function is_guest($context, $user = null) {
2837 global $USER;
2839 // first find the course context
2840 $coursecontext = get_course_context($context);
2842 // make sure there is a real user specified
2843 if ($user === null) {
2844 $userid = !empty($USER->id) ? $USER->id : 0;
2845 } else {
2846 $userid = !empty($user->id) ? $user->id : $user;
2849 if (isguestuser($userid)) {
2850 // can not inspect or be enrolled
2851 return true;
2854 if (has_capability('moodle/course:view', $coursecontext, $user)) {
2855 // viewing users appear out of nowhere, they are neither guests nor participants
2856 return false;
2859 // consider only real active enrolments here
2860 if (is_enrolled($coursecontext, $user, '', true)) {
2861 return false;
2864 return true;
2869 * Returns true if the user has moodle/course:view capability in the course,
2870 * this is intended for admins, managers (aka small admins), inspectors, etc.
2872 * @param stdClass $context
2873 * @param int|object $user, if null $USER is used
2874 * @param string $withcapability extra capability name
2875 * @return bool
2877 function is_viewing($context, $user = null, $withcapability = '') {
2878 // first find the course context
2879 $coursecontext = get_course_context($context);
2881 if (isguestuser($user)) {
2882 // can not inspect
2883 return false;
2886 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2887 // admins are allowed to inspect courses
2888 return false;
2891 if ($withcapability and !has_capability($withcapability, $context, $user)) {
2892 // site admins always have the capability, but the enrolment above blocks
2893 return false;
2896 return true;
2900 * Returns true if user is enrolled (is participating) in course
2901 * this is intended for students and teachers.
2903 * @param object $context
2904 * @param int|object $user, if null $USER is used, otherwise user object or id expected
2905 * @param string $withcapability extra capability name
2906 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2907 * @return bool
2909 function is_enrolled($context, $user = null, $withcapability = '', $onlyactive = false) {
2910 global $USER, $DB;
2912 // first find the course context
2913 $coursecontext = get_course_context($context);
2915 // make sure there is a real user specified
2916 if ($user === null) {
2917 $userid = !empty($USER->id) ? $USER->id : 0;
2918 } else {
2919 $userid = !empty($user->id) ? $user->id : $user;
2922 if (empty($userid)) {
2923 // not-logged-in!
2924 return false;
2925 } else if (isguestuser($userid)) {
2926 // guest account can not be enrolled anywhere
2927 return false;
2930 if ($coursecontext->instanceid == SITEID) {
2931 // everybody participates on frontpage
2932 } else {
2933 if ($onlyactive) {
2934 $sql = "SELECT ue.*
2935 FROM {user_enrolments} ue
2936 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2937 JOIN {user} u ON u.id = ue.userid
2938 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
2939 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2940 // this result should be very small, better not do the complex time checks in sql for now ;-)
2941 $enrolments = $DB->get_records_sql($sql, $params);
2942 $now = time();
2943 // make sure the enrol period is ok
2944 $result = false;
2945 foreach ($enrolments as $e) {
2946 if ($e->timestart > $now) {
2947 continue;
2949 if ($e->timeend and $e->timeend < $now) {
2950 continue;
2952 $result = true;
2953 break;
2955 if (!$result) {
2956 return false;
2959 } else {
2960 // any enrolment is good for us here, even outdated, disabled or inactive
2961 $sql = "SELECT 'x'
2962 FROM {user_enrolments} ue
2963 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2964 JOIN {user} u ON u.id = ue.userid
2965 WHERE ue.userid = :userid AND u.deleted = 0";
2966 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2967 if (!$DB->record_exists_sql($sql, $params)) {
2968 return false;
2973 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2974 return false;
2977 return true;
2981 * Returns true if the user is able to access the course.
2983 * This function is in no way, shape, or form a substitute for require_login.
2984 * It should only be used in circumstances where it is not possible to call require_login
2985 * such as the navigation.
2987 * This function checks many of the methods of access to a course such as the view
2988 * capability, enrollments, and guest access. It also makes use of the cache
2989 * generated by require_login for guest access.
2991 * The flags within the $USER object that are used here should NEVER be used outside
2992 * of this function can_access_course and require_login. Doing so WILL break future
2993 * versions.
2995 * @global moodle_database $DB
2996 * @param stdClass $context
2997 * @param stdClass|null $user
2998 * @param string $withcapability Check for this capability as well.
2999 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
3000 * @param boolean $trustcache If set to false guest access will always be checked
3001 * against the enrolment plugins from the course, rather
3002 * than the cache generated by require_login.
3003 * @return boolean Returns true if the user is able to access the course
3005 function can_access_course($context, $user = null, $withcapability = '', $onlyactive = false, $trustcache = true) {
3006 global $DB, $USER;
3008 $coursecontext = get_course_context($context);
3009 $courseid = $coursecontext->instanceid;
3011 // First check the obvious, is the user viewing or is the user enrolled.
3012 if (is_viewing($coursecontext, $user, $withcapability) || is_enrolled($coursecontext, $user, $withcapability, $onlyactive)) {
3013 // How easy was that!
3014 return true;
3017 $access = false;
3018 if (!isset($USER->enrol)) {
3019 // Cache hasn't been generated yet so we can't trust it
3020 $trustcache = false;
3022 * These flags within the $USER object should NEVER be used outside of this
3023 * function can_access_course and the function require_login.
3024 * Doing so WILL break future versions!!!!
3026 $USER->enrol = array();
3027 $USER->enrol['enrolled'] = array();
3028 $USER->enrol['tempguest'] = array();
3031 // If we don't trust the cache we need to check with the courses enrolment
3032 // plugin instances to see if the user can access the course as a guest.
3033 if (!$trustcache) {
3034 // Ok, off to the database we go!
3035 $instances = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
3036 $enrols = enrol_get_plugins(true);
3037 foreach($instances as $instance) {
3038 if (!isset($enrols[$instance->enrol])) {
3039 continue;
3041 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3042 if ($until !== false) {
3043 // Never use me anywhere but here and require_login
3044 $USER->enrol['tempguest'][$courseid] = $until;
3045 $access = true;
3046 break;
3051 // If we don't already have access (from above) check the cache and see whether
3052 // there is record of it in there.
3053 if (!$access && isset($USER->enrol['tempguest'][$courseid])) {
3054 // Never use me anywhere but here and require_login
3055 if ($USER->enrol['tempguest'][$courseid] == 0) {
3056 $access = true;
3057 } else if ($USER->enrol['tempguest'][$courseid] > time()) {
3058 $access = true;
3059 } else {
3060 //expired
3061 unset($USER->enrol['tempguest'][$courseid]);
3064 return $access;
3068 * Returns array with sql code and parameters returning all ids
3069 * of users enrolled into course.
3071 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
3073 * @param object $context
3074 * @param string $withcapability
3075 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
3076 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
3077 * @return array list($sql, $params)
3079 function get_enrolled_sql($context, $withcapability = '', $groupid = 0, $onlyactive = false) {
3080 global $DB, $CFG;
3082 // use unique prefix just in case somebody makes some SQL magic with the result
3083 static $i = 0;
3084 $i++;
3085 $prefix = 'eu'.$i.'_';
3087 // first find the course context
3088 $coursecontext = get_course_context($context);
3090 $isfrontpage = ($coursecontext->instanceid == SITEID);
3092 $joins = array();
3093 $wheres = array();
3094 $params = array();
3096 list($contextids, $contextpaths) = get_context_info_list($context);
3098 // get all relevant capability info for all roles
3099 if ($withcapability) {
3100 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
3101 $cparams['cap'] = $withcapability;
3103 $defs = array();
3104 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
3105 FROM {role_capabilities} rc
3106 JOIN {context} ctx on rc.contextid = ctx.id
3107 WHERE rc.contextid $incontexts AND rc.capability = :cap";
3108 $rcs = $DB->get_records_sql($sql, $cparams);
3109 foreach ($rcs as $rc) {
3110 $defs[$rc->path][$rc->roleid] = $rc->permission;
3113 $access = array();
3114 if (!empty($defs)) {
3115 foreach ($contextpaths as $path) {
3116 if (empty($defs[$path])) {
3117 continue;
3119 foreach($defs[$path] as $roleid => $perm) {
3120 if ($perm == CAP_PROHIBIT) {
3121 $access[$roleid] = CAP_PROHIBIT;
3122 continue;
3124 if (!isset($access[$roleid])) {
3125 $access[$roleid] = (int)$perm;
3131 unset($defs);
3133 // make lists of roles that are needed and prohibited
3134 $needed = array(); // one of these is enough
3135 $prohibited = array(); // must not have any of these
3136 foreach ($access as $roleid => $perm) {
3137 if ($perm == CAP_PROHIBIT) {
3138 unset($needed[$roleid]);
3139 $prohibited[$roleid] = true;
3140 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
3141 $needed[$roleid] = true;
3145 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3146 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3148 $nobody = false;
3150 if ($isfrontpage) {
3151 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
3152 $nobody = true;
3153 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
3154 // everybody not having prohibit has the capability
3155 $needed = array();
3156 } else if (empty($needed)) {
3157 $nobody = true;
3159 } else {
3160 if (!empty($prohibited[$defaultuserroleid])) {
3161 $nobody = true;
3162 } else if (!empty($needed[$defaultuserroleid])) {
3163 // everybody not having prohibit has the capability
3164 $needed = array();
3165 } else if (empty($needed)) {
3166 $nobody = true;
3170 if ($nobody) {
3171 // nobody can match so return some SQL that does not return any results
3172 $wheres[] = "1 = 2";
3174 } else {
3176 if ($needed) {
3177 $ctxids = implode(',', $contextids);
3178 $roleids = implode(',', array_keys($needed));
3179 $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))";
3182 if ($prohibited) {
3183 $ctxids = implode(',', $contextids);
3184 $roleids = implode(',', array_keys($prohibited));
3185 $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))";
3186 $wheres[] = "{$prefix}ra4.id IS NULL";
3189 if ($groupid) {
3190 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
3191 $params["{$prefix}gmid"] = $groupid;
3195 } else {
3196 if ($groupid) {
3197 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
3198 $params["{$prefix}gmid"] = $groupid;
3202 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
3203 $params["{$prefix}guestid"] = $CFG->siteguest;
3205 if ($isfrontpage) {
3206 // all users are "enrolled" on the frontpage
3207 } else {
3208 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
3209 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
3210 $params[$prefix.'courseid'] = $coursecontext->instanceid;
3212 if ($onlyactive) {
3213 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
3214 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
3215 $now = round(time(), -2); // rounding helps caching in DB
3216 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
3217 $prefix.'active'=>ENROL_USER_ACTIVE,
3218 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
3222 $joins = implode("\n", $joins);
3223 $wheres = "WHERE ".implode(" AND ", $wheres);
3225 $sql = "SELECT DISTINCT {$prefix}u.id
3226 FROM {user} {$prefix}u
3227 $joins
3228 $wheres";
3230 return array($sql, $params);
3234 * Returns list of users enrolled into course.
3235 * @param object $context
3236 * @param string $withcapability
3237 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
3238 * @param string $userfields requested user record fields
3239 * @param string $orderby
3240 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
3241 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
3242 * @return array of user records
3244 function get_enrolled_users($context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
3245 global $DB;
3247 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
3248 $sql = "SELECT $userfields
3249 FROM {user} u
3250 JOIN ($esql) je ON je.id = u.id
3251 WHERE u.deleted = 0";
3253 if ($orderby) {
3254 $sql = "$sql ORDER BY $orderby";
3255 } else {
3256 $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
3259 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3263 * Counts list of users enrolled into course (as per above function)
3264 * @param object $context
3265 * @param string $withcapability
3266 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
3267 * @return array of user records
3269 function count_enrolled_users($context, $withcapability = '', $groupid = 0) {
3270 global $DB;
3272 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
3273 $sql = "SELECT count(u.id)
3274 FROM {user} u
3275 JOIN ($esql) je ON je.id = u.id
3276 WHERE u.deleted = 0";
3278 return $DB->count_records_sql($sql, $params);
3283 * Loads the capability definitions for the component (from file).
3285 * Loads the capability definitions for the component (from file). If no
3286 * capabilities are defined for the component, we simply return an empty array.
3288 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
3289 * @return array array of capabilities
3291 function load_capability_def($component) {
3292 $defpath = get_component_directory($component).'/db/access.php';
3294 $capabilities = array();
3295 if (file_exists($defpath)) {
3296 require($defpath);
3297 if (!empty(${$component.'_capabilities'})) {
3298 // BC capability array name
3299 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
3300 debugging('componentname_capabilities array is deprecated, please use capabilities array only in access.php files');
3301 $capabilities = ${$component.'_capabilities'};
3305 return $capabilities;
3310 * Gets the capabilities that have been cached in the database for this component.
3311 * @param string $component - examples: 'moodle', 'mod_forum'
3312 * @return array array of capabilities
3314 function get_cached_capabilities($component = 'moodle') {
3315 global $DB;
3316 return $DB->get_records('capabilities', array('component'=>$component));
3320 * Returns default capabilities for given role archetype.
3321 * @param string $archetype role archetype
3322 * @return array
3324 function get_default_capabilities($archetype) {
3325 global $DB;
3327 if (!$archetype) {
3328 return array();
3331 $alldefs = array();
3332 $defaults = array();
3333 $components = array();
3334 $allcaps = $DB->get_records('capabilities');
3336 foreach ($allcaps as $cap) {
3337 if (!in_array($cap->component, $components)) {
3338 $components[] = $cap->component;
3339 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
3342 foreach($alldefs as $name=>$def) {
3343 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
3344 if (isset($def['archetypes'])) {
3345 if (isset($def['archetypes'][$archetype])) {
3346 $defaults[$name] = $def['archetypes'][$archetype];
3348 // 'legacy' is for backward compatibility with 1.9 access.php
3349 } else {
3350 if (isset($def['legacy'][$archetype])) {
3351 $defaults[$name] = $def['legacy'][$archetype];
3356 return $defaults;
3360 * Reset role capabilities to default according to selected role archetype.
3361 * If no archetype selected, removes all capabilities.
3362 * @param int $roleid
3363 * @return void
3365 function reset_role_capabilities($roleid) {
3366 global $DB;
3368 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
3369 $defaultcaps = get_default_capabilities($role->archetype);
3371 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
3373 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
3375 foreach($defaultcaps as $cap=>$permission) {
3376 assign_capability($cap, $permission, $roleid, $sitecontext->id);
3381 * Updates the capabilities table with the component capability definitions.
3382 * If no parameters are given, the function updates the core moodle
3383 * capabilities.
3385 * Note that the absence of the db/access.php capabilities definition file
3386 * will cause any stored capabilities for the component to be removed from
3387 * the database.
3389 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
3390 * @return boolean true if success, exception in case of any problems
3392 function update_capabilities($component = 'moodle') {
3393 global $DB, $OUTPUT, $ACCESSLIB_PRIVATE;
3395 $storedcaps = array();
3397 $filecaps = load_capability_def($component);
3398 $cachedcaps = get_cached_capabilities($component);
3399 if ($cachedcaps) {
3400 foreach ($cachedcaps as $cachedcap) {
3401 array_push($storedcaps, $cachedcap->name);
3402 // update risk bitmasks and context levels in existing capabilities if needed
3403 if (array_key_exists($cachedcap->name, $filecaps)) {
3404 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
3405 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
3407 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
3408 $updatecap = new stdClass();
3409 $updatecap->id = $cachedcap->id;
3410 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
3411 $DB->update_record('capabilities', $updatecap);
3413 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
3414 $updatecap = new stdClass();
3415 $updatecap->id = $cachedcap->id;
3416 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
3417 $DB->update_record('capabilities', $updatecap);
3420 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
3421 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
3423 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
3424 $updatecap = new stdClass();
3425 $updatecap->id = $cachedcap->id;
3426 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
3427 $DB->update_record('capabilities', $updatecap);
3433 // Are there new capabilities in the file definition?
3434 $newcaps = array();
3436 foreach ($filecaps as $filecap => $def) {
3437 if (!$storedcaps ||
3438 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
3439 if (!array_key_exists('riskbitmask', $def)) {
3440 $def['riskbitmask'] = 0; // no risk if not specified
3442 $newcaps[$filecap] = $def;
3445 // Add new capabilities to the stored definition.
3446 foreach ($newcaps as $capname => $capdef) {
3447 $capability = new stdClass();
3448 $capability->name = $capname;
3449 $capability->captype = $capdef['captype'];
3450 $capability->contextlevel = $capdef['contextlevel'];
3451 $capability->component = $component;
3452 $capability->riskbitmask = $capdef['riskbitmask'];
3454 $DB->insert_record('capabilities', $capability, false);
3456 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
3457 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
3458 foreach ($rolecapabilities as $rolecapability){
3459 //assign_capability will update rather than insert if capability exists
3460 if (!assign_capability($capname, $rolecapability->permission,
3461 $rolecapability->roleid, $rolecapability->contextid, true)){
3462 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
3466 // we ignore archetype key if we have cloned permissions
3467 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
3468 assign_legacy_capabilities($capname, $capdef['archetypes']);
3469 // 'legacy' is for backward compatibility with 1.9 access.php
3470 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
3471 assign_legacy_capabilities($capname, $capdef['legacy']);
3474 // Are there any capabilities that have been removed from the file
3475 // definition that we need to delete from the stored capabilities and
3476 // role assignments?
3477 capabilities_cleanup($component, $filecaps);
3479 // reset static caches
3480 $ACCESSLIB_PRIVATE->capabilities = null;
3482 return true;
3487 * Deletes cached capabilities that are no longer needed by the component.
3488 * Also unassigns these capabilities from any roles that have them.
3490 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
3491 * @param array $newcapdef array of the new capability definitions that will be
3492 * compared with the cached capabilities
3493 * @return int number of deprecated capabilities that have been removed
3495 function capabilities_cleanup($component, $newcapdef = null) {
3496 global $DB;
3498 $removedcount = 0;
3500 if ($cachedcaps = get_cached_capabilities($component)) {
3501 foreach ($cachedcaps as $cachedcap) {
3502 if (empty($newcapdef) ||
3503 array_key_exists($cachedcap->name, $newcapdef) === false) {
3505 // Remove from capabilities cache.
3506 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
3507 $removedcount++;
3508 // Delete from roles.
3509 if ($roles = get_roles_with_capability($cachedcap->name)) {
3510 foreach($roles as $role) {
3511 if (!unassign_capability($cachedcap->name, $role->id)) {
3512 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
3516 } // End if.
3519 return $removedcount;
3524 //////////////////
3525 // UI FUNCTIONS //
3526 //////////////////
3529 * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
3530 * @return string the name for this type of context.
3532 function get_contextlevel_name($contextlevel) {
3533 static $strcontextlevels = null;
3534 if (is_null($strcontextlevels)) {
3535 $strcontextlevels = array(
3536 CONTEXT_SYSTEM => get_string('coresystem'),
3537 CONTEXT_USER => get_string('user'),
3538 CONTEXT_COURSECAT => get_string('category'),
3539 CONTEXT_COURSE => get_string('course'),
3540 CONTEXT_MODULE => get_string('activitymodule'),
3541 CONTEXT_BLOCK => get_string('block')
3544 return $strcontextlevels[$contextlevel];
3548 * Prints human readable context identifier.
3550 * @param object $context the context.
3551 * @param boolean $withprefix whether to prefix the name of the context with the
3552 * type of context, e.g. User, Course, Forum, etc.
3553 * @param boolean $short whether to user the short name of the thing. Only applies
3554 * to course contexts
3555 * @return string the human readable context name.
3557 function print_context_name($context, $withprefix = true, $short = false) {
3558 global $DB;
3560 $name = '';
3561 switch ($context->contextlevel) {
3563 case CONTEXT_SYSTEM:
3564 $name = get_string('coresystem');
3565 break;
3567 case CONTEXT_USER:
3568 if ($user = $DB->get_record('user', array('id'=>$context->instanceid))) {
3569 if ($withprefix){
3570 $name = get_string('user').': ';
3572 $name .= fullname($user);
3574 break;
3576 case CONTEXT_COURSECAT:
3577 if ($category = $DB->get_record('course_categories', array('id'=>$context->instanceid))) {
3578 if ($withprefix){
3579 $name = get_string('category').': ';
3581 $name .=format_string($category->name);
3583 break;
3585 case CONTEXT_COURSE:
3586 if ($context->instanceid == SITEID) {
3587 $name = get_string('frontpage', 'admin');
3588 } else {
3589 if ($course = $DB->get_record('course', array('id'=>$context->instanceid))) {
3590 if ($withprefix){
3591 $name = get_string('course').': ';
3593 if ($short){
3594 $name .= format_string($course->shortname);
3595 } else {
3596 $name .= format_string($course->fullname);
3600 break;
3602 case CONTEXT_MODULE:
3603 if ($cm = $DB->get_record_sql('SELECT cm.*, md.name AS modname FROM {course_modules} cm ' .
3604 'JOIN {modules} md ON md.id = cm.module WHERE cm.id = ?', array($context->instanceid))) {
3605 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
3606 if ($withprefix){
3607 $name = get_string('modulename', $cm->modname).': ';
3609 $name .= $mod->name;
3612 break;
3614 case CONTEXT_BLOCK:
3615 if ($blockinstance = $DB->get_record('block_instances', array('id'=>$context->instanceid))) {
3616 global $CFG;
3617 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
3618 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
3619 $blockname = "block_$blockinstance->blockname";
3620 if ($blockobject = new $blockname()) {
3621 if ($withprefix){
3622 $name = get_string('block').': ';
3624 $name .= $blockobject->title;
3627 break;
3629 default:
3630 print_error('unknowncontext');
3631 return false;
3634 return $name;
3638 * Get a URL for a context, if there is a natural one. For example, for
3639 * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
3640 * user profile page.
3642 * @param object $context the context.
3643 * @return moodle_url
3645 function get_context_url($context) {
3646 global $COURSE, $DB;
3648 switch ($context->contextlevel) {
3649 case CONTEXT_USER:
3650 if ($COURSE->id == SITEID) {
3651 $url = new moodle_url('/user/profile.php', array('id'=>$context->instanceid));
3652 } else {
3653 $url = new moodle_url('/user/view.php', array('id'=>$context->instanceid, 'courseid'=>$COURSE->id));
3655 return $url;;
3657 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
3658 return new moodle_url('/course/category.php', array('id'=>$context->instanceid));
3660 case CONTEXT_COURSE: // 1 to 1 to course cat
3661 if ($context->instanceid != SITEID) {
3662 return new moodle_url('/course/view.php', array('id'=>$context->instanceid));
3664 break;
3666 case CONTEXT_MODULE: // 1 to 1 to course
3667 if ($modname = $DB->get_field_sql('SELECT md.name AS modname FROM {course_modules} cm ' .
3668 'JOIN {modules} md ON md.id = cm.module WHERE cm.id = ?', array($context->instanceid))) {
3669 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$context->instanceid));
3671 break;
3673 case CONTEXT_BLOCK:
3674 $parentcontexts = get_parent_contexts($context, false);
3675 $parent = reset($parentcontexts);
3676 $parent = get_context_instance_by_id($parent);
3677 return get_context_url($parent);
3680 return new moodle_url('/');
3684 * Returns an array of all the known types of risk
3685 * The array keys can be used, for example as CSS class names, or in calls to
3686 * print_risk_icon. The values are the corresponding RISK_ constants.
3688 * @return array all the known types of risk.
3690 function get_all_risks() {
3691 return array(
3692 'riskmanagetrust' => RISK_MANAGETRUST,
3693 'riskconfig' => RISK_CONFIG,
3694 'riskxss' => RISK_XSS,
3695 'riskpersonal' => RISK_PERSONAL,
3696 'riskspam' => RISK_SPAM,
3697 'riskdataloss' => RISK_DATALOSS,
3702 * Return a link to moodle docs for a given capability name
3704 * @param object $capability a capability - a row from the mdl_capabilities table.
3705 * @return string the human-readable capability name as a link to Moodle Docs.
3707 function get_capability_docs_link($capability) {
3708 global $CFG;
3709 $url = get_docs_url('Capabilities/' . $capability->name);
3710 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
3714 * Extracts the relevant capabilities given a contextid.
3715 * All case based, example an instance of forum context.
3716 * Will fetch all forum related capabilities, while course contexts
3717 * Will fetch all capabilities
3719 * capabilities
3720 * `name` varchar(150) NOT NULL,
3721 * `captype` varchar(50) NOT NULL,
3722 * `contextlevel` int(10) NOT NULL,
3723 * `component` varchar(100) NOT NULL,
3725 * @param object context
3726 * @return array
3728 function fetch_context_capabilities($context) {
3729 global $DB, $CFG;
3731 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
3733 $params = array();
3735 switch ($context->contextlevel) {
3737 case CONTEXT_SYSTEM: // all
3738 $SQL = "SELECT *
3739 FROM {capabilities}";
3740 break;
3742 case CONTEXT_USER:
3743 $extracaps = array('moodle/grade:viewall');
3744 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
3745 $SQL = "SELECT *
3746 FROM {capabilities}
3747 WHERE contextlevel = ".CONTEXT_USER."
3748 OR name $extra";
3749 break;
3751 case CONTEXT_COURSECAT: // course category context and bellow
3752 $SQL = "SELECT *
3753 FROM {capabilities}
3754 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
3755 break;
3757 case CONTEXT_COURSE: // course context and bellow
3758 $SQL = "SELECT *
3759 FROM {capabilities}
3760 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
3761 break;
3763 case CONTEXT_MODULE: // mod caps
3764 $cm = $DB->get_record('course_modules', array('id'=>$context->instanceid));
3765 $module = $DB->get_record('modules', array('id'=>$cm->module));
3767 $subcaps = array();
3768 $subpluginsfile = "$CFG->dirroot/mod/$module->name/db/subplugins.php";
3769 if (file_exists($subpluginsfile)) {
3770 $subplugins = array(); // should be redefined in the file
3771 include($subpluginsfile);
3772 if (!empty($subplugins)) {
3773 foreach (array_keys($subplugins) as $subplugintype) {
3774 foreach (array_keys(get_plugin_list($subplugintype)) as $subpluginname) {
3775 $subcaps = array_merge($subcaps, array_keys(load_capability_def($subplugintype.'_'.$subpluginname)));
3781 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
3782 if (file_exists($modfile)) {
3783 include_once($modfile);
3784 $modfunction = $module->name.'_get_extra_capabilities';
3785 if (function_exists($modfunction)) {
3786 $extracaps = $modfunction();
3789 if (empty($extracaps)) {
3790 $extracaps = array();
3793 $extracaps = array_merge($subcaps, $extracaps);
3795 // All modules allow viewhiddenactivities. This is so you can hide
3796 // the module then override to allow specific roles to see it.
3797 // The actual check is in course page so not module-specific
3798 $extracaps[]="moodle/course:viewhiddenactivities";
3799 list($extra, $params) = $DB->get_in_or_equal(
3800 $extracaps, SQL_PARAMS_NAMED, 'cap0');
3801 $extra = "OR name $extra";
3803 $SQL = "SELECT *
3804 FROM {capabilities}
3805 WHERE (contextlevel = ".CONTEXT_MODULE."
3806 AND component = :component)
3807 $extra";
3808 $params['component'] = "mod_$module->name";
3809 break;
3811 case CONTEXT_BLOCK: // block caps
3812 $bi = $DB->get_record('block_instances', array('id' => $context->instanceid));
3814 $extra = '';
3815 $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
3816 if ($extracaps) {
3817 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap');
3818 $extra = "OR name $extra";
3821 $SQL = "SELECT *
3822 FROM {capabilities}
3823 WHERE (contextlevel = ".CONTEXT_BLOCK."
3824 AND component = :component)
3825 $extra";
3826 $params['component'] = 'block_' . $bi->blockname;
3827 break;
3829 default:
3830 return false;
3833 if (!$records = $DB->get_records_sql($SQL.' '.$sort, $params)) {
3834 $records = array();
3837 return $records;
3842 * This function pulls out all the resolved capabilities (overrides and
3843 * defaults) of a role used in capability overrides in contexts at a given
3844 * context.
3846 * @param obj $context
3847 * @param int $roleid
3848 * @param string $cap capability, optional, defaults to ''
3849 * @return array of capabilities
3851 function role_context_capabilities($roleid, $context, $cap = '') {
3852 global $DB;
3854 $contexts = get_parent_contexts($context);
3855 $contexts[] = $context->id;
3856 $contexts = '('.implode(',', $contexts).')';
3858 $params = array($roleid);
3860 if ($cap) {
3861 $search = " AND rc.capability = ? ";
3862 $params[] = $cap;
3863 } else {
3864 $search = '';
3867 $sql = "SELECT rc.*
3868 FROM {role_capabilities} rc, {context} c
3869 WHERE rc.contextid in $contexts
3870 AND rc.roleid = ?
3871 AND rc.contextid = c.id $search
3872 ORDER BY c.contextlevel DESC, rc.capability DESC";
3874 $capabilities = array();
3876 if ($records = $DB->get_records_sql($sql, $params)) {
3877 // We are traversing via reverse order.
3878 foreach ($records as $record) {
3879 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3880 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
3881 $capabilities[$record->capability] = $record->permission;
3885 return $capabilities;
3889 * Recursive function which, given a context, find all parent context ids,
3890 * and return the array in reverse order, i.e. parent first, then grand
3891 * parent, etc.
3893 * @param object $context
3894 * @param bool $capability optional, defaults to false
3895 * @return array
3897 function get_parent_contexts($context, $includeself = false) {
3899 if ($context->path == '') {
3900 return array();
3903 $parentcontexts = substr($context->path, 1); // kill leading slash
3904 $parentcontexts = explode('/', $parentcontexts);
3905 if (!$includeself) {
3906 array_pop($parentcontexts); // and remove its own id
3909 return array_reverse($parentcontexts);
3913 * Return the id of the parent of this context, or false if there is no parent (only happens if this
3914 * is the site context.)
3916 * @param object $context
3917 * @return integer the id of the parent context.
3919 function get_parent_contextid($context) {
3920 $parentcontexts = get_parent_contexts($context);
3921 if (count($parentcontexts) == 0) {
3922 return false;
3924 return array_shift($parentcontexts);
3928 * Constructs array with contextids as first parameter and context paths,
3929 * in both cases bottom top including self.
3931 * @param object $context
3932 * @return array
3934 function get_context_info_list($context) {
3935 $contextids = explode('/', ltrim($context->path, '/'));
3936 $contextpaths = array();
3937 $contextids2 = $contextids;
3938 while ($contextids2) {
3939 $contextpaths[] = '/' . implode('/', $contextids2);
3940 array_pop($contextids2);
3942 return array($contextids, $contextpaths);
3946 * Find course context
3947 * @param object $context - course or lower context
3948 * @return object context of the enclosing course, throws exception when related course context can not be found
3950 function get_course_context($context) {
3951 if (empty($context->contextlevel)) {
3952 throw new coding_exception('Invalid context parameter.');
3954 } if ($context->contextlevel == CONTEXT_COURSE) {
3955 return $context;
3957 } else if ($context->contextlevel == CONTEXT_MODULE) {
3958 return get_context_instance_by_id(get_parent_contextid($context, MUST_EXIST));
3960 } else if ($context->contextlevel == CONTEXT_BLOCK) {
3961 $parentcontext = get_context_instance_by_id(get_parent_contextid($context, MUST_EXIST));
3962 if ($parentcontext->contextlevel == CONTEXT_COURSE) {
3963 return $parentcontext;
3964 } else if ($parentcontext->contextlevel == CONTEXT_MODULE) {
3965 return get_context_instance_by_id(get_parent_contextid($parentcontext, MUST_EXIST));
3966 } else {
3967 throw new coding_exception('Invalid level of block context parameter.');
3971 throw new coding_exception('Invalid context level of parameter.');
3975 * Check if context is the front page context or a context inside it
3977 * Returns true if this context is the front page context, or a context inside it,
3978 * otherwise false.
3980 * @param object $context a context object.
3981 * @return bool
3983 function is_inside_frontpage($context) {
3984 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
3985 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
3989 * Runs get_records select on context table and returns the result
3990 * Does get_records_select on the context table, and returns the results ordered
3991 * by contextlevel, and then the natural sort order within each level.
3992 * for the purpose of $select, you need to know that the context table has been
3993 * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
3995 * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
3996 * @param array $params any parameters required by $select.
3997 * @return array the requested context records.
3999 function get_sorted_contexts($select, $params = array()) {
4000 global $DB;
4001 if ($select) {
4002 $select = 'WHERE ' . $select;
4004 return $DB->get_records_sql("
4005 SELECT ctx.*
4006 FROM {context} ctx
4007 LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
4008 LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
4009 LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
4010 LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
4011 LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
4012 $select
4013 ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
4014 ", $params);
4018 * Recursive function which, given a context, find all its children context ids.
4020 * When called for a course context, it will return the modules and blocks
4021 * displayed in the course page.
4023 * For course category contexts it will return categories and courses. It will
4024 * NOT recurse into courses, nor return blocks on the category pages. If you
4025 * want to do that, call it on the returned courses.
4027 * If called on a course context it _will_ populate the cache with the appropriate
4028 * contexts ;-)
4030 * @param object $context.
4031 * @return array Array of child records
4033 function get_child_contexts($context) {
4035 global $DB, $ACCESSLIB_PRIVATE;
4037 // We *MUST* populate the context_cache as the callers
4038 // will probably ask for the full record anyway soon after
4039 // soon after calling us ;-)
4041 $array = array();
4042 $cache = $ACCESSLIB_PRIVATE->contexcache;
4044 switch ($context->contextlevel) {
4046 case CONTEXT_BLOCK:
4047 // No children.
4048 break;
4050 case CONTEXT_MODULE:
4051 // Find
4052 // - blocks under this context path.
4053 $sql = " SELECT ctx.*
4054 FROM {context} ctx
4055 WHERE ctx.path LIKE ?
4056 AND ctx.contextlevel = ".CONTEXT_BLOCK;
4057 $params = array("{$context->path}/%", $context->instanceid);
4058 $records = $DB->get_recordset_sql($sql, $params);
4059 foreach ($records as $rec) {
4060 $cache->add($rec);
4061 $array[$rec->id] = $rec;
4063 break;
4065 case CONTEXT_COURSE:
4066 // Find
4067 // - modules and blocks under this context path.
4068 $sql = " SELECT ctx.*
4069 FROM {context} ctx
4070 WHERE ctx.path LIKE ?
4071 AND ctx.contextlevel IN (".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
4072 $params = array("{$context->path}/%", $context->instanceid);
4073 $records = $DB->get_recordset_sql($sql, $params);
4074 foreach ($records as $rec) {
4075 $cache->add($rec);
4076 $array[$rec->id] = $rec;
4078 break;
4080 case CONTEXT_COURSECAT:
4081 // Find
4082 // - categories
4083 // - courses
4084 $sql = " SELECT ctx.*
4085 FROM {context} ctx
4086 WHERE ctx.path LIKE ?
4087 AND ctx.contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.")";
4088 $params = array("{$context->path}/%");
4089 $records = $DB->get_recordset_sql($sql, $params);
4090 foreach ($records as $rec) {
4091 $cache->add($rec);
4092 $array[$rec->id] = $rec;
4094 break;
4096 case CONTEXT_USER:
4097 // Find
4098 // - blocks under this context path.
4099 $sql = " SELECT ctx.*
4100 FROM {context} ctx
4101 WHERE ctx.path LIKE ?
4102 AND ctx.contextlevel = ".CONTEXT_BLOCK;
4103 $params = array("{$context->path}/%", $context->instanceid);
4104 $records = $DB->get_recordset_sql($sql, $params);
4105 foreach ($records as $rec) {
4106 $cache->add($rec);
4107 $array[$rec->id] = $rec;
4109 break;
4111 case CONTEXT_SYSTEM:
4112 // Just get all the contexts except for CONTEXT_SYSTEM level
4113 // and hope we don't OOM in the process - don't cache
4114 $sql = "SELECT c.*
4115 FROM {context} c
4116 WHERE contextlevel != ".CONTEXT_SYSTEM;
4118 $records = $DB->get_records_sql($sql);
4119 foreach ($records as $rec) {
4120 $array[$rec->id] = $rec;
4122 break;
4124 default:
4125 print_error('unknowcontext', '', '', $context->contextlevel);
4126 return false;
4128 return $array;
4133 * Gets a string for sql calls, searching for stuff in this context or above
4135 * @param object $context
4136 * @return string
4138 function get_related_contexts_string($context) {
4139 if ($parents = get_parent_contexts($context)) {
4140 return (' IN ('.$context->id.','.implode(',', $parents).')');
4141 } else {
4142 return (' ='.$context->id);
4147 * Returns capability information (cached)
4149 * @param string $capabilityname
4150 * @return object or null if capability not found
4152 function get_capability_info($capabilityname) {
4153 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
4155 // TODO: cache this in shared memory if available, use new $CFG->roledefrev for version check
4157 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
4158 $ACCESSLIB_PRIVATE->capabilities = array();
4159 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
4160 foreach ($caps as $cap) {
4161 $capname = $cap->name;
4162 unset($cap->id);
4163 unset($cap->name);
4164 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
4168 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
4172 * Returns the human-readable, translated version of the capability.
4173 * Basically a big switch statement.
4175 * @param string $capabilityname e.g. mod/choice:readresponses
4176 * @return string
4178 function get_capability_string($capabilityname) {
4180 // Typical capability name is 'plugintype/pluginname:capabilityname'
4181 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
4183 if ($type === 'moodle') {
4184 $component = 'core_role';
4185 } else if ($type === 'quizreport') {
4186 //ugly hack!!
4187 $component = 'quiz_'.$name;
4188 } else {
4189 $component = $type.'_'.$name;
4192 $stringname = $name.':'.$capname;
4194 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
4195 return get_string($stringname, $component);
4198 $dir = get_component_directory($component);
4199 if (!file_exists($dir)) {
4200 // plugin broken or does not exist, do not bother with printing of debug message
4201 return $capabilityname.' ???';
4204 // something is wrong in plugin, better print debug
4205 return get_string($stringname, $component);
4210 * This gets the mod/block/course/core etc strings.
4212 * @param string $component
4213 * @param int $contextlevel
4214 * @return string|bool String is success, false if failed
4216 function get_component_string($component, $contextlevel) {
4218 if ($component === 'moodle' or $component === 'core') {
4219 switch ($contextlevel) {
4220 case CONTEXT_SYSTEM: return get_string('coresystem');
4221 case CONTEXT_USER: return get_string('users');
4222 case CONTEXT_COURSECAT: return get_string('categories');
4223 case CONTEXT_COURSE: return get_string('course');
4224 case CONTEXT_MODULE: return get_string('activities');
4225 case CONTEXT_BLOCK: return get_string('block');
4226 default: print_error('unknowncontext');
4230 list($type, $name) = normalize_component($component);
4231 $dir = get_plugin_directory($type, $name);
4232 if (!file_exists($dir)) {
4233 // plugin not installed, bad luck, there is no way to find the name
4234 return $component.' ???';
4237 switch ($type) {
4238 // TODO this is really hacky
4239 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
4240 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
4241 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
4242 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
4243 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
4244 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
4245 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
4246 case 'mod':
4247 if (get_string_manager()->string_exists('pluginname', $component)) {
4248 return get_string('activity').': '.get_string('pluginname', $component);
4249 } else {
4250 return get_string('activity').': '.get_string('modulename', $component);
4252 default: return get_string('pluginname', $component);
4257 * Gets the list of roles assigned to this context and up (parents)
4258 * from the list of roles that are visible on user profile page
4259 * and participants page.
4261 * @param object $context
4262 * @return array
4264 function get_profile_roles($context) {
4265 global $CFG, $DB;
4267 if (empty($CFG->profileroles)) {
4268 return array();
4271 $allowed = explode(',', $CFG->profileroles);
4272 list($rallowed, $params) = $DB->get_in_or_equal($allowed, SQL_PARAMS_NAMED);
4274 $contextlist = get_related_contexts_string($context);
4276 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
4277 FROM {role_assignments} ra, {role} r
4278 WHERE r.id = ra.roleid
4279 AND ra.contextid $contextlist
4280 AND r.id $rallowed
4281 ORDER BY r.sortorder ASC";
4283 return $DB->get_records_sql($sql, $params);
4287 * Gets the list of roles assigned to this context and up (parents)
4289 * @param object $context
4290 * @return array
4292 function get_roles_used_in_context($context) {
4293 global $DB;
4295 $contextlist = get_related_contexts_string($context);
4297 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
4298 FROM {role_assignments} ra, {role} r
4299 WHERE r.id = ra.roleid
4300 AND ra.contextid $contextlist
4301 ORDER BY r.sortorder ASC";
4303 return $DB->get_records_sql($sql);
4307 * This function is used to print roles column in user profile page.
4308 * It is using the CFG->profileroles to limit the list to only interesting roles.
4309 * (The permission tab has full details of user role assignments.)
4311 * @param int $userid
4312 * @param int $courseid
4313 * @return string
4315 function get_user_roles_in_course($userid, $courseid) {
4316 global $CFG, $DB,$USER;
4318 if (empty($CFG->profileroles)) {
4319 return '';
4322 if ($courseid == SITEID) {
4323 $context = get_context_instance(CONTEXT_SYSTEM);
4324 } else {
4325 $context = get_context_instance(CONTEXT_COURSE, $courseid);
4328 if (empty($CFG->profileroles)) {
4329 return array();
4332 $allowed = explode(',', $CFG->profileroles);
4333 list($rallowed, $params) = $DB->get_in_or_equal($allowed, SQL_PARAMS_NAMED);
4335 $contextlist = get_related_contexts_string($context);
4337 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
4338 FROM {role_assignments} ra, {role} r
4339 WHERE r.id = ra.roleid
4340 AND ra.contextid $contextlist
4341 AND r.id $rallowed
4342 AND ra.userid = :userid
4343 ORDER BY r.sortorder ASC";
4344 $params['userid'] = $userid;
4346 $rolestring = '';
4348 if ($roles = $DB->get_records_sql($sql, $params)) {
4349 foreach ($roles as $userrole) {
4350 $rolenames[$userrole->id] = $userrole->name;
4353 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
4355 foreach ($rolenames as $roleid => $rolename) {
4356 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
4358 $rolestring = implode(',', $rolenames);
4361 return $rolestring;
4365 * Checks if a user can assign users to a particular role in this context
4367 * @param object $context
4368 * @param int $targetroleid - the id of the role you want to assign users to
4369 * @return boolean
4371 function user_can_assign($context, $targetroleid) {
4372 global $DB;
4374 // first check if user has override capability
4375 // if not return false;
4376 if (!has_capability('moodle/role:assign', $context)) {
4377 return false;
4379 // pull out all active roles of this user from this context(or above)
4380 if ($userroles = get_user_roles($context)) {
4381 foreach ($userroles as $userrole) {
4382 // if any in the role_allow_override table, then it's ok
4383 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
4384 return true;
4389 return false;
4393 * Returns all site roles in correct sort order.
4395 * @return array
4397 function get_all_roles() {
4398 global $DB;
4399 return $DB->get_records('role', null, 'sortorder ASC');
4403 * Returns roles of a specified archetype
4404 * @param string $archetype
4405 * @return array of full role records
4407 function get_archetype_roles($archetype) {
4408 global $DB;
4409 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
4413 * Gets all the user roles assigned in this context, or higher contexts
4414 * this is mainly used when checking if a user can assign a role, or overriding a role
4415 * i.e. we need to know what this user holds, in order to verify against allow_assign and
4416 * allow_override tables
4418 * @param object $context
4419 * @param int $userid
4420 * @param bool $checkparentcontexts defaults to true
4421 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
4422 * @return array
4424 function get_user_roles($context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
4425 global $USER, $DB;
4427 if (empty($userid)) {
4428 if (empty($USER->id)) {
4429 return array();
4431 $userid = $USER->id;
4434 if ($checkparentcontexts) {
4435 $contextids = get_parent_contexts($context);
4436 } else {
4437 $contextids = array();
4439 $contextids[] = $context->id;
4441 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
4443 array_unshift($params, $userid);
4445 $sql = "SELECT ra.*, r.name, r.shortname
4446 FROM {role_assignments} ra, {role} r, {context} c
4447 WHERE ra.userid = ?
4448 AND ra.roleid = r.id
4449 AND ra.contextid = c.id
4450 AND ra.contextid $contextids
4451 ORDER BY $order";
4453 return $DB->get_records_sql($sql ,$params);
4457 * Creates a record in the role_allow_override table
4459 * @param int $sroleid source roleid
4460 * @param int $troleid target roleid
4461 * @return void
4463 function allow_override($sroleid, $troleid) {
4464 global $DB;
4466 $record = new stdClass();
4467 $record->roleid = $sroleid;
4468 $record->allowoverride = $troleid;
4469 $DB->insert_record('role_allow_override', $record);
4473 * Creates a record in the role_allow_assign table
4475 * @param int $sroleid source roleid
4476 * @param int $troleid target roleid
4477 * @return void
4479 function allow_assign($fromroleid, $targetroleid) {
4480 global $DB;
4482 $record = new stdClass();
4483 $record->roleid = $fromroleid;
4484 $record->allowassign = $targetroleid;
4485 $DB->insert_record('role_allow_assign', $record);
4489 * Creates a record in the role_allow_switch table
4491 * @param int $sroleid source roleid
4492 * @param int $troleid target roleid
4493 * @return void
4495 function allow_switch($fromroleid, $targetroleid) {
4496 global $DB;
4498 $record = new stdClass();
4499 $record->roleid = $fromroleid;
4500 $record->allowswitch = $targetroleid;
4501 $DB->insert_record('role_allow_switch', $record);
4505 * Gets a list of roles that this user can assign in this context
4507 * @param object $context the context.
4508 * @param int $rolenamedisplay the type of role name to display. One of the
4509 * ROLENAME_X constants. Default ROLENAME_ALIAS.
4510 * @param bool $withusercounts if true, count the number of users with each role.
4511 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
4512 * @return array if $withusercounts is false, then an array $roleid => $rolename.
4513 * if $withusercounts is true, returns a list of three arrays,
4514 * $rolenames, $rolecounts, and $nameswithcounts.
4516 function get_assignable_roles($context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
4517 global $USER, $DB;
4519 // make sure there is a real user specified
4520 if ($user === null) {
4521 $userid = !empty($USER->id) ? $USER->id : 0;
4522 } else {
4523 $userid = !empty($user->id) ? $user->id : $user;
4526 if (!has_capability('moodle/role:assign', $context, $userid)) {
4527 if ($withusercounts) {
4528 return array(array(), array(), array());
4529 } else {
4530 return array();
4534 $parents = get_parent_contexts($context, true);
4535 $contexts = implode(',' , $parents);
4537 $params = array();
4538 $extrafields = '';
4539 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT or $rolenamedisplay == ROLENAME_SHORT) {
4540 $extrafields .= ', r.shortname';
4543 if ($withusercounts) {
4544 $extrafields = ', (SELECT count(u.id)
4545 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
4546 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
4547 ) AS usercount';
4548 $params['conid'] = $context->id;
4551 if (is_siteadmin($userid)) {
4552 // show all roles allowed in this context to admins
4553 $assignrestriction = "";
4554 } else {
4555 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
4556 FROM {role_allow_assign} raa
4557 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
4558 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
4559 ) ar ON ar.id = r.id";
4560 $params['userid'] = $userid;
4562 $params['contextlevel'] = $context->contextlevel;
4563 $sql = "SELECT r.id, r.name $extrafields
4564 FROM {role} r
4565 $assignrestriction
4566 JOIN {role_context_levels} rcl ON r.id = rcl.roleid
4567 WHERE rcl.contextlevel = :contextlevel
4568 ORDER BY r.sortorder ASC";
4569 $roles = $DB->get_records_sql($sql, $params);
4571 $rolenames = array();
4572 foreach ($roles as $role) {
4573 if ($rolenamedisplay == ROLENAME_SHORT) {
4574 $rolenames[$role->id] = $role->shortname;
4575 continue;
4577 $rolenames[$role->id] = $role->name;
4578 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4579 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
4582 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT and $rolenamedisplay != ROLENAME_SHORT) {
4583 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
4586 if (!$withusercounts) {
4587 return $rolenames;
4590 $rolecounts = array();
4591 $nameswithcounts = array();
4592 foreach ($roles as $role) {
4593 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
4594 $rolecounts[$role->id] = $roles[$role->id]->usercount;
4596 return array($rolenames, $rolecounts, $nameswithcounts);
4600 * Gets a list of roles that this user can switch to in a context
4602 * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
4603 * This function just process the contents of the role_allow_switch table. You also need to
4604 * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
4606 * @param object $context a context.
4607 * @return array an array $roleid => $rolename.
4609 function get_switchable_roles($context) {
4610 global $USER, $DB;
4612 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
4614 $params = array();
4615 $extrajoins = '';
4616 $extrawhere = '';
4617 if (!is_siteadmin()) {
4618 // Admins are allowed to switch to any role with.
4619 // Others are subject to the additional constraint that the switch-to role must be allowed by
4620 // 'role_allow_switch' for some role they have assigned in this context or any parent.
4621 $parents = get_parent_contexts($context);
4622 $parents[] = $context->id;
4623 $contexts = implode(',' , $parents);
4625 $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
4626 JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
4627 $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
4628 $params['userid'] = $USER->id;
4631 $query = "
4632 SELECT r.id, r.name
4633 FROM (SELECT DISTINCT rc.roleid
4634 FROM {role_capabilities} rc
4635 $extrajoins
4636 $extrawhere) idlist
4637 JOIN {role} r ON r.id = idlist.roleid
4638 ORDER BY r.sortorder";
4640 $rolenames = $DB->get_records_sql_menu($query, $params);
4641 return role_fix_names($rolenames, $context, ROLENAME_ALIAS);
4645 * Gets a list of roles that this user can override in this context.
4647 * @param object $context the context.
4648 * @param int $rolenamedisplay the type of role name to display. One of the
4649 * ROLENAME_X constants. Default ROLENAME_ALIAS.
4650 * @param bool $withcounts if true, count the number of overrides that are set for each role.
4651 * @return array if $withcounts is false, then an array $roleid => $rolename.
4652 * if $withusercounts is true, returns a list of three arrays,
4653 * $rolenames, $rolecounts, and $nameswithcounts.
4655 function get_overridable_roles($context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
4656 global $USER, $DB;
4658 if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
4659 if ($withcounts) {
4660 return array(array(), array(), array());
4661 } else {
4662 return array();
4666 $parents = get_parent_contexts($context);
4667 $parents[] = $context->id;
4668 $contexts = implode(',' , $parents);
4670 $params = array();
4671 $extrafields = '';
4672 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4673 $extrafields .= ', ro.shortname';
4676 $params['userid'] = $USER->id;
4677 if ($withcounts) {
4678 $extrafields = ', (SELECT count(rc.id) FROM {role_capabilities} rc
4679 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
4680 $params['conid'] = $context->id;
4683 if (is_siteadmin()) {
4684 // show all roles to admins
4685 $roles = $DB->get_records_sql("
4686 SELECT ro.id, ro.name$extrafields
4687 FROM {role} ro
4688 ORDER BY ro.sortorder ASC", $params);
4690 } else {
4691 $roles = $DB->get_records_sql("
4692 SELECT ro.id, ro.name$extrafields
4693 FROM {role} ro
4694 JOIN (SELECT DISTINCT r.id
4695 FROM {role} r
4696 JOIN {role_allow_override} rao ON r.id = rao.allowoverride
4697 JOIN {role_assignments} ra ON rao.roleid = ra.roleid
4698 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
4699 ) inline_view ON ro.id = inline_view.id
4700 ORDER BY ro.sortorder ASC", $params);
4703 $rolenames = array();
4704 foreach ($roles as $role) {
4705 $rolenames[$role->id] = $role->name;
4706 if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
4707 $rolenames[$role->id] .= ' (' . $role->shortname . ')';
4710 if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT) {
4711 $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
4714 if (!$withcounts) {
4715 return $rolenames;
4718 $rolecounts = array();
4719 $nameswithcounts = array();
4720 foreach ($roles as $role) {
4721 $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
4722 $rolecounts[$role->id] = $roles[$role->id]->overridecount;
4724 return array($rolenames, $rolecounts, $nameswithcounts);
4728 * Create a role menu suitable for default role selection in enrol plugins.
4729 * @param object $context
4730 * @param int $addroleid current or default role - always added to list
4731 * @return array roleid=>localised role name
4733 function get_default_enrol_roles($context, $addroleid = null) {
4734 global $DB;
4736 $params = array('contextlevel'=>CONTEXT_COURSE);
4737 if ($addroleid) {
4738 $addrole = "OR r.id = :addroleid";
4739 $params['addroleid'] = $addroleid;
4740 } else {
4741 $addrole = "";
4743 $sql = "SELECT r.id, r.name
4744 FROM {role} r
4745 LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
4746 WHERE rcl.id IS NOT NULL $addrole
4747 ORDER BY sortorder DESC";
4749 $roles = $DB->get_records_sql_menu($sql, $params);
4750 $roles = role_fix_names($roles, $context, ROLENAME_BOTH);
4752 return $roles;
4756 * @param integer $roleid the id of a role.
4757 * @return array list of the context levels at which this role may be assigned.
4759 function get_role_contextlevels($roleid) {
4760 global $DB;
4761 return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
4762 'contextlevel', 'id,contextlevel');
4766 * @param integer $contextlevel a contextlevel.
4767 * @return array list of role ids that are assignable at this context level.
4769 function get_roles_for_contextlevels($contextlevel) {
4770 global $DB;
4771 return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
4772 '', 'id,roleid');
4776 * @param string $rolearchetype one of the role archetypes - that is, one of the keys
4777 * from the array returned by get_role_archetypes();
4778 * @return array list of the context levels at which this type of role may be assigned by default.
4780 function get_default_contextlevels($rolearchetype) {
4781 static $defaults = array(
4782 'manager' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
4783 'coursecreator' => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
4784 'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
4785 'teacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
4786 'student' => array(CONTEXT_COURSE, CONTEXT_MODULE),
4787 'guest' => array(),
4788 'user' => array(),
4789 'frontpage' => array());
4791 if (isset($defaults[$rolearchetype])) {
4792 return $defaults[$rolearchetype];
4793 } else {
4794 return array();
4799 * Set the context levels at which a particular role can be assigned.
4800 * Throws exceptions in case of error.
4802 * @param integer $roleid the id of a role.
4803 * @param array $contextlevels the context levels at which this role should be assignable,
4804 * duplicate levels are removed.
4805 * @return void
4807 function set_role_contextlevels($roleid, array $contextlevels) {
4808 global $DB;
4809 $DB->delete_records('role_context_levels', array('roleid' => $roleid));
4810 $rcl = new stdClass();
4811 $rcl->roleid = $roleid;
4812 $contextlevels = array_unique($contextlevels);
4813 foreach ($contextlevels as $level) {
4814 $rcl->contextlevel = $level;
4815 $DB->insert_record('role_context_levels', $rcl, false, true);
4820 * Who has this capability in this context?
4822 * This can be a very expensive call - use sparingly and keep
4823 * the results if you are going to need them again soon.
4825 * Note if $fields is empty this function attempts to get u.*
4826 * which can get rather large - and has a serious perf impact
4827 * on some DBs.
4829 * @param object $context
4830 * @param string|array $capability - capability name(s)
4831 * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
4832 * @param string $sort - the sort order. Default is lastaccess time.
4833 * @param mixed $limitfrom - number of records to skip (offset)
4834 * @param mixed $limitnum - number of records to fetch
4835 * @param string|array $groups - single group or array of groups - only return
4836 * users who are in one of these group(s).
4837 * @param string|array $exceptions - list of users to exclude, comma separated or array
4838 * @param bool $doanything_ignored not used any more, admin accounts are never returned
4839 * @param bool $view_ignored - use get_enrolled_sql() instead
4840 * @param bool $useviewallgroups if $groups is set the return users who
4841 * have capability both $capability and moodle/site:accessallgroups
4842 * in this context, as well as users who have $capability and who are
4843 * in $groups.
4844 * @return mixed
4846 function get_users_by_capability($context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
4847 $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
4848 global $CFG, $DB;
4850 if (empty($context->id)) {
4851 throw new coding_exception('Invalid context specified');
4854 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
4855 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
4857 $ctxids = trim($context->path, '/');
4858 $ctxids = str_replace('/', ',', $ctxids);
4860 // Context is the frontpage
4861 $iscoursepage = false; // coursepage other than fp
4862 $isfrontpage = false;
4863 if ($context->contextlevel == CONTEXT_COURSE) {
4864 if ($context->instanceid == SITEID) {
4865 $isfrontpage = true;
4866 } else {
4867 $iscoursepage = true;
4870 $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
4872 $caps = (array)$capability;
4874 // construct list of context paths bottom-->top
4875 list($contextids, $paths) = get_context_info_list($context);
4877 // we need to find out all roles that have these capabilities either in definition or in overrides
4878 $defs = array();
4879 list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
4880 list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
4881 $params = array_merge($params, $params2);
4882 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
4883 FROM {role_capabilities} rc
4884 JOIN {context} ctx on rc.contextid = ctx.id
4885 WHERE rc.contextid $incontexts AND rc.capability $incaps";
4887 $rcs = $DB->get_records_sql($sql, $params);
4888 foreach ($rcs as $rc) {
4889 $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
4892 // go through the permissions bottom-->top direction to evaluate the current permission,
4893 // first one wins (prohibit is an exception that always wins)
4894 $access = array();
4895 foreach ($caps as $cap) {
4896 foreach ($paths as $path) {
4897 if (empty($defs[$cap][$path])) {
4898 continue;
4900 foreach($defs[$cap][$path] as $roleid => $perm) {
4901 if ($perm == CAP_PROHIBIT) {
4902 $access[$cap][$roleid] = CAP_PROHIBIT;
4903 continue;
4905 if (!isset($access[$cap][$roleid])) {
4906 $access[$cap][$roleid] = (int)$perm;
4912 // make lists of roles that are needed and prohibited in this context
4913 $needed = array(); // one of these is enough
4914 $prohibited = array(); // must not have any of these
4915 foreach ($caps as $cap) {
4916 if (empty($access[$cap])) {
4917 continue;
4919 foreach ($access[$cap] as $roleid => $perm) {
4920 if ($perm == CAP_PROHIBIT) {
4921 unset($needed[$cap][$roleid]);
4922 $prohibited[$cap][$roleid] = true;
4923 } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
4924 $needed[$cap][$roleid] = true;
4927 if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
4928 // easy, nobody has the permission
4929 unset($needed[$cap]);
4930 unset($prohibited[$cap]);
4931 } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
4932 // everybody is disqualified on the frontapge
4933 unset($needed[$cap]);
4934 unset($prohibited[$cap]);
4936 if (empty($prohibited[$cap])) {
4937 unset($prohibited[$cap]);
4941 if (empty($needed)) {
4942 // there can not be anybody if no roles match this request
4943 return array();
4946 if (empty($prohibited)) {
4947 // we can compact the needed roles
4948 $n = array();
4949 foreach ($needed as $cap) {
4950 foreach ($cap as $roleid=>$unused) {
4951 $n[$roleid] = true;
4954 $needed = array('any'=>$n);
4955 unset($n);
4958 /// ***** Set up default fields ******
4959 if (empty($fields)) {
4960 if ($iscoursepage) {
4961 $fields = 'u.*, ul.timeaccess AS lastaccess';
4962 } else {
4963 $fields = 'u.*';
4965 } else {
4966 if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
4967 debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
4971 /// Set up default sort
4972 if (empty($sort)) { // default to course lastaccess or just lastaccess
4973 if ($iscoursepage) {
4974 $sort = 'ul.timeaccess';
4975 } else {
4976 $sort = 'u.lastaccess';
4979 $sortby = "ORDER BY $sort";
4981 // Prepare query clauses
4982 $wherecond = array();
4983 $params = array();
4984 $joins = array();
4986 // User lastaccess JOIN
4987 if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
4988 // user_lastaccess is not required MDL-13810
4989 } else {
4990 if ($iscoursepage) {
4991 $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
4992 } else {
4993 throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
4997 /// We never return deleted users or guest account.
4998 $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
4999 $params['guestid'] = $CFG->siteguest;
5001 /// Groups
5002 if ($groups) {
5003 $groups = (array)$groups;
5004 list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
5005 $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
5006 $params = array_merge($params, $grpparams);
5008 if ($useviewallgroups) {
5009 $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
5010 $wherecond[] = "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
5011 } else {
5012 $wherecond[] = "($grouptest)";
5016 /// User exceptions
5017 if (!empty($exceptions)) {
5018 $exceptions = (array)$exceptions;
5019 list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
5020 $params = array_merge($params, $exparams);
5021 $wherecond[] = "u.id $exsql";
5024 // now add the needed and prohibited roles conditions as joins
5025 if (!empty($needed['any'])) {
5026 // simple case - there are no prohibits involved
5027 if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
5028 // everybody
5029 } else {
5030 $joins[] = "JOIN (SELECT DISTINCT userid
5031 FROM {role_assignments}
5032 WHERE contextid IN ($ctxids)
5033 AND roleid IN (".implode(',', array_keys($needed['any'])) .")
5034 ) ra ON ra.userid = u.id";
5036 } else {
5037 $unions = array();
5038 $everybody = false;
5039 foreach ($needed as $cap=>$unused) {
5040 if (empty($prohibited[$cap])) {
5041 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
5042 $everybody = true;
5043 break;
5044 } else {
5045 $unions[] = "SELECT userid
5046 FROM {role_assignments}
5047 WHERE contextid IN ($ctxids)
5048 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
5050 } else {
5051 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
5052 // nobody can have this cap because it is prevented in default roles
5053 continue;
5055 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
5056 // everybody except the prohibitted - hiding does not matter
5057 $unions[] = "SELECT id AS userid
5058 FROM {user}
5059 WHERE id NOT IN (SELECT userid
5060 FROM {role_assignments}
5061 WHERE contextid IN ($ctxids)
5062 AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
5064 } else {
5065 $unions[] = "SELECT userid
5066 FROM {role_assignments}
5067 WHERE contextid IN ($ctxids)
5068 AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
5069 AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
5073 if (!$everybody) {
5074 if ($unions) {
5075 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
5076 } else {
5077 // only prohibits found - nobody can be matched
5078 $wherecond[] = "1 = 2";
5083 // Collect WHERE conditions and needed joins
5084 $where = implode(' AND ', $wherecond);
5085 if ($where !== '') {
5086 $where = 'WHERE ' . $where;
5088 $joins = implode("\n", $joins);
5090 /// Ok, let's get the users!
5091 $sql = "SELECT $fields
5092 FROM {user} u
5093 $joins
5094 $where
5095 ORDER BY $sort";
5097 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
5101 * Re-sort a users array based on a sorting policy
5103 * Will re-sort a $users results array (from get_users_by_capability(), usually)
5104 * based on a sorting policy. This is to support the odd practice of
5105 * sorting teachers by 'authority', where authority was "lowest id of the role
5106 * assignment".
5108 * Will execute 1 database query. Only suitable for small numbers of users, as it
5109 * uses an u.id IN() clause.
5111 * Notes about the sorting criteria.
5113 * As a default, we cannot rely on role.sortorder because then
5114 * admins/coursecreators will always win. That is why the sane
5115 * rule "is locality matters most", with sortorder as 2nd
5116 * consideration.
5118 * If you want role.sortorder, use the 'sortorder' policy, and
5119 * name explicitly what roles you want to cover. It's probably
5120 * a good idea to see what roles have the capabilities you want
5121 * (array_diff() them against roiles that have 'can-do-anything'
5122 * to weed out admin-ish roles. Or fetch a list of roles from
5123 * variables like $CFG->coursecontact .
5125 * @param array $users Users array, keyed on userid
5126 * @param object $context
5127 * @param array $roles ids of the roles to include, optional
5128 * @param string $policy defaults to locality, more about
5129 * @return array sorted copy of the array
5131 function sort_by_roleassignment_authority($users, $context, $roles = array(), $sortpolicy = 'locality') {
5132 global $DB;
5134 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
5135 $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
5136 if (empty($roles)) {
5137 $roleswhere = '';
5138 } else {
5139 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
5142 $sql = "SELECT ra.userid
5143 FROM {role_assignments} ra
5144 JOIN {role} r
5145 ON ra.roleid=r.id
5146 JOIN {context} ctx
5147 ON ra.contextid=ctx.id
5148 WHERE $userswhere
5149 $contextwhere
5150 $roleswhere";
5152 // Default 'locality' policy -- read PHPDoc notes
5153 // about sort policies...
5154 $orderby = 'ORDER BY '
5155 .'ctx.depth DESC, ' /* locality wins */
5156 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
5157 .'ra.id'; /* role assignment order tie-breaker */
5158 if ($sortpolicy === 'sortorder') {
5159 $orderby = 'ORDER BY '
5160 .'r.sortorder ASC, ' /* rolesorting 2nd criteria */
5161 .'ra.id'; /* role assignment order tie-breaker */
5164 $sortedids = $DB->get_fieldset_sql($sql . $orderby);
5165 $sortedusers = array();
5166 $seen = array();
5168 foreach ($sortedids as $id) {
5169 // Avoid duplicates
5170 if (isset($seen[$id])) {
5171 continue;
5173 $seen[$id] = true;
5175 // assign
5176 $sortedusers[$id] = $users[$id];
5178 return $sortedusers;
5182 * Gets all the users assigned this role in this context or higher
5184 * @param int $roleid (can also be an array of ints!)
5185 * @param stdClass $context
5186 * @param bool $parent if true, get list of users assigned in higher context too
5187 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
5188 * @param string $sort sort from user (u.) , role assignment (ra) or role (r.)
5189 * @param bool $gethidden_ignored use enrolments instead
5190 * @param string $group defaults to ''
5191 * @param mixed $limitfrom defaults to ''
5192 * @param mixed $limitnum defaults to ''
5193 * @param string $extrawheretest defaults to ''
5194 * @param string|array $whereparams defaults to ''
5195 * @return array
5197 function get_role_users($roleid, $context, $parent = false, $fields = '',
5198 $sort = 'u.lastname, u.firstname', $gethidden_ignored = null, $group = '',
5199 $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereparams = array()) {
5200 global $DB;
5202 if (empty($fields)) {
5203 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
5204 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
5205 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
5206 'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder';
5209 $parentcontexts = '';
5210 if ($parent) {
5211 $parentcontexts = substr($context->path, 1); // kill leading slash
5212 $parentcontexts = str_replace('/', ',', $parentcontexts);
5213 if ($parentcontexts !== '') {
5214 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
5218 if ($roleid) {
5219 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
5220 $roleselect = "AND ra.roleid $rids";
5221 } else {
5222 $params = array();
5223 $roleselect = '';
5226 if ($group) {
5227 $groupjoin = "JOIN {groups_members} gm ON gm.userid = u.id";
5228 $groupselect = " AND gm.groupid = ? ";
5229 $params[] = $group;
5230 } else {
5231 $groupjoin = '';
5232 $groupselect = '';
5235 array_unshift($params, $context->id);
5237 if ($extrawheretest) {
5238 $extrawheretest = ' AND ' . $extrawheretest;
5239 $params = array_merge($params, $whereparams);
5242 $sql = "SELECT DISTINCT $fields, ra.roleid
5243 FROM {role_assignments} ra
5244 JOIN {user} u ON u.id = ra.userid
5245 JOIN {role} r ON ra.roleid = r.id
5246 $groupjoin
5247 WHERE (ra.contextid = ? $parentcontexts)
5248 $roleselect
5249 $groupselect
5250 $extrawheretest
5251 ORDER BY $sort"; // join now so that we can just use fullname() later
5253 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
5257 * Counts all the users assigned this role in this context or higher
5259 * @param mixed $roleid either int or an array of ints
5260 * @param object $context
5261 * @param bool $parent if true, get list of users assigned in higher context too
5262 * @return int Returns the result count
5264 function count_role_users($roleid, $context, $parent = false) {
5265 global $DB;
5267 if ($parent) {
5268 if ($contexts = get_parent_contexts($context)) {
5269 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
5270 } else {
5271 $parentcontexts = '';
5273 } else {
5274 $parentcontexts = '';
5277 if ($roleid) {
5278 list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_QM);
5279 $roleselect = "AND r.roleid $rids";
5280 } else {
5281 $params = array();
5282 $roleselect = '';
5285 array_unshift($params, $context->id);
5287 $sql = "SELECT count(u.id)
5288 FROM {role_assignments} r
5289 JOIN {user} u ON u.id = r.userid
5290 WHERE (r.contextid = ? $parentcontexts)
5291 $roleselect
5292 AND u.deleted = 0";
5294 return $DB->count_records_sql($sql, $params);
5298 * This function gets the list of courses that this user has a particular capability in.
5299 * It is still not very efficient.
5301 * @param string $capability Capability in question
5302 * @param int $userid User ID or null for current user
5303 * @param bool $doanything True if 'doanything' is permitted (default)
5304 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
5305 * otherwise use a comma-separated list of the fields you require, not including id
5306 * @param string $orderby If set, use a comma-separated list of fields from course
5307 * table with sql modifiers (DESC) if needed
5308 * @return array Array of courses, may have zero entries. Or false if query failed.
5310 function get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '', $orderby = '') {
5311 global $DB;
5313 // Convert fields list and ordering
5314 $fieldlist = '';
5315 if ($fieldsexceptid) {
5316 $fields = explode(',', $fieldsexceptid);
5317 foreach($fields as $field) {
5318 $fieldlist .= ',c.'.$field;
5321 if ($orderby) {
5322 $fields = explode(',', $orderby);
5323 $orderby = '';
5324 foreach($fields as $field) {
5325 if ($orderby) {
5326 $orderby .= ',';
5328 $orderby .= 'c.'.$field;
5330 $orderby = 'ORDER BY '.$orderby;
5333 // Obtain a list of everything relevant about all courses including context.
5334 // Note the result can be used directly as a context (we are going to), the course
5335 // fields are just appended.
5337 $courses = array();
5338 $rs = $DB->get_recordset_sql("SELECT x.*, c.id AS courseid $fieldlist
5339 FROM {course} c
5340 INNER JOIN {context} x
5341 ON (c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE.")
5342 $orderby");
5343 // Check capability for each course in turn
5344 foreach ($rs as $coursecontext) {
5345 if (has_capability($capability, $coursecontext, $userid, $doanything)) {
5346 // We've got the capability. Make the record look like a course record
5347 // and store it
5348 $coursecontext->id = $coursecontext->courseid;
5349 unset($coursecontext->courseid);
5350 unset($coursecontext->contextlevel);
5351 unset($coursecontext->instanceid);
5352 $courses[] = $coursecontext;
5355 $rs->close();
5356 return empty($courses) ? false : $courses;
5360 * This function finds the roles assigned directly to this context only
5361 * i.e. no parents role
5363 * @param object $context
5364 * @return array
5366 function get_roles_on_exact_context($context) {
5367 global $DB;
5369 return $DB->get_records_sql("SELECT r.*
5370 FROM {role_assignments} ra, {role} r
5371 WHERE ra.roleid = r.id AND ra.contextid = ?",
5372 array($context->id));
5377 * Switches the current user to another role for the current session and only
5378 * in the given context.
5380 * The caller *must* check
5381 * - that this op is allowed
5382 * - that the requested role can be switched to in this context (use get_switchable_roles)
5383 * - that the requested role is NOT $CFG->defaultuserroleid
5385 * To "unswitch" pass 0 as the roleid.
5387 * This function *will* modify $USER->access - beware
5389 * @param integer $roleid the role to switch to.
5390 * @param object $context the context in which to perform the switch.
5391 * @return bool success or failure.
5393 function role_switch($roleid, $context) {
5394 global $USER;
5397 // Plan of action
5399 // - Add the ghost RA to $USER->access
5400 // as $USER->access['rsw'][$path] = $roleid
5402 // - Make sure $USER->access['rdef'] has the roledefs
5403 // it needs to honour the switcherole
5405 // Roledefs will get loaded "deep" here - down to the last child
5406 // context. Note that
5408 // - When visiting subcontexts, our selective accessdata loading
5409 // will still work fine - though those ra/rdefs will be ignored
5410 // appropriately while the switch is in place
5412 // - If a switcherole happens at a category with tons of courses
5413 // (that have many overrides for switched-to role), the session
5414 // will get... quite large. Sometimes you just can't win.
5416 // To un-switch just unset($USER->access['rsw'][$path])
5418 // Note: it is not possible to switch to roles that do not have course:view
5420 // Add the switch RA
5421 if (!isset($USER->access['rsw'])) {
5422 $USER->access['rsw'] = array();
5425 if ($roleid == 0) {
5426 unset($USER->access['rsw'][$context->path]);
5427 if (empty($USER->access['rsw'])) {
5428 unset($USER->access['rsw']);
5430 return true;
5433 $USER->access['rsw'][$context->path]=$roleid;
5435 // Load roledefs
5436 $USER->access = get_role_access_bycontext($roleid, $context,
5437 $USER->access);
5439 return true;
5443 * Checks if the user has switched roles within the given course.
5445 * Note: You can only switch roles within the course, hence it takes a courseid
5446 * rather than a context. On that note Petr volunteered to implement this across
5447 * all other contexts, all requests for this should be forwarded to him ;)
5449 * @param int $courseid The id of the course to check
5450 * @return bool True if the user has switched roles within the course.
5452 function is_role_switched($courseid) {
5453 global $USER;
5454 $context = get_context_instance(CONTEXT_COURSE, $courseid, MUST_EXIST);
5455 return (!empty($USER->access['rsw'][$context->path]));
5459 * Get any role that has an override on exact context
5461 * @global moodle_database
5462 * @param stdClass $context The context to check
5463 * @return array An array of roles
5465 function get_roles_with_override_on_context($context) {
5466 global $DB;
5468 return $DB->get_records_sql("SELECT r.*
5469 FROM {role_capabilities} rc, {role} r
5470 WHERE rc.roleid = r.id AND rc.contextid = ?",
5471 array($context->id));
5475 * Get all capabilities for this role on this context (overrides)
5477 * @param object $role
5478 * @param object $context
5479 * @return array
5481 function get_capabilities_from_role_on_context($role, $context) {
5482 global $DB;
5484 return $DB->get_records_sql("SELECT *
5485 FROM {role_capabilities}
5486 WHERE contextid = ? AND roleid = ?",
5487 array($context->id, $role->id));
5491 * Find out which roles has assignment on this context
5493 * @param object $context
5494 * @return array
5497 function get_roles_with_assignment_on_context($context) {
5498 global $DB;
5500 return $DB->get_records_sql("SELECT r.*
5501 FROM {role_assignments} ra, {role} r
5502 WHERE ra.roleid = r.id AND ra.contextid = ?",
5503 array($context->id));
5509 * Find all user assignment of users for this role, on this context
5511 * @param object $role
5512 * @param object $context
5513 * @return array
5515 function get_users_from_role_on_context($role, $context) {
5516 global $DB;
5518 return $DB->get_records_sql("SELECT *
5519 FROM {role_assignments}
5520 WHERE contextid = ? AND roleid = ?",
5521 array($context->id, $role->id));
5525 * Simple function returning a boolean true if user has roles
5526 * in context or parent contexts, otherwise false.
5528 * @param int $userid
5529 * @param int $roleid
5530 * @param int $contextid empty means any context
5531 * @return bool
5533 function user_has_role_assignment($userid, $roleid, $contextid = 0) {
5534 global $DB;
5536 if ($contextid) {
5537 if (!$context = get_context_instance_by_id($contextid)) {
5538 return false;
5540 $parents = get_parent_contexts($context, true);
5541 list($contexts, $params) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED, 'r');
5542 $params['userid'] = $userid;
5543 $params['roleid'] = $roleid;
5545 $sql = "SELECT COUNT(ra.id)
5546 FROM {role_assignments} ra
5547 WHERE ra.userid = :userid AND ra.roleid = :roleid AND ra.contextid $contexts";
5549 $count = $DB->get_field_sql($sql, $params);
5550 return ($count > 0);
5552 } else {
5553 return $DB->record_exists('role_assignments', array('userid'=>$userid, 'roleid'=>$roleid));
5558 * Get role name or alias if exists and format the text.
5560 * @param object $role role object
5561 * @param object $coursecontext
5562 * @return string name of role in course context
5564 function role_get_name($role, $coursecontext) {
5565 global $DB;
5567 if ($r = $DB->get_record('role_names', array('roleid'=>$role->id, 'contextid'=>$coursecontext->id))) {
5568 return strip_tags(format_string($r->name));
5569 } else {
5570 return strip_tags(format_string($role->name));
5575 * Prepare list of roles for display, apply aliases and format text
5577 * @param array $roleoptions array roleid => rolename or roleid => roleobject
5578 * @param object $context a context
5579 * @return array Array of context-specific role names, or role objexts with a ->localname field added.
5581 function role_fix_names($roleoptions, $context, $rolenamedisplay = ROLENAME_ALIAS) {
5582 global $DB;
5584 // Make sure we are working with an array roleid => name. Normally we
5585 // want to use the unlocalised name if the localised one is not present.
5586 $newnames = array();
5587 foreach ($roleoptions as $rid => $roleorname) {
5588 if ($rolenamedisplay != ROLENAME_ALIAS_RAW) {
5589 if (is_object($roleorname)) {
5590 $newnames[$rid] = $roleorname->name;
5591 } else {
5592 $newnames[$rid] = $roleorname;
5594 } else {
5595 $newnames[$rid] = '';
5599 // If necessary, get the localised names.
5600 if ($rolenamedisplay != ROLENAME_ORIGINAL && !empty($context->id)) {
5601 // Make sure we have a course context.
5602 if ($context->contextlevel == CONTEXT_MODULE) {
5603 if ($parentcontextid = array_shift(get_parent_contexts($context))) {
5604 $context = get_context_instance_by_id($parentcontextid);
5606 } else if ($context->contextlevel == CONTEXT_BLOCK) {
5607 do {
5608 if ($parentcontextid = array_shift(get_parent_contexts($context))) {
5609 $context = get_context_instance_by_id($parentcontextid);
5611 } while ($parentcontextid && $context->contextlevel != CONTEXT_COURSE);
5614 // The get the relevant renames, and use them.
5615 $aliasnames = $DB->get_records('role_names', array('contextid'=>$context->id));
5616 foreach ($aliasnames as $alias) {
5617 if (isset($newnames[$alias->roleid])) {
5618 if ($rolenamedisplay == ROLENAME_ALIAS || $rolenamedisplay == ROLENAME_ALIAS_RAW) {
5619 $newnames[$alias->roleid] = $alias->name;
5620 } else if ($rolenamedisplay == ROLENAME_BOTH) {
5621 $newnames[$alias->roleid] = $alias->name . ' (' . $roleoptions[$alias->roleid] . ')';
5627 // Finally, apply format_string and put the result in the right place.
5628 foreach ($roleoptions as $rid => $roleorname) {
5629 if ($rolenamedisplay != ROLENAME_ALIAS_RAW) {
5630 $newnames[$rid] = strip_tags(format_string($newnames[$rid]));
5632 if (is_object($roleorname)) {
5633 $roleoptions[$rid]->localname = $newnames[$rid];
5634 } else {
5635 $roleoptions[$rid] = $newnames[$rid];
5638 return $roleoptions;
5642 * Aids in detecting if a new line is required when reading a new capability
5644 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
5645 * when we read in a new capability.
5646 * Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
5647 * but when we are in grade, all reports/import/export capabilities should be together
5649 * @param string $cap component string a
5650 * @param string $comp component string b
5651 * @param mixed $contextlevel
5652 * @return bool whether 2 component are in different "sections"
5654 function component_level_changed($cap, $comp, $contextlevel) {
5656 if (strstr($cap->component, '/') && strstr($comp, '/')) {
5657 $compsa = explode('/', $cap->component);
5658 $compsb = explode('/', $comp);
5660 // list of system reports
5661 if (($compsa[0] == 'report') && ($compsb[0] == 'report')) {
5662 return false;
5665 // we are in gradebook, still
5666 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
5667 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
5668 return false;
5671 if (($compsa[0] == 'coursereport') && ($compsb[0] == 'coursereport')) {
5672 return false;
5676 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
5680 * Rebuild all related context depth and path caches
5682 * @param array $fixcontexts array of contexts, strongtyped
5684 function rebuild_contexts(array $fixcontexts) {
5685 global $DB;
5687 foreach ($fixcontexts as $context) {
5688 if ($context->path) {
5689 mark_context_dirty($context->path);
5691 $DB->set_field_select('context', 'depth', 0, "path LIKE '%/$context->id/%'");
5692 $DB->set_field('context', 'depth', 0, array('id'=>$context->id));
5694 build_context_path(false);
5698 * Populate context.path and context.depth where missing.
5700 * @param bool $force force a complete rebuild of the path and depth fields, defaults to false
5702 function build_context_path($force = false) {
5703 global $CFG, $DB, $ACCESSLIB_PRIVATE;
5705 // System context
5706 $sitectx = get_system_context(!$force);
5707 $base = '/'.$sitectx->id;
5709 // Sitecourse
5710 $sitecoursectx = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>SITEID));
5711 if ($force || $sitecoursectx->path !== "$base/{$sitecoursectx->id}") {
5712 $DB->set_field('context', 'path', "$base/{$sitecoursectx->id}", array('id'=>$sitecoursectx->id));
5713 $DB->set_field('context', 'depth', 2, array('id'=>$sitecoursectx->id));
5714 $sitecoursectx = $DB->get_record('context', array('contextlevel'=>CONTEXT_COURSE, 'instanceid'=>SITEID));
5717 $ctxemptyclause = " AND (ctx.path IS NULL
5718 OR ctx.depth=0) ";
5719 $emptyclause = " AND ({context}.path IS NULL
5720 OR {context}.depth=0) ";
5721 if ($force) {
5722 $ctxemptyclause = $emptyclause = '';
5725 /* MDL-11347:
5726 * - mysql does not allow to use FROM in UPDATE statements
5727 * - using two tables after UPDATE works in mysql, but might give unexpected
5728 * results in pg 8 (depends on configuration)
5729 * - using table alias in UPDATE does not work in pg < 8.2
5731 * Different code for each database - mostly for performance reasons
5733 $dbfamily = $DB->get_dbfamily();
5734 if ($dbfamily == 'mysql') {
5735 $updatesql = "UPDATE {context} ct, {context_temp} temp
5736 SET ct.path = temp.path,
5737 ct.depth = temp.depth
5738 WHERE ct.id = temp.id";
5739 } else if ($dbfamily == 'oracle') {
5740 $updatesql = "UPDATE {context} ct
5741 SET (ct.path, ct.depth) =
5742 (SELECT temp.path, temp.depth
5743 FROM {context_temp} temp
5744 WHERE temp.id=ct.id)
5745 WHERE EXISTS (SELECT 'x'
5746 FROM {context_temp} temp
5747 WHERE temp.id = ct.id)";
5748 } else if ($dbfamily == 'postgres' or $dbfamily == 'mssql') {
5749 $updatesql = "UPDATE {context}
5750 SET path = temp.path,
5751 depth = temp.depth
5752 FROM {context_temp} temp
5753 WHERE temp.id={context}.id";
5754 } else {
5755 // sqlite and others
5756 $updatesql = "UPDATE {context}
5757 SET path = (SELECT path FROM {context_temp} WHERE id = {context}.id),
5758 depth = (SELECT depth FROM {context_temp} WHERE id = {context}.id)
5759 WHERE id IN (SELECT id FROM {context_temp})";
5762 // Top level categories
5763 $sql = "UPDATE {context}
5764 SET depth=2, path=" . $DB->sql_concat("'$base/'", 'id') . "
5765 WHERE contextlevel=".CONTEXT_COURSECAT."
5766 AND EXISTS (SELECT 'x'
5767 FROM {course_categories} cc
5768 WHERE cc.id = {context}.instanceid
5769 AND cc.depth=1)
5770 $emptyclause";
5772 $DB->execute($sql);
5773 $DB->delete_records('context_temp');
5775 // Deeper categories - one query per depthlevel
5776 $maxdepth = $DB->get_field_sql("SELECT MAX(depth)
5777 FROM {course_categories}");
5778 for ($n=2; $n<=$maxdepth; $n++) {
5779 $sql = "INSERT INTO {context_temp} (id, path, depth)
5780 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", $n+1
5781 FROM {context} ctx
5782 JOIN {course_categories} c ON ctx.instanceid=c.id
5783 JOIN {context} pctx ON c.parent=pctx.instanceid
5784 WHERE ctx.contextlevel=".CONTEXT_COURSECAT."
5785 AND pctx.contextlevel=".CONTEXT_COURSECAT."
5786 AND c.depth=$n
5787 AND NOT EXISTS (SELECT 'x'
5788 FROM {context_temp} temp
5789 WHERE temp.id = ctx.id)
5790 $ctxemptyclause";
5791 $DB->execute($sql);
5793 // this is needed after every loop
5794 // MDL-11532
5795 $DB->execute($updatesql);
5796 $DB->delete_records('context_temp');
5799 // Courses -- except sitecourse
5800 $sql = "INSERT INTO {context_temp} (id, path, depth)
5801 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5802 FROM {context} ctx
5803 JOIN {course} c ON ctx.instanceid=c.id
5804 JOIN {context} pctx ON c.category=pctx.instanceid
5805 WHERE ctx.contextlevel=".CONTEXT_COURSE."
5806 AND c.id!=".SITEID."
5807 AND pctx.contextlevel=".CONTEXT_COURSECAT."
5808 AND NOT EXISTS (SELECT 'x'
5809 FROM {context_temp} temp
5810 WHERE temp.id = ctx.id)
5811 $ctxemptyclause";
5812 $DB->execute($sql);
5814 $DB->execute($updatesql);
5815 $DB->delete_records('context_temp');
5817 // Module instances
5818 $sql = "INSERT INTO {context_temp} (id, path, depth)
5819 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5820 FROM {context} ctx
5821 JOIN {course_modules} cm ON ctx.instanceid=cm.id
5822 JOIN {context} pctx ON cm.course=pctx.instanceid
5823 WHERE ctx.contextlevel=".CONTEXT_MODULE."
5824 AND pctx.contextlevel=".CONTEXT_COURSE."
5825 AND NOT EXISTS (SELECT 'x'
5826 FROM {context_temp} temp
5827 WHERE temp.id = ctx.id)
5828 $ctxemptyclause";
5829 $DB->execute($sql);
5831 $DB->execute($updatesql);
5832 $DB->delete_records('context_temp');
5834 // User
5835 $sql = "UPDATE {context}
5836 SET depth=2, path=".$DB->sql_concat("'$base/'", 'id')."
5837 WHERE contextlevel=".CONTEXT_USER."
5838 AND EXISTS (SELECT 'x'
5839 FROM {user} u
5840 WHERE u.id = {context}.instanceid)
5841 $emptyclause ";
5842 $DB->execute($sql);
5844 // Blocks
5845 // pctx.path IS NOT NULL prevents fatal problems with broken block instances that point to invalid context parent
5846 $sql = "INSERT INTO {context_temp} (id, path, depth)
5847 SELECT ctx.id, ".$DB->sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5848 FROM {context} ctx
5849 JOIN {block_instances} bi ON ctx.instanceid = bi.id
5850 JOIN {context} pctx ON bi.parentcontextid = pctx.id
5851 WHERE ctx.contextlevel=".CONTEXT_BLOCK."
5852 AND pctx.path IS NOT NULL
5853 AND NOT EXISTS (SELECT 'x'
5854 FROM {context_temp} temp
5855 WHERE temp.id = ctx.id)
5856 $ctxemptyclause";
5857 $DB->execute($sql);
5859 $DB->execute($updatesql);
5860 $DB->delete_records('context_temp');
5862 // reset static course cache - it might have incorrect cached data
5863 $ACCESSLIB_PRIVATE->contexcache->reset();
5867 * Update the path field of the context and all dep. subcontexts that follow
5869 * Update the path field of the context and
5870 * all the dependent subcontexts that follow
5871 * the move.
5873 * The most important thing here is to be as
5874 * DB efficient as possible. This op can have a
5875 * massive impact in the DB.
5877 * @param stdClass $current context obj
5878 * @param stdClass $newparent new parent obj
5881 function context_moved($context, $newparent) {
5882 global $DB;
5884 $frompath = $context->path;
5885 $newpath = $newparent->path . '/' . $context->id;
5887 $setdepth = '';
5888 if (($newparent->depth +1) != $context->depth) {
5889 $diff = $newparent->depth - $context->depth + 1;
5890 $setdepth = ", depth = depth + $diff";
5892 $sql = "UPDATE {context}
5893 SET path = ?
5894 $setdepth
5895 WHERE path = ?";
5896 $params = array($newpath, $frompath);
5897 $DB->execute($sql, $params);
5899 $sql = "UPDATE {context}
5900 SET path = ".$DB->sql_concat("?", $DB->sql_substr("path", strlen($frompath)+1))."
5901 $setdepth
5902 WHERE path LIKE ?";
5903 $params = array($newpath, "{$frompath}/%");
5904 $DB->execute($sql, $params);
5906 mark_context_dirty($frompath);
5907 mark_context_dirty($newpath);
5911 * Preloads context information together with instances.
5912 * NOTE: in future this function may return empty strings
5913 * if we implement different caching.
5915 * @param string $joinon for example 'u.id'
5916 * @param string $contextlevel context level of instance in $joinon
5917 * @param string $tablealias context table alias
5918 * @return array with two values - select and join part
5920 function context_instance_preload_sql($joinon, $contextlevel, $tablealias) {
5921 $select = ", $tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
5922 $join = "LEFT JOIN {context} $tablealias ON ($tablealias.instanceid = $joinon AND $tablealias.contextlevel = $contextlevel)";
5923 return array($select, $join);
5927 * Preloads context information from db record and strips the cached info.
5928 * The db request has to ontain both the $join and $select from context_instance_preload_sql()
5930 * @param object $rec
5931 * @return void (modifies $rec)
5933 function context_instance_preload(stdClass $rec) {
5934 global $ACCESSLIB_PRIVATE;
5935 if (empty($rec->ctxid)) {
5936 // $rec does not have enough data, passed here repeatedly or context does not exist yet
5937 return;
5940 // note: in PHP5 the objects are passed by reference, no need to return $rec
5941 $context = new stdClass();
5942 $context->id = $rec->ctxid; unset($rec->ctxid);
5943 $context->path = $rec->ctxpath; unset($rec->ctxpath);
5944 $context->depth = $rec->ctxdepth; unset($rec->ctxdepth);
5945 $context->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
5946 $context->instanceid = $rec->ctxinstance; unset($rec->ctxinstance);
5948 $ACCESSLIB_PRIVATE->contexcache->add($context);
5952 * Fetch recent dirty contexts to know cheaply whether our $USER->access
5953 * is stale and needs to be reloaded.
5955 * Uses cache_flags
5956 * @param int $time
5957 * @return array Array of dirty contexts
5959 function get_dirty_contexts($time) {
5960 return get_cache_flags('accesslib/dirtycontexts', $time-2);
5964 * Mark a context as dirty (with timestamp)
5965 * so as to force reloading of the context.
5967 * @param string $path context path
5969 function mark_context_dirty($path) {
5970 global $CFG, $ACCESSLIB_PRIVATE;
5972 if (during_initial_install()) {
5973 return;
5976 // only if it is a non-empty string
5977 if (is_string($path) && $path !== '') {
5978 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
5979 if (isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
5980 $ACCESSLIB_PRIVATE->dirtycontexts[$path] = 1;
5986 * Will walk the contextpath to answer whether
5987 * the contextpath is dirty
5989 * @param array $contexts array of strings
5990 * @param obj|array $dirty Dirty contexts from get_dirty_contexts()
5991 * @return bool
5993 function is_contextpath_dirty($pathcontexts, $dirty) {
5994 $path = '';
5995 foreach ($pathcontexts as $ctx) {
5996 $path = $path.'/'.$ctx;
5997 if (isset($dirty[$path])) {
5998 return true;
6001 return false;
6005 * Fix the roles.sortorder field in the database, so it contains sequential integers,
6006 * and return an array of roleids in order.
6008 * @param array $allroles array of roles, as returned by get_all_roles();
6009 * @return array $role->sortorder =-> $role->id with the keys in ascending order.
6011 function fix_role_sortorder($allroles) {
6012 global $DB;
6014 $rolesort = array();
6015 $i = 0;
6016 foreach ($allroles as $role) {
6017 $rolesort[$i] = $role->id;
6018 if ($role->sortorder != $i) {
6019 $r = new stdClass();
6020 $r->id = $role->id;
6021 $r->sortorder = $i;
6022 $DB->update_record('role', $r);
6023 $allroles[$role->id]->sortorder = $i;
6025 $i++;
6027 return $rolesort;
6031 * Switch the sort order of two roles (used in admin/roles/manage.php).
6033 * @param object $first The first role. Actually, only ->sortorder is used.
6034 * @param object $second The second role. Actually, only ->sortorder is used.
6035 * @return boolean success or failure
6037 function switch_roles($first, $second) {
6038 global $DB;
6039 $temp = $DB->get_field('role', 'MAX(sortorder) + 1', array());
6040 $result = $DB->set_field('role', 'sortorder', $temp, array('sortorder' => $first->sortorder));
6041 $result = $result && $DB->set_field('role', 'sortorder', $first->sortorder, array('sortorder' => $second->sortorder));
6042 $result = $result && $DB->set_field('role', 'sortorder', $second->sortorder, array('sortorder' => $temp));
6043 return $result;
6047 * duplicates all the base definitions of a role
6049 * @param object $sourcerole role to copy from
6050 * @param int $targetrole id of role to copy to
6052 function role_cap_duplicate($sourcerole, $targetrole) {
6053 global $DB;
6055 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
6056 $caps = $DB->get_records_sql("SELECT *
6057 FROM {role_capabilities}
6058 WHERE roleid = ? AND contextid = ?",
6059 array($sourcerole->id, $systemcontext->id));
6060 // adding capabilities
6061 foreach ($caps as $cap) {
6062 unset($cap->id);
6063 $cap->roleid = $targetrole;
6064 $DB->insert_record('role_capabilities', $cap);
6070 * Returns two lists, this can be used to find out if user has capability.
6071 * Having any needed role and no forbidden role in this context means
6072 * user has this capability in this context.
6073 * Use get_role_names_with_cap_in_context() if you need role names to display in the UI
6075 * @param object $context
6076 * @param string $capability
6077 * @return array($neededroles, $forbiddenroles)
6079 function get_roles_with_cap_in_context($context, $capability) {
6080 global $DB;
6082 $ctxids = trim($context->path, '/'); // kill leading slash
6083 $ctxids = str_replace('/', ',', $ctxids);
6085 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.depth
6086 FROM {role_capabilities} rc
6087 JOIN {context} ctx ON ctx.id = rc.contextid
6088 WHERE rc.capability = :cap AND ctx.id IN ($ctxids)
6089 ORDER BY rc.roleid ASC, ctx.depth DESC";
6090 $params = array('cap'=>$capability);
6092 if (!$capdefs = $DB->get_records_sql($sql, $params)) {
6093 // no cap definitions --> no capability
6094 return array(array(), array());
6097 $forbidden = array();
6098 $needed = array();
6099 foreach($capdefs as $def) {
6100 if (isset($forbidden[$def->roleid])) {
6101 continue;
6103 if ($def->permission == CAP_PROHIBIT) {
6104 $forbidden[$def->roleid] = $def->roleid;
6105 unset($needed[$def->roleid]);
6106 continue;
6108 if (!isset($needed[$def->roleid])) {
6109 if ($def->permission == CAP_ALLOW) {
6110 $needed[$def->roleid] = true;
6111 } else if ($def->permission == CAP_PREVENT) {
6112 $needed[$def->roleid] = false;
6116 unset($capdefs);
6118 // remove all those roles not allowing
6119 foreach($needed as $key=>$value) {
6120 if (!$value) {
6121 unset($needed[$key]);
6122 } else {
6123 $needed[$key] = $key;
6127 return array($needed, $forbidden);
6131 * Returns an array of role IDs that have ALL of the the supplied capabilities
6132 * Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden
6134 * @param object $context
6135 * @param array $capabilities An array of capabilities
6136 * @return array of roles with all of the required capabilities
6138 function get_roles_with_caps_in_context($context, $capabilities) {
6139 $neededarr = array();
6140 $forbiddenarr = array();
6141 foreach($capabilities as $caprequired) {
6142 list($neededarr[], $forbiddenarr[]) = get_roles_with_cap_in_context($context, $caprequired);
6145 $rolesthatcanrate = array();
6146 if (!empty($neededarr)) {
6147 foreach ($neededarr as $needed) {
6148 if (empty($rolesthatcanrate)) {
6149 $rolesthatcanrate = $needed;
6150 } else {
6151 //only want roles that have all caps
6152 $rolesthatcanrate = array_intersect_key($rolesthatcanrate,$needed);
6156 if (!empty($forbiddenarr) && !empty($rolesthatcanrate)) {
6157 foreach ($forbiddenarr as $forbidden) {
6158 //remove any roles that are forbidden any of the caps
6159 $rolesthatcanrate = array_diff($rolesthatcanrate, $forbidden);
6162 return $rolesthatcanrate;
6166 * Returns an array of role names that have ALL of the the supplied capabilities
6167 * Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden
6169 * @param object $context
6170 * @param array $capabilities An array of capabilities
6171 * @return array of roles with all of the required capabilities
6173 function get_role_names_with_caps_in_context($context, $capabilities) {
6174 global $DB;
6176 $rolesthatcanrate = get_roles_with_caps_in_context($context, $capabilities);
6178 $allroles = array();
6179 $roles = $DB->get_records('role', null, 'sortorder DESC');
6180 foreach ($roles as $roleid=>$role) {
6181 $allroles[$roleid] = $role->name;
6184 $rolenames = array();
6185 foreach ($rolesthatcanrate as $r) {
6186 $rolenames[$r] = $allroles[$r];
6188 $rolenames = role_fix_names($rolenames, $context);
6189 return $rolenames;
6193 * This function verifies the prohibit comes from this context
6194 * and there are no more prohibits in parent contexts.
6195 * @param object $context
6196 * @param string $capability name
6197 * @return bool
6199 function prohibit_is_removable($roleid, $context, $capability) {
6200 global $DB;
6202 $ctxids = trim($context->path, '/'); // kill leading slash
6203 $ctxids = str_replace('/', ',', $ctxids);
6205 $params = array('roleid'=>$roleid, 'cap'=>$capability, 'prohibit'=>CAP_PROHIBIT);
6207 $sql = "SELECT ctx.id
6208 FROM {role_capabilities} rc
6209 JOIN {context} ctx ON ctx.id = rc.contextid
6210 WHERE rc.roleid = :roleid AND rc.permission = :prohibit AND rc.capability = :cap AND ctx.id IN ($ctxids)
6211 ORDER BY ctx.depth DESC";
6213 if (!$prohibits = $DB->get_records_sql($sql, $params)) {
6214 // no prohibits == nothing to remove
6215 return true;
6218 if (count($prohibits) > 1) {
6219 // more prohibints can not be removed
6220 return false;
6223 return !empty($prohibits[$context->id]);
6227 * More user friendly role permission changing,
6228 * it should produce as few overrides as possible.
6229 * @param int $roleid
6230 * @param object $context
6231 * @param string $capname capability name
6232 * @param int $permission
6233 * @return void
6235 function role_change_permission($roleid, $context, $capname, $permission) {
6236 global $DB;
6238 if ($permission == CAP_INHERIT) {
6239 unassign_capability($capname, $roleid, $context->id);
6240 mark_context_dirty($context->path);
6241 return;
6244 $ctxids = trim($context->path, '/'); // kill leading slash
6245 $ctxids = str_replace('/', ',', $ctxids);
6247 $params = array('roleid'=>$roleid, 'cap'=>$capname);
6249 $sql = "SELECT ctx.id, rc.permission, ctx.depth
6250 FROM {role_capabilities} rc
6251 JOIN {context} ctx ON ctx.id = rc.contextid
6252 WHERE rc.roleid = :roleid AND rc.capability = :cap AND ctx.id IN ($ctxids)
6253 ORDER BY ctx.depth DESC";
6255 if ($existing = $DB->get_records_sql($sql, $params)) {
6256 foreach($existing as $e) {
6257 if ($e->permission == CAP_PROHIBIT) {
6258 // prohibit can not be overridden, no point in changing anything
6259 return;
6262 $lowest = array_shift($existing);
6263 if ($lowest->permission == $permission) {
6264 // permission already set in this context or parent - nothing to do
6265 return;
6267 if ($existing) {
6268 $parent = array_shift($existing);
6269 if ($parent->permission == $permission) {
6270 // permission already set in parent context or parent - just unset in this context
6271 // we do this because we want as few overrides as possible for performance reasons
6272 unassign_capability($capname, $roleid, $context->id);
6273 mark_context_dirty($context->path);
6274 return;
6278 } else {
6279 if ($permission == CAP_PREVENT) {
6280 // nothing means role does not have permission
6281 return;
6285 // assign the needed capability
6286 assign_capability($capname, $permission, $roleid, $context->id, true);
6288 // force cap reloading
6289 mark_context_dirty($context->path);