weekly release 2.6dev
[moodle.git] / lib / accesslib.php
CommitLineData
46808d7c 1<?php
117bd748
PS
2// This file is part of Moodle - http://moodle.org/
3//
46808d7c 4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
117bd748 13//
46808d7c 14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
6cdd0f9c 16
92e53168 17/**
46808d7c 18 * This file contains functions for managing user access
19 *
cc3edaa4 20 * <b>Public API vs internals</b>
5a4e7398 21 *
92e53168 22 * General users probably only care about
23 *
dcd6a775 24 * Context handling
e922fe23
PS
25 * - context_course::instance($courseid), context_module::instance($cm->id), context_coursecat::instance($catid)
26 * - context::instance_by_id($contextid)
27 * - $context->get_parent_contexts();
28 * - $context->get_child_contexts();
5a4e7398 29 *
dcd6a775 30 * Whether the user can do something...
92e53168 31 * - has_capability()
8a1b1c32 32 * - has_any_capability()
33 * - has_all_capabilities()
efd6fce5 34 * - require_capability()
dcd6a775 35 * - require_login() (from moodlelib)
f76249cc
PS
36 * - is_enrolled()
37 * - is_viewing()
38 * - is_guest()
e922fe23 39 * - is_siteadmin()
f76249cc
PS
40 * - isguestuser()
41 * - isloggedin()
dcd6a775 42 *
43 * What courses has this user access to?
e922fe23 44 * - get_enrolled_users()
dcd6a775 45 *
db70c4bd 46 * What users can do X in this context?
f76249cc
PS
47 * - get_enrolled_users() - at and bellow course context
48 * - get_users_by_capability() - above course context
db70c4bd 49 *
e922fe23
PS
50 * Modify roles
51 * - role_assign()
52 * - role_unassign()
53 * - role_unassign_all()
5a4e7398 54 *
e922fe23 55 * Advanced - for internal use only
dcd6a775 56 * - load_all_capabilities()
57 * - reload_all_capabilities()
bb2c22bd 58 * - has_capability_in_accessdata()
dcd6a775 59 * - get_user_access_sitewide()
e922fe23
PS
60 * - load_course_context()
61 * - load_role_access_by_context()
62 * - etc.
dcd6a775 63 *
cc3edaa4 64 * <b>Name conventions</b>
5a4e7398 65 *
cc3edaa4 66 * "ctx" means context
92e53168 67 *
cc3edaa4 68 * <b>accessdata</b>
92e53168 69 *
70 * Access control data is held in the "accessdata" array
71 * which - for the logged-in user, will be in $USER->access
5a4e7398 72 *
d867e696 73 * For other users can be generated and passed around (but may also be cached
e922fe23 74 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
92e53168 75 *
bb2c22bd 76 * $accessdata is a multidimensional array, holding
5a4e7398 77 * role assignments (RAs), role-capabilities-perm sets
51be70d2 78 * (role defs) and a list of courses we have loaded
92e53168 79 * data for.
80 *
5a4e7398 81 * Things are keyed on "contextpaths" (the path field of
92e53168 82 * the context table) for fast walking up/down the tree.
cc3edaa4 83 * <code>
e922fe23
PS
84 * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
85 * [$contextpath] = array($roleid=>$roleid)
86 * [$contextpath] = array($roleid=>$roleid)
117bd748 87 * </code>
92e53168 88 *
89 * Role definitions are stored like this
90 * (no cap merge is done - so it's compact)
91 *
cc3edaa4 92 * <code>
e922fe23
PS
93 * $accessdata['rdef']["$contextpath:$roleid"]['mod/forum:viewpost'] = 1
94 * ['mod/forum:editallpost'] = -1
95 * ['mod/forum:startdiscussion'] = -1000
cc3edaa4 96 * </code>
92e53168 97 *
e922fe23 98 * See how has_capability_in_accessdata() walks up the tree.
92e53168 99 *
e922fe23
PS
100 * First we only load rdef and ra down to the course level, but not below.
101 * This keeps accessdata small and compact. Below-the-course ra/rdef
102 * are loaded as needed. We keep track of which courses we have loaded ra/rdef in
cc3edaa4 103 * <code>
e922fe23 104 * $accessdata['loaded'] = array($courseid1=>1, $courseid2=>1)
cc3edaa4 105 * </code>
92e53168 106 *
cc3edaa4 107 * <b>Stale accessdata</b>
92e53168 108 *
109 * For the logged-in user, accessdata is long-lived.
110 *
d867e696 111 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
92e53168 112 * context paths affected by changes. Any check at-or-below
113 * a dirty context will trigger a transparent reload of accessdata.
5a4e7398 114 *
4f65e0fb 115 * Changes at the system level will force the reload for everyone.
92e53168 116 *
cc3edaa4 117 * <b>Default role caps</b>
5a4e7398 118 * The default role assignment is not in the DB, so we
119 * add it manually to accessdata.
92e53168 120 *
121 * This means that functions that work directly off the
122 * DB need to ensure that the default role caps
5a4e7398 123 * are dealt with appropriately.
92e53168 124 *
f76249cc 125 * @package core_access
78bfb562
PS
126 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
127 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
92e53168 128 */
bbbf2d40 129
78bfb562
PS
130defined('MOODLE_INTERNAL') || die();
131
e922fe23 132/** No capability change */
e49e61bf 133define('CAP_INHERIT', 0);
e922fe23 134/** Allow permission, overrides CAP_PREVENT defined in parent contexts */
bbbf2d40 135define('CAP_ALLOW', 1);
e922fe23 136/** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
bbbf2d40 137define('CAP_PREVENT', -1);
e922fe23 138/** Prohibit permission, overrides everything in current and child contexts */
bbbf2d40 139define('CAP_PROHIBIT', -1000);
140
e922fe23 141/** System context level - only one instance in every system */
bbbf2d40 142define('CONTEXT_SYSTEM', 10);
e922fe23 143/** User context level - one instance for each user describing what others can do to user */
4b10f08b 144define('CONTEXT_USER', 30);
e922fe23 145/** Course category context level - one instance for each category */
bbbf2d40 146define('CONTEXT_COURSECAT', 40);
e922fe23 147/** Course context level - one instances for each course */
bbbf2d40 148define('CONTEXT_COURSE', 50);
e922fe23 149/** Course module context level - one instance for each course module */
bbbf2d40 150define('CONTEXT_MODULE', 70);
e922fe23
PS
151/**
152 * Block context level - one instance for each block, sticky blocks are tricky
153 * because ppl think they should be able to override them at lower contexts.
154 * Any other context level instance can be parent of block context.
155 */
bbbf2d40 156define('CONTEXT_BLOCK', 80);
157
e922fe23 158/** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
21b6db6e 159define('RISK_MANAGETRUST', 0x0001);
e922fe23 160/** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
a6b02b65 161define('RISK_CONFIG', 0x0002);
f76249cc 162/** Capability allows user to add scripted content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
21b6db6e 163define('RISK_XSS', 0x0004);
e922fe23 164/** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
21b6db6e 165define('RISK_PERSONAL', 0x0008);
f76249cc 166/** Capability allows users to add content others may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
21b6db6e 167define('RISK_SPAM', 0x0010);
e922fe23 168/** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
3a0c6cca 169define('RISK_DATALOSS', 0x0020);
21b6db6e 170
c52551dc 171/** rolename displays - the name as defined in the role definition, localised if name empty */
cc3edaa4 172define('ROLENAME_ORIGINAL', 0);
c52551dc 173/** rolename displays - the name as defined by a role alias at the course level, falls back to ROLENAME_ORIGINAL if alias not present */
cc3edaa4 174define('ROLENAME_ALIAS', 1);
e922fe23 175/** rolename displays - Both, like this: Role alias (Original) */
cc3edaa4 176define('ROLENAME_BOTH', 2);
e922fe23 177/** rolename displays - the name as defined in the role definition and the shortname in brackets */
cc3edaa4 178define('ROLENAME_ORIGINALANDSHORT', 3);
e922fe23 179/** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
cc3edaa4 180define('ROLENAME_ALIAS_RAW', 4);
e922fe23 181/** rolename displays - the name is simply short role name */
df997f84 182define('ROLENAME_SHORT', 5);
cc3edaa4 183
e922fe23 184if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
f76249cc 185 /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
e922fe23 186 define('CONTEXT_CACHE_MAX_SIZE', 2500);
4d10247f 187}
188
cc3edaa4 189/**
117bd748 190 * Although this looks like a global variable, it isn't really.
cc3edaa4 191 *
117bd748
PS
192 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
193 * It is used to cache various bits of data between function calls for performance reasons.
4f65e0fb 194 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
cc3edaa4 195 * as methods of a class, instead of functions.
196 *
f76249cc 197 * @access private
cc3edaa4 198 * @global stdClass $ACCESSLIB_PRIVATE
199 * @name $ACCESSLIB_PRIVATE
200 */
f14438dc 201global $ACCESSLIB_PRIVATE;
62e65b21 202$ACCESSLIB_PRIVATE = new stdClass();
e922fe23
PS
203$ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache, loaded from DB once per page
204$ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
205$ACCESSLIB_PRIVATE->rolepermissions = array(); // role permissions cache - helps a lot with mem usage
206$ACCESSLIB_PRIVATE->capabilities = null; // detailed information about the capabilities
bbbf2d40 207
d867e696 208/**
46808d7c 209 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
117bd748 210 *
d867e696 211 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
212 * accesslib's private caches. You need to do this before setting up test data,
4f65e0fb 213 * and also at the end of the tests.
e922fe23 214 *
f76249cc 215 * @access private
e922fe23 216 * @return void
d867e696 217 */
218function accesslib_clear_all_caches_for_unit_testing() {
c8b3346c
PS
219 global $USER;
220 if (!PHPUNIT_TEST) {
d867e696 221 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
222 }
e922fe23
PS
223
224 accesslib_clear_all_caches(true);
d867e696 225
226 unset($USER->access);
227}
228
46808d7c 229/**
e922fe23 230 * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
46808d7c 231 *
e922fe23
PS
232 * This reset does not touch global $USER.
233 *
f76249cc 234 * @access private
e922fe23
PS
235 * @param bool $resetcontexts
236 * @return void
46808d7c 237 */
e922fe23
PS
238function accesslib_clear_all_caches($resetcontexts) {
239 global $ACCESSLIB_PRIVATE;
e7876c1e 240
e922fe23
PS
241 $ACCESSLIB_PRIVATE->dirtycontexts = null;
242 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
243 $ACCESSLIB_PRIVATE->rolepermissions = array();
244 $ACCESSLIB_PRIVATE->capabilities = null;
e7876c1e 245
e922fe23
PS
246 if ($resetcontexts) {
247 context_helper::reset_caches();
e7876c1e 248 }
eef879ec 249}
250
eef879ec 251/**
46808d7c 252 * Gets the accessdata for role "sitewide" (system down to course)
343effbe 253 *
f76249cc 254 * @access private
46808d7c 255 * @param int $roleid
e0376a62 256 * @return array
eef879ec 257 */
e922fe23
PS
258function get_role_access($roleid) {
259 global $DB, $ACCESSLIB_PRIVATE;
eef879ec 260
e922fe23 261 /* Get it in 1 DB query...
e0376a62 262 * - relevant role caps at the root and down
263 * to the course level - but not below
264 */
e922fe23
PS
265
266 //TODO: MUC - this could be cached in shared memory to speed up first page loading, web crawlers, etc.
267
268 $accessdata = get_empty_accessdata();
269
270 $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
e7876c1e 271
2c4bccd5
PS
272 // Overrides for the role IN ANY CONTEXTS down to COURSE - not below -.
273
274 /*
e0376a62 275 $sql = "SELECT ctx.path,
276 rc.capability, rc.permission
f33e1ed4 277 FROM {context} ctx
e922fe23
PS
278 JOIN {role_capabilities} rc ON rc.contextid = ctx.id
279 LEFT JOIN {context} cctx
280 ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
281 WHERE rc.roleid = ? AND cctx.id IS NULL";
f33e1ed4 282 $params = array($roleid);
2c4bccd5
PS
283 */
284
285 // Note: the commented out query is 100% accurate but slow, so let's cheat instead by hardcoding the blocks mess directly.
286
287 $sql = "SELECT COALESCE(ctx.path, bctx.path) AS path, rc.capability, rc.permission
288 FROM {role_capabilities} rc
289 LEFT JOIN {context} ctx ON (ctx.id = rc.contextid AND ctx.contextlevel <= ".CONTEXT_COURSE.")
290 LEFT JOIN ({context} bctx
291 JOIN {block_instances} bi ON (bi.id = bctx.instanceid)
292 JOIN {context} pctx ON (pctx.id = bi.parentcontextid AND pctx.contextlevel < ".CONTEXT_COURSE.")
293 ) ON (bctx.id = rc.contextid AND bctx.contextlevel = ".CONTEXT_BLOCK.")
294 WHERE rc.roleid = :roleid AND (ctx.id IS NOT NULL OR bctx.id IS NOT NULL)";
295 $params = array('roleid'=>$roleid);
133d5a97 296
a91b910e 297 // we need extra caching in CLI scripts and cron
e922fe23
PS
298 $rs = $DB->get_recordset_sql($sql, $params);
299 foreach ($rs as $rd) {
300 $k = "{$rd->path}:{$roleid}";
301 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
8d2b18a8 302 }
e922fe23 303 $rs->close();
e0376a62 304
e922fe23
PS
305 // share the role definitions
306 foreach ($accessdata['rdef'] as $k=>$unused) {
307 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
308 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
4e1fe7d1 309 }
e922fe23
PS
310 $accessdata['rdef_count']++;
311 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
4e1fe7d1 312 }
313
314 return $accessdata;
315}
316
8f8ed475 317/**
e922fe23
PS
318 * Get the default guest role, this is used for guest account,
319 * search engine spiders, etc.
117bd748 320 *
e922fe23 321 * @return stdClass role record
8f8ed475 322 */
323function get_guest_role() {
f33e1ed4 324 global $CFG, $DB;
ebce32b5 325
326 if (empty($CFG->guestroleid)) {
4f0c2d00 327 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
ebce32b5 328 $guestrole = array_shift($roles); // Pick the first one
329 set_config('guestroleid', $guestrole->id);
330 return $guestrole;
331 } else {
332 debugging('Can not find any guest role!');
333 return false;
334 }
8f8ed475 335 } else {
f33e1ed4 336 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
ebce32b5 337 return $guestrole;
338 } else {
e922fe23 339 // somebody is messing with guest roles, remove incorrect setting and try to find a new one
ebce32b5 340 set_config('guestroleid', '');
341 return get_guest_role();
342 }
8f8ed475 343 }
344}
345
128f0984 346/**
4f65e0fb 347 * Check whether a user has a particular capability in a given context.
46808d7c 348 *
e922fe23 349 * For example:
f76249cc
PS
350 * $context = context_module::instance($cm->id);
351 * has_capability('mod/forum:replypost', $context)
46808d7c 352 *
4f65e0fb 353 * By default checks the capabilities of the current user, but you can pass a
4f0c2d00
PS
354 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
355 *
356 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
357 * or capabilities with XSS, config or data loss risks.
117bd748 358 *
f76249cc
PS
359 * @category access
360 *
41e87d30 361 * @param string $capability the name of the capability to check. For example mod/forum:view
f76249cc
PS
362 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
363 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
4f0c2d00 364 * @param boolean $doanything If false, ignores effect of admin role assignment
41e87d30 365 * @return boolean true if the user has this capability. Otherwise false.
128f0984 366 */
e922fe23
PS
367function has_capability($capability, context $context, $user = null, $doanything = true) {
368 global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
18818abf 369
31a99877 370 if (during_initial_install()) {
e922fe23 371 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
18818abf 372 // we are in an installer - roles can not work yet
373 return true;
374 } else {
375 return false;
376 }
377 }
7f97ea29 378
4f0c2d00
PS
379 if (strpos($capability, 'moodle/legacy:') === 0) {
380 throw new coding_exception('Legacy capabilities can not be used any more!');
381 }
382
e922fe23
PS
383 if (!is_bool($doanything)) {
384 throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
385 }
386
387 // capability must exist
388 if (!$capinfo = get_capability_info($capability)) {
389 debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
7d0c81b3 390 return false;
74ac5b66 391 }
e922fe23
PS
392
393 if (!isset($USER->id)) {
394 // should never happen
395 $USER->id = 0;
c90e6b46 396 debugging('Capability check being performed on a user with no ID.', DEBUG_DEVELOPER);
4f0c2d00 397 }
7f97ea29 398
4f0c2d00 399 // make sure there is a real user specified
62e65b21 400 if ($user === null) {
e922fe23 401 $userid = $USER->id;
4f0c2d00 402 } else {
2b55aca7 403 $userid = is_object($user) ? $user->id : $user;
cc3d5e10 404 }
405
e922fe23
PS
406 // make sure forcelogin cuts off not-logged-in users if enabled
407 if (!empty($CFG->forcelogin) and $userid == 0) {
4f0c2d00
PS
408 return false;
409 }
e922fe23 410
4f0c2d00 411 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
e922fe23 412 if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
4f0c2d00
PS
413 if (isguestuser($userid) or $userid == 0) {
414 return false;
c84a2dbe 415 }
7f97ea29 416 }
417
e922fe23
PS
418 // somehow make sure the user is not deleted and actually exists
419 if ($userid != 0) {
420 if ($userid == $USER->id and isset($USER->deleted)) {
421 // this prevents one query per page, it is a bit of cheating,
422 // but hopefully session is terminated properly once user is deleted
423 if ($USER->deleted) {
424 return false;
425 }
128f0984 426 } else {
e922fe23
PS
427 if (!context_user::instance($userid, IGNORE_MISSING)) {
428 // no user context == invalid userid
429 return false;
430 }
7be3be1b 431 }
148eb2a7 432 }
128f0984 433
e922fe23
PS
434 // context path/depth must be valid
435 if (empty($context->path) or $context->depth == 0) {
436 // this should not happen often, each upgrade tries to rebuild the context paths
437 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()');
438 if (is_siteadmin($userid)) {
439 return true;
128f0984 440 } else {
e922fe23 441 return false;
128f0984 442 }
148eb2a7 443 }
128f0984 444
4f0c2d00
PS
445 // Find out if user is admin - it is not possible to override the doanything in any way
446 // and it is not possible to switch to admin role either.
447 if ($doanything) {
448 if (is_siteadmin($userid)) {
7abbc5c2
PS
449 if ($userid != $USER->id) {
450 return true;
451 }
452 // make sure switchrole is not used in this context
453 if (empty($USER->access['rsw'])) {
454 return true;
455 }
456 $parts = explode('/', trim($context->path, '/'));
457 $path = '';
458 $switched = false;
459 foreach ($parts as $part) {
460 $path .= '/' . $part;
461 if (!empty($USER->access['rsw'][$path])) {
462 $switched = true;
463 break;
464 }
465 }
466 if (!$switched) {
467 return true;
468 }
469 //ok, admin switched role in this context, let's use normal access control rules
4f0c2d00
PS
470 }
471 }
472
e922fe23
PS
473 // Careful check for staleness...
474 $context->reload_if_dirty();
13a79475 475
e922fe23
PS
476 if ($USER->id == $userid) {
477 if (!isset($USER->access)) {
478 load_all_capabilities();
7f97ea29 479 }
e922fe23 480 $access =& $USER->access;
bb2c22bd 481
e922fe23
PS
482 } else {
483 // make sure user accessdata is really loaded
484 get_user_accessdata($userid, true);
485 $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
204a369c 486 }
4f0c2d00 487
e922fe23
PS
488
489 // Load accessdata for below-the-course context if necessary,
490 // all contexts at and above all courses are already loaded
491 if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
492 load_course_context($userid, $coursecontext, $access);
420bfab1 493 }
e922fe23
PS
494
495 return has_capability_in_accessdata($capability, $context, $access);
7f97ea29 496}
497
3fc3ebf2 498/**
41e87d30 499 * Check if the user has any one of several capabilities from a list.
46808d7c 500 *
41e87d30 501 * This is just a utility method that calls has_capability in a loop. Try to put
502 * the capabilities that most users are likely to have first in the list for best
503 * performance.
3fc3ebf2 504 *
f76249cc 505 * @category access
46808d7c 506 * @see has_capability()
f76249cc 507 *
41e87d30 508 * @param array $capabilities an array of capability names.
f76249cc
PS
509 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
510 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
4f0c2d00 511 * @param boolean $doanything If false, ignore effect of admin role assignment
41e87d30 512 * @return boolean true if the user has any of these capabilities. Otherwise false.
3fc3ebf2 513 */
f76249cc 514function has_any_capability(array $capabilities, context $context, $user = null, $doanything = true) {
3fc3ebf2 515 foreach ($capabilities as $capability) {
f76249cc 516 if (has_capability($capability, $context, $user, $doanything)) {
3fc3ebf2 517 return true;
518 }
519 }
520 return false;
521}
522
8a1b1c32 523/**
41e87d30 524 * Check if the user has all the capabilities in a list.
46808d7c 525 *
41e87d30 526 * This is just a utility method that calls has_capability in a loop. Try to put
527 * the capabilities that fewest users are likely to have first in the list for best
528 * performance.
8a1b1c32 529 *
f76249cc 530 * @category access
46808d7c 531 * @see has_capability()
f76249cc 532 *
41e87d30 533 * @param array $capabilities an array of capability names.
f76249cc
PS
534 * @param context $context the context to check the capability in. You normally get this with instance method of a context class.
535 * @param integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
4f0c2d00 536 * @param boolean $doanything If false, ignore effect of admin role assignment
41e87d30 537 * @return boolean true if the user has all of these capabilities. Otherwise false.
8a1b1c32 538 */
f76249cc 539function has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true) {
8a1b1c32 540 foreach ($capabilities as $capability) {
f76249cc 541 if (!has_capability($capability, $context, $user, $doanything)) {
8a1b1c32 542 return false;
543 }
544 }
545 return true;
546}
547
128f0984 548/**
4f0c2d00 549 * Check if the user is an admin at the site level.
46808d7c 550 *
4f0c2d00
PS
551 * Please note that use of proper capabilities is always encouraged,
552 * this function is supposed to be used from core or for temporary hacks.
39407442 553 *
f76249cc
PS
554 * @category access
555 *
e922fe23
PS
556 * @param int|stdClass $user_or_id user id or user object
557 * @return bool true if user is one of the administrators, false otherwise
39407442 558 */
62e65b21 559function is_siteadmin($user_or_id = null) {
4f0c2d00 560 global $CFG, $USER;
39407442 561
62e65b21 562 if ($user_or_id === null) {
4f0c2d00
PS
563 $user_or_id = $USER;
564 }
6cab02ac 565
4f0c2d00
PS
566 if (empty($user_or_id)) {
567 return false;
568 }
569 if (!empty($user_or_id->id)) {
4f0c2d00
PS
570 $userid = $user_or_id->id;
571 } else {
572 $userid = $user_or_id;
573 }
6cab02ac 574
0d9e5992 575 // Because this script is called many times (150+ for course page) with
576 // the same parameters, it is worth doing minor optimisations. This static
577 // cache stores the value for a single userid, saving about 2ms from course
578 // page load time without using significant memory. As the static cache
579 // also includes the value it depends on, this cannot break unit tests.
580 static $knownid, $knownresult, $knownsiteadmins;
581 if ($knownid === $userid && $knownsiteadmins === $CFG->siteadmins) {
582 return $knownresult;
583 }
584 $knownid = $userid;
585 $knownsiteadmins = $CFG->siteadmins;
586
4f0c2d00 587 $siteadmins = explode(',', $CFG->siteadmins);
0d9e5992 588 $knownresult = in_array($userid, $siteadmins);
589 return $knownresult;
6cab02ac 590}
591
bbdb7070 592/**
4f0c2d00 593 * Returns true if user has at least one role assign
df997f84 594 * of 'coursecontact' role (is potentially listed in some course descriptions).
62e65b21 595 *
e922fe23
PS
596 * @param int $userid
597 * @return bool
bbdb7070 598 */
df997f84 599function has_coursecontact_role($userid) {
2fb34345 600 global $DB, $CFG;
bbdb7070 601
df997f84 602 if (empty($CFG->coursecontact)) {
4f0c2d00
PS
603 return false;
604 }
605 $sql = "SELECT 1
606 FROM {role_assignments}
df997f84 607 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
b2cd6570 608 return $DB->record_exists_sql($sql, array('userid'=>$userid));
bbdb7070 609}
610
128f0984 611/**
01a2ce80 612 * Does the user have a capability to do something?
46808d7c 613 *
31c2de82 614 * Walk the accessdata array and return true/false.
e922fe23 615 * Deals with prohibits, role switching, aggregating
6a8d9a38 616 * capabilities, etc.
617 *
618 * The main feature of here is being FAST and with no
5a4e7398 619 * side effects.
6a8d9a38 620 *
3ac81bd1 621 * Notes:
622 *
3d034f77 623 * Switch Role merges with default role
624 * ------------------------------------
625 * If you are a teacher in course X, you have at least
626 * teacher-in-X + defaultloggedinuser-sitewide. So in the
627 * course you'll have techer+defaultloggedinuser.
628 * We try to mimic that in switchrole.
629 *
01a2ce80
PS
630 * Permission evaluation
631 * ---------------------
4f65e0fb 632 * Originally there was an extremely complicated way
01a2ce80 633 * to determine the user access that dealt with
4f65e0fb
PS
634 * "locality" or role assignments and role overrides.
635 * Now we simply evaluate access for each role separately
01a2ce80
PS
636 * and then verify if user has at least one role with allow
637 * and at the same time no role with prohibit.
638 *
f76249cc 639 * @access private
46808d7c 640 * @param string $capability
e922fe23 641 * @param context $context
46808d7c 642 * @param array $accessdata
46808d7c 643 * @return bool
6a8d9a38 644 */
e922fe23 645function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
3ac81bd1 646 global $CFG;
647
01a2ce80 648 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
e922fe23
PS
649 $path = $context->path;
650 $paths = array($path);
651 while($path = rtrim($path, '0123456789')) {
652 $path = rtrim($path, '/');
653 if ($path === '') {
654 break;
655 }
656 $paths[] = $path;
3ac81bd1 657 }
658
01a2ce80
PS
659 $roles = array();
660 $switchedrole = false;
6a8d9a38 661
01a2ce80
PS
662 // Find out if role switched
663 if (!empty($accessdata['rsw'])) {
6a8d9a38 664 // From the bottom up...
01a2ce80 665 foreach ($paths as $path) {
1209cb5c 666 if (isset($accessdata['rsw'][$path])) {
01a2ce80 667 // Found a switchrole assignment - check for that role _plus_ the default user role
62e65b21 668 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
01a2ce80
PS
669 $switchedrole = true;
670 break;
6a8d9a38 671 }
672 }
673 }
674
01a2ce80
PS
675 if (!$switchedrole) {
676 // get all users roles in this context and above
677 foreach ($paths as $path) {
678 if (isset($accessdata['ra'][$path])) {
679 foreach ($accessdata['ra'][$path] as $roleid) {
62e65b21 680 $roles[$roleid] = null;
7f97ea29 681 }
01a2ce80
PS
682 }
683 }
7f97ea29 684 }
685
01a2ce80 686 // Now find out what access is given to each role, going bottom-->up direction
e922fe23 687 $allowed = false;
01a2ce80
PS
688 foreach ($roles as $roleid => $ignored) {
689 foreach ($paths as $path) {
690 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
691 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
e922fe23
PS
692 if ($perm === CAP_PROHIBIT) {
693 // any CAP_PROHIBIT found means no permission for the user
694 return false;
695 }
696 if (is_null($roles[$roleid])) {
01a2ce80
PS
697 $roles[$roleid] = $perm;
698 }
699 }
7f97ea29 700 }
e922fe23
PS
701 // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
702 $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
7f97ea29 703 }
704
e922fe23 705 return $allowed;
018d4b52 706}
707
0468976c 708/**
41e87d30 709 * A convenience function that tests has_capability, and displays an error if
710 * the user does not have that capability.
8a9c1c1c 711 *
41e87d30 712 * NOTE before Moodle 2.0, this function attempted to make an appropriate
713 * require_login call before checking the capability. This is no longer the case.
714 * You must call require_login (or one of its variants) if you want to check the
715 * user is logged in, before you call this function.
efd6fce5 716 *
46808d7c 717 * @see has_capability()
718 *
41e87d30 719 * @param string $capability the name of the capability to check. For example mod/forum:view
e922fe23
PS
720 * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
721 * @param int $userid A user id. By default (null) checks the permissions of the current user.
4f0c2d00 722 * @param bool $doanything If false, ignore effect of admin role assignment
e922fe23 723 * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
41e87d30 724 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
725 * @return void terminates with an error if the user does not have the given capability.
0468976c 726 */
e922fe23 727function require_capability($capability, context $context, $userid = null, $doanything = true,
41e87d30 728 $errormessage = 'nopermissions', $stringfile = '') {
d74067e8 729 if (!has_capability($capability, $context, $userid, $doanything)) {
9a0df45a 730 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
0468976c 731 }
732}
733
a9bee37e 734/**
46808d7c 735 * Return a nested array showing role assignments
a9bee37e 736 * all relevant role capabilities for the user at
df997f84 737 * site/course_category/course levels
a9bee37e 738 *
739 * We do _not_ delve deeper than courses because the number of
e922fe23 740 * overrides at the module/block levels can be HUGE.
a9bee37e 741 *
e922fe23
PS
742 * [ra] => [/path][roleid]=roleid
743 * [rdef] => [/path:roleid][capability]=permission
a9bee37e 744 *
f76249cc 745 * @access private
62e65b21 746 * @param int $userid - the id of the user
e922fe23 747 * @return array access info array
a9bee37e 748 */
74ac5b66 749function get_user_access_sitewide($userid) {
e922fe23 750 global $CFG, $DB, $ACCESSLIB_PRIVATE;
a9bee37e 751
e922fe23 752 /* Get in a few cheap DB queries...
f5930992 753 * - role assignments
a9bee37e 754 * - relevant role caps
f5930992 755 * - above and within this user's RAs
a9bee37e 756 * - below this user's RAs - limited to course level
757 */
758
e922fe23
PS
759 // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
760 $raparents = array();
761 $accessdata = get_empty_accessdata();
a9bee37e 762
e922fe23
PS
763 // start with the default role
764 if (!empty($CFG->defaultuserroleid)) {
765 $syscontext = context_system::instance();
766 $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
e7f2c2cc 767 $raparents[$CFG->defaultuserroleid][$syscontext->id] = $syscontext->id;
e922fe23
PS
768 }
769
770 // load the "default frontpage role"
771 if (!empty($CFG->defaultfrontpageroleid)) {
772 $frontpagecontext = context_course::instance(get_site()->id);
773 if ($frontpagecontext->path) {
774 $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
e7f2c2cc 775 $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->id] = $frontpagecontext->id;
e922fe23
PS
776 }
777 }
778
779 // preload every assigned role at and above course context
e7f2c2cc 780 $sql = "SELECT ctx.path, ra.roleid, ra.contextid
f33e1ed4 781 FROM {role_assignments} ra
e7f2c2cc
PS
782 JOIN {context} ctx
783 ON ctx.id = ra.contextid
784 LEFT JOIN {block_instances} bi
785 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
786 LEFT JOIN {context} bpctx
787 ON (bpctx.id = bi.parentcontextid)
788 WHERE ra.userid = :userid
789 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")";
e922fe23
PS
790 $params = array('userid'=>$userid);
791 $rs = $DB->get_recordset_sql($sql, $params);
792 foreach ($rs as $ra) {
793 // RAs leafs are arrays to support multi-role assignments...
794 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
e7f2c2cc 795 $raparents[$ra->roleid][$ra->contextid] = $ra->contextid;
a9bee37e 796 }
e922fe23 797 $rs->close();
a9bee37e 798
e922fe23
PS
799 if (empty($raparents)) {
800 return $accessdata;
a9bee37e 801 }
f5930992 802
e922fe23
PS
803 // now get overrides of interesting roles in all interesting child contexts
804 // hopefully we will not run out of SQL limits here,
e7f2c2cc 805 // users would have to have very many roles at/above course context...
e922fe23
PS
806 $sqls = array();
807 $params = array();
f5930992 808
e922fe23 809 static $cp = 0;
e7f2c2cc 810 foreach ($raparents as $roleid=>$ras) {
e922fe23 811 $cp++;
e7f2c2cc
PS
812 list($sqlcids, $cids) = $DB->get_in_or_equal($ras, SQL_PARAMS_NAMED, 'c'.$cp.'_');
813 $params = array_merge($params, $cids);
e922fe23
PS
814 $params['r'.$cp] = $roleid;
815 $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
816 FROM {role_capabilities} rc
817 JOIN {context} ctx
818 ON (ctx.id = rc.contextid)
e922fe23 819 JOIN {context} pctx
e7f2c2cc 820 ON (pctx.id $sqlcids
e922fe23
PS
821 AND (ctx.id = pctx.id
822 OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
823 OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
e7f2c2cc
PS
824 LEFT JOIN {block_instances} bi
825 ON (ctx.contextlevel = ".CONTEXT_BLOCK." AND bi.id = ctx.instanceid)
826 LEFT JOIN {context} bpctx
827 ON (bpctx.id = bi.parentcontextid)
e922fe23 828 WHERE rc.roleid = :r{$cp}
e7f2c2cc
PS
829 AND (ctx.contextlevel <= ".CONTEXT_COURSE." OR bpctx.contextlevel < ".CONTEXT_COURSE.")
830 )";
e922fe23
PS
831 }
832
833 // fixed capability order is necessary for rdef dedupe
834 $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
a9bee37e 835
e922fe23
PS
836 foreach ($rs as $rd) {
837 $k = $rd->path.':'.$rd->roleid;
838 $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
a9bee37e 839 }
e922fe23 840 $rs->close();
a9bee37e 841
e922fe23
PS
842 // share the role definitions
843 foreach ($accessdata['rdef'] as $k=>$unused) {
844 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
845 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
0dbb2191 846 }
e922fe23
PS
847 $accessdata['rdef_count']++;
848 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
a9bee37e 849 }
e922fe23 850
bb2c22bd 851 return $accessdata;
a9bee37e 852}
853
74ac5b66 854/**
e922fe23 855 * Add to the access ctrl array the data needed by a user for a given course.
74ac5b66 856 *
e922fe23
PS
857 * This function injects all course related access info into the accessdata array.
858 *
f76249cc 859 * @access private
e922fe23
PS
860 * @param int $userid the id of the user
861 * @param context_course $coursecontext course context
862 * @param array $accessdata accessdata array (modified)
863 * @return void modifies $accessdata parameter
74ac5b66 864 */
e922fe23
PS
865function load_course_context($userid, context_course $coursecontext, &$accessdata) {
866 global $DB, $CFG, $ACCESSLIB_PRIVATE;
018d4b52 867
e922fe23
PS
868 if (empty($coursecontext->path)) {
869 // weird, this should not happen
870 return;
871 }
74ac5b66 872
e922fe23
PS
873 if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
874 // already loaded, great!
875 return;
876 }
74ac5b66 877
e922fe23 878 $roles = array();
5a4e7398 879
e922fe23
PS
880 if (empty($userid)) {
881 if (!empty($CFG->notloggedinroleid)) {
882 $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
883 }
74ac5b66 884
e922fe23
PS
885 } else if (isguestuser($userid)) {
886 if ($guestrole = get_guest_role()) {
887 $roles[$guestrole->id] = $guestrole->id;
888 }
74ac5b66 889
e922fe23
PS
890 } else {
891 // Interesting role assignments at, above and below the course context
892 list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
893 $params['userid'] = $userid;
894 $params['children'] = $coursecontext->path."/%";
895 $sql = "SELECT ra.*, ctx.path
896 FROM {role_assignments} ra
897 JOIN {context} ctx ON ra.contextid = ctx.id
898 WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
899 $rs = $DB->get_recordset_sql($sql, $params);
900
901 // add missing role definitions
f33e1ed4 902 foreach ($rs as $ra) {
e922fe23
PS
903 $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
904 $roles[$ra->roleid] = $ra->roleid;
74ac5b66 905 }
f33e1ed4 906 $rs->close();
74ac5b66 907
e922fe23
PS
908 // add the "default frontpage role" when on the frontpage
909 if (!empty($CFG->defaultfrontpageroleid)) {
910 $frontpagecontext = context_course::instance(get_site()->id);
911 if ($frontpagecontext->id == $coursecontext->id) {
912 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
913 }
914 }
53fb75dc 915
e922fe23
PS
916 // do not forget the default role
917 if (!empty($CFG->defaultuserroleid)) {
918 $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
919 }
74ac5b66 920 }
921
e922fe23
PS
922 if (!$roles) {
923 // weird, default roles must be missing...
924 $accessdata['loaded'][$coursecontext->instanceid] = 1;
925 return;
7e17f43b 926 }
e922fe23
PS
927
928 // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
929 $params = array('c'=>$coursecontext->id);
930 list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
931 $params = array_merge($params, $rparams);
932 list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
933 $params = array_merge($params, $rparams);
934
53fb75dc 935 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
e922fe23
PS
936 FROM {role_capabilities} rc
937 JOIN {context} ctx
938 ON (ctx.id = rc.contextid)
939 JOIN {context} cctx
940 ON (cctx.id = :c
941 AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
942 WHERE rc.roleid $roleids
943 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
944 $rs = $DB->get_recordset_sql($sql, $params);
53fb75dc 945
a2cf7f1b 946 $newrdefs = array();
afa559e9 947 foreach ($rs as $rd) {
e922fe23
PS
948 $k = $rd->path.':'.$rd->roleid;
949 if (isset($accessdata['rdef'][$k])) {
950 continue;
74ac5b66 951 }
e922fe23 952 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
74ac5b66 953 }
afa559e9 954 $rs->close();
74ac5b66 955
e922fe23
PS
956 // share new role definitions
957 foreach ($newrdefs as $k=>$unused) {
958 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
959 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
960 }
961 $accessdata['rdef_count']++;
962 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
a2cf7f1b 963 }
74ac5b66 964
e922fe23
PS
965 $accessdata['loaded'][$coursecontext->instanceid] = 1;
966
967 // we want to deduplicate the USER->access from time to time, this looks like a good place,
968 // because we have to do it before the end of session
969 dedupe_user_access();
74ac5b66 970}
2f1a4248 971
eef879ec 972/**
46808d7c 973 * Add to the access ctrl array the data needed by a role for a given context.
6f1bce30 974 *
975 * The data is added in the rdef key.
6f1bce30 976 * This role-centric function is useful for role_switching
e922fe23 977 * and temporary course roles.
6f1bce30 978 *
f76249cc 979 * @access private
e922fe23
PS
980 * @param int $roleid the id of the user
981 * @param context $context needs path!
982 * @param array $accessdata accessdata array (is modified)
46808d7c 983 * @return array
6f1bce30 984 */
e922fe23
PS
985function load_role_access_by_context($roleid, context $context, &$accessdata) {
986 global $DB, $ACCESSLIB_PRIVATE;
6f1bce30 987
988 /* Get the relevant rolecaps into rdef
989 * - relevant role caps
990 * - at ctx and above
991 * - below this ctx
992 */
993
e922fe23
PS
994 if (empty($context->path)) {
995 // weird, this should not happen
996 return;
6f1bce30 997 }
5a4e7398 998
e922fe23
PS
999 list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
1000 $params['roleid'] = $roleid;
1001 $params['childpath'] = $context->path.'/%';
6f1bce30 1002
6f1bce30 1003 $sql = "SELECT ctx.path, rc.capability, rc.permission
f33e1ed4 1004 FROM {role_capabilities} rc
e922fe23
PS
1005 JOIN {context} ctx ON (rc.contextid = ctx.id)
1006 WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
1007 ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
afa559e9 1008 $rs = $DB->get_recordset_sql($sql, $params);
e922fe23
PS
1009
1010 $newrdefs = array();
afa559e9 1011 foreach ($rs as $rd) {
e922fe23
PS
1012 $k = $rd->path.':'.$roleid;
1013 if (isset($accessdata['rdef'][$k])) {
1014 continue;
1015 }
1016 $newrdefs[$k][$rd->capability] = (int)$rd->permission;
6f1bce30 1017 }
afa559e9 1018 $rs->close();
6f1bce30 1019
e922fe23
PS
1020 // share new role definitions
1021 foreach ($newrdefs as $k=>$unused) {
1022 if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
1023 $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
1024 }
1025 $accessdata['rdef_count']++;
1026 $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
1027 }
1028}
1029
1030/**
1031 * Returns empty accessdata structure.
99ddfdf4 1032 *
f76249cc 1033 * @access private
e922fe23
PS
1034 * @return array empt accessdata
1035 */
1036function get_empty_accessdata() {
1037 $accessdata = array(); // named list
1038 $accessdata['ra'] = array();
1039 $accessdata['rdef'] = array();
1040 $accessdata['rdef_count'] = 0; // this bloody hack is necessary because count($array) is slooooowwww in PHP
1041 $accessdata['rdef_lcc'] = 0; // rdef_count during the last compression
1042 $accessdata['loaded'] = array(); // loaded course contexts
1043 $accessdata['time'] = time();
843ca761 1044 $accessdata['rsw'] = array();
e922fe23 1045
bb2c22bd 1046 return $accessdata;
6f1bce30 1047}
1048
a2cf7f1b 1049/**
e922fe23 1050 * Get accessdata for a given user.
204a369c 1051 *
f76249cc 1052 * @access private
46808d7c 1053 * @param int $userid
e922fe23
PS
1054 * @param bool $preloadonly true means do not return access array
1055 * @return array accessdata
5a4e7398 1056 */
e922fe23
PS
1057function get_user_accessdata($userid, $preloadonly=false) {
1058 global $CFG, $ACCESSLIB_PRIVATE, $USER;
204a369c 1059
e922fe23
PS
1060 if (!empty($USER->acces['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1061 // share rdef from USER session with rolepermissions cache in order to conserve memory
1062 foreach($USER->acces['rdef'] as $k=>$v) {
1063 $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->acces['rdef'][$k];
7d0c81b3 1064 }
e922fe23 1065 $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->acces;
204a369c 1066 }
1067
e922fe23
PS
1068 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1069 if (empty($userid)) {
1070 if (!empty($CFG->notloggedinroleid)) {
1071 $accessdata = get_role_access($CFG->notloggedinroleid);
1072 } else {
1073 // weird
1074 return get_empty_accessdata();
1075 }
1076
1077 } else if (isguestuser($userid)) {
1078 if ($guestrole = get_guest_role()) {
1079 $accessdata = get_role_access($guestrole->id);
1080 } else {
1081 //weird
1082 return get_empty_accessdata();
1083 }
1084
1085 } else {
1086 $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
4e1fe7d1 1087 }
128f0984 1088
e922fe23
PS
1089 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1090 }
a2cf7f1b 1091
e922fe23
PS
1092 if ($preloadonly) {
1093 return;
1094 } else {
1095 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1096 }
204a369c 1097}
ef989bd9 1098
a2cf7f1b 1099/**
e922fe23
PS
1100 * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1101 * this function looks for contexts with the same overrides and shares them.
cc3edaa4 1102 *
f76249cc 1103 * @access private
e922fe23 1104 * @return void
a2cf7f1b 1105 */
e922fe23
PS
1106function dedupe_user_access() {
1107 global $USER;
a2cf7f1b 1108
e922fe23
PS
1109 if (CLI_SCRIPT) {
1110 // no session in CLI --> no compression necessary
1111 return;
1112 }
a2cf7f1b 1113
e922fe23
PS
1114 if (empty($USER->access['rdef_count'])) {
1115 // weird, this should not happen
1116 return;
1117 }
1118
1119 // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1120 if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1121 // do not compress after each change, wait till there is more stuff to be done
1122 return;
1123 }
1124
1125 $hashmap = array();
1126 foreach ($USER->access['rdef'] as $k=>$def) {
1127 $hash = sha1(serialize($def));
1128 if (isset($hashmap[$hash])) {
1129 $USER->access['rdef'][$k] =& $hashmap[$hash];
1130 } else {
1131 $hashmap[$hash] =& $USER->access['rdef'][$k];
a2cf7f1b 1132 }
a2cf7f1b 1133 }
e922fe23
PS
1134
1135 $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
a2cf7f1b 1136}
1137
6f1bce30 1138/**
46808d7c 1139 * A convenience function to completely load all the capabilities
e922fe23
PS
1140 * for the current user. It is called from has_capability() and functions change permissions.
1141 *
1142 * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
46808d7c 1143 * @see check_enrolment_plugins()
117bd748 1144 *
f76249cc 1145 * @access private
62e65b21 1146 * @return void
2f1a4248 1147 */
1148function load_all_capabilities() {
e922fe23 1149 global $USER;
bbbf2d40 1150
18818abf 1151 // roles not installed yet - we are in the middle of installation
31a99877 1152 if (during_initial_install()) {
1045a007 1153 return;
1154 }
1155
e922fe23
PS
1156 if (!isset($USER->id)) {
1157 // this should not happen
1158 $USER->id = 0;
2f1a4248 1159 }
55e68c29 1160
e922fe23
PS
1161 unset($USER->access);
1162 $USER->access = get_user_accessdata($USER->id);
1163
1164 // deduplicate the overrides to minimize session size
1165 dedupe_user_access();
55e68c29 1166
1167 // Clear to force a refresh
e922fe23 1168 unset($USER->mycourses);
bbfdff34
PS
1169
1170 // init/reset internal enrol caches - active course enrolments and temp access
1171 $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
bbbf2d40 1172}
1173
ef989bd9 1174/**
5a4e7398 1175 * A convenience function to completely reload all the capabilities
ef989bd9 1176 * for the current user when roles have been updated in a relevant
5a4e7398 1177 * context -- but PRESERVING switchroles and loginas.
e922fe23 1178 * This function resets all accesslib and context caches.
ef989bd9 1179 *
1180 * That is - completely transparent to the user.
5a4e7398 1181 *
e922fe23 1182 * Note: reloads $USER->access completely.
ef989bd9 1183 *
f76249cc 1184 * @access private
62e65b21 1185 * @return void
ef989bd9 1186 */
1187function reload_all_capabilities() {
e922fe23 1188 global $USER, $DB, $ACCESSLIB_PRIVATE;
ef989bd9 1189
ef989bd9 1190 // copy switchroles
1191 $sw = array();
843ca761 1192 if (!empty($USER->access['rsw'])) {
ef989bd9 1193 $sw = $USER->access['rsw'];
ef989bd9 1194 }
1195
e922fe23 1196 accesslib_clear_all_caches(true);
ef989bd9 1197 unset($USER->access);
e922fe23 1198 $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
5a4e7398 1199
ef989bd9 1200 load_all_capabilities();
1201
1202 foreach ($sw as $path => $roleid) {
e922fe23
PS
1203 if ($record = $DB->get_record('context', array('path'=>$path))) {
1204 $context = context::instance_by_id($record->id);
1205 role_switch($roleid, $context);
1206 }
ef989bd9 1207 }
ef989bd9 1208}
2f1a4248 1209
f33e1ed4 1210/**
e922fe23 1211 * Adds a temp role to current USER->access array.
343effbe 1212 *
e922fe23 1213 * Useful for the "temporary guest" access we grant to logged-in users.
f76249cc 1214 * This is useful for enrol plugins only.
343effbe 1215 *
f76249cc 1216 * @since 2.2
e922fe23 1217 * @param context_course $coursecontext
46808d7c 1218 * @param int $roleid
e922fe23 1219 * @return void
343effbe 1220 */
e922fe23 1221function load_temp_course_role(context_course $coursecontext, $roleid) {
bbfdff34 1222 global $USER, $SITE;
5a4e7398 1223
e922fe23
PS
1224 if (empty($roleid)) {
1225 debugging('invalid role specified in load_temp_course_role()');
1226 return;
1227 }
343effbe 1228
bbfdff34
PS
1229 if ($coursecontext->instanceid == $SITE->id) {
1230 debugging('Can not use temp roles on the frontpage');
1231 return;
1232 }
1233
e922fe23
PS
1234 if (!isset($USER->access)) {
1235 load_all_capabilities();
f33e1ed4 1236 }
343effbe 1237
e922fe23 1238 $coursecontext->reload_if_dirty();
343effbe 1239
e922fe23
PS
1240 if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1241 return;
343effbe 1242 }
1243
e922fe23
PS
1244 // load course stuff first
1245 load_course_context($USER->id, $coursecontext, $USER->access);
1246
1247 $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1248
1249 load_role_access_by_context($roleid, $coursecontext, $USER->access);
343effbe 1250}
1251
efe12f6c 1252/**
e922fe23 1253 * Removes any extra guest roles from current USER->access array.
f76249cc 1254 * This is useful for enrol plugins only.
e922fe23 1255 *
f76249cc 1256 * @since 2.2
e922fe23
PS
1257 * @param context_course $coursecontext
1258 * @return void
64026e8c 1259 */
e922fe23 1260function remove_temp_course_roles(context_course $coursecontext) {
bbfdff34
PS
1261 global $DB, $USER, $SITE;
1262
1263 if ($coursecontext->instanceid == $SITE->id) {
1264 debugging('Can not use temp roles on the frontpage');
1265 return;
1266 }
e922fe23
PS
1267
1268 if (empty($USER->access['ra'][$coursecontext->path])) {
1269 //no roles here, weird
1270 return;
1271 }
1272
df997f84
PS
1273 $sql = "SELECT DISTINCT ra.roleid AS id
1274 FROM {role_assignments} ra
1275 WHERE ra.contextid = :contextid AND ra.userid = :userid";
e922fe23 1276 $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
e4ec4e41 1277
e922fe23
PS
1278 $USER->access['ra'][$coursecontext->path] = array();
1279 foreach($ras as $r) {
1280 $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
0831484c 1281 }
64026e8c 1282}
1283
3562486b 1284/**
4f0c2d00 1285 * Returns array of all role archetypes.
cc3edaa4 1286 *
46808d7c 1287 * @return array
3562486b 1288 */
4f0c2d00 1289function get_role_archetypes() {
3562486b 1290 return array(
4f0c2d00
PS
1291 'manager' => 'manager',
1292 'coursecreator' => 'coursecreator',
1293 'editingteacher' => 'editingteacher',
1294 'teacher' => 'teacher',
1295 'student' => 'student',
1296 'guest' => 'guest',
1297 'user' => 'user',
1298 'frontpage' => 'frontpage'
3562486b 1299 );
1300}
1301
bbbf2d40 1302/**
4f65e0fb 1303 * Assign the defaults found in this capability definition to roles that have
bbbf2d40 1304 * the corresponding legacy capabilities assigned to them.
cc3edaa4 1305 *
46808d7c 1306 * @param string $capability
1307 * @param array $legacyperms an array in the format (example):
bbbf2d40 1308 * 'guest' => CAP_PREVENT,
1309 * 'student' => CAP_ALLOW,
1310 * 'teacher' => CAP_ALLOW,
1311 * 'editingteacher' => CAP_ALLOW,
1312 * 'coursecreator' => CAP_ALLOW,
4f0c2d00 1313 * 'manager' => CAP_ALLOW
46808d7c 1314 * @return boolean success or failure.
bbbf2d40 1315 */
1316function assign_legacy_capabilities($capability, $legacyperms) {
eef868d1 1317
4f0c2d00 1318 $archetypes = get_role_archetypes();
3562486b 1319
bbbf2d40 1320 foreach ($legacyperms as $type => $perm) {
eef868d1 1321
e922fe23 1322 $systemcontext = context_system::instance();
4f0c2d00
PS
1323 if ($type === 'admin') {
1324 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1325 $type = 'manager';
1326 }
eef868d1 1327
4f0c2d00 1328 if (!array_key_exists($type, $archetypes)) {
e49ef64a 1329 print_error('invalidlegacy', '', '', $type);
3562486b 1330 }
eef868d1 1331
4f0c2d00 1332 if ($roles = get_archetype_roles($type)) {
2e85fffe 1333 foreach ($roles as $role) {
1334 // Assign a site level capability.
1335 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1336 return false;
1337 }
bbbf2d40 1338 }
1339 }
1340 }
1341 return true;
1342}
1343
faf75fe7 1344/**
e922fe23
PS
1345 * Verify capability risks.
1346 *
f76249cc 1347 * @param stdClass $capability a capability - a row from the capabilities table.
ed149942 1348 * @return boolean whether this capability is safe - that is, whether people with the
faf75fe7 1349 * safeoverrides capability should be allowed to change it.
1350 */
1351function is_safe_capability($capability) {
4659454a 1352 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
faf75fe7 1353}
cee0901c 1354
bbbf2d40 1355/**
e922fe23 1356 * Get the local override (if any) for a given capability in a role in a context
a0760047 1357 *
e922fe23
PS
1358 * @param int $roleid
1359 * @param int $contextid
1360 * @param string $capability
1361 * @return stdClass local capability override
bbbf2d40 1362 */
e922fe23
PS
1363function get_local_override($roleid, $contextid, $capability) {
1364 global $DB;
1365 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1366}
e40413be 1367
e922fe23
PS
1368/**
1369 * Returns context instance plus related course and cm instances
1370 *
1371 * @param int $contextid
1372 * @return array of ($context, $course, $cm)
1373 */
1374function get_context_info_array($contextid) {
1375 global $DB;
e40413be 1376
e922fe23
PS
1377 $context = context::instance_by_id($contextid, MUST_EXIST);
1378 $course = null;
1379 $cm = null;
e40413be 1380
e922fe23
PS
1381 if ($context->contextlevel == CONTEXT_COURSE) {
1382 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
e40413be 1383
e922fe23
PS
1384 } else if ($context->contextlevel == CONTEXT_MODULE) {
1385 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1386 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
7d0c81b3 1387
e922fe23
PS
1388 } else if ($context->contextlevel == CONTEXT_BLOCK) {
1389 $parent = $context->get_parent_context();
f689028c 1390
e922fe23
PS
1391 if ($parent->contextlevel == CONTEXT_COURSE) {
1392 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1393 } else if ($parent->contextlevel == CONTEXT_MODULE) {
1394 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1395 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1396 }
bbbf2d40 1397 }
4f0c2d00 1398
e922fe23 1399 return array($context, $course, $cm);
bbbf2d40 1400}
1401
efe12f6c 1402/**
e922fe23 1403 * Function that creates a role
46808d7c 1404 *
e922fe23
PS
1405 * @param string $name role name
1406 * @param string $shortname role short name
1407 * @param string $description role description
1408 * @param string $archetype
1409 * @return int id or dml_exception
8ba412da 1410 */
e922fe23
PS
1411function create_role($name, $shortname, $description, $archetype = '') {
1412 global $DB;
7d0c81b3 1413
e922fe23
PS
1414 if (strpos($archetype, 'moodle/legacy:') !== false) {
1415 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
8ba412da 1416 }
7d0c81b3 1417
e922fe23
PS
1418 // verify role archetype actually exists
1419 $archetypes = get_role_archetypes();
1420 if (empty($archetypes[$archetype])) {
1421 $archetype = '';
7d0c81b3 1422 }
1423
e922fe23
PS
1424 // Insert the role record.
1425 $role = new stdClass();
1426 $role->name = $name;
1427 $role->shortname = $shortname;
1428 $role->description = $description;
1429 $role->archetype = $archetype;
1430
1431 //find free sortorder number
1432 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1433 if (empty($role->sortorder)) {
1434 $role->sortorder = 1;
7d0c81b3 1435 }
e922fe23 1436 $id = $DB->insert_record('role', $role);
7d0c81b3 1437
e922fe23 1438 return $id;
8ba412da 1439}
b51ece5b 1440
9991d157 1441/**
e922fe23 1442 * Function that deletes a role and cleanups up after it
cc3edaa4 1443 *
e922fe23
PS
1444 * @param int $roleid id of role to delete
1445 * @return bool always true
9991d157 1446 */
e922fe23
PS
1447function delete_role($roleid) {
1448 global $DB;
b51ece5b 1449
e922fe23
PS
1450 // first unssign all users
1451 role_unassign_all(array('roleid'=>$roleid));
2ac56258 1452
e922fe23
PS
1453 // cleanup all references to this role, ignore errors
1454 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
1455 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
1456 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
1457 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1458 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1459 $DB->delete_records('role_names', array('roleid'=>$roleid));
1460 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
a05bcfba 1461
e922fe23
PS
1462 // finally delete the role itself
1463 // get this before the name is gone for logging
1464 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
582bae08 1465
e922fe23 1466 $DB->delete_records('role', array('id'=>$roleid));
582bae08 1467
e922fe23 1468 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
196f1a25
PS
1469
1470 return true;
9991d157 1471}
1472
9a81a606 1473/**
e922fe23 1474 * Function to write context specific overrides, or default capabilities.
cc3edaa4 1475 *
e922fe23
PS
1476 * NOTE: use $context->mark_dirty() after this
1477 *
1478 * @param string $capability string name
1479 * @param int $permission CAP_ constants
1480 * @param int $roleid role id
1481 * @param int|context $contextid context id
1482 * @param bool $overwrite
1483 * @return bool always true or exception
9a81a606 1484 */
e922fe23
PS
1485function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1486 global $USER, $DB;
9a81a606 1487
e922fe23
PS
1488 if ($contextid instanceof context) {
1489 $context = $contextid;
1490 } else {
1491 $context = context::instance_by_id($contextid);
9a81a606 1492 }
1493
e922fe23
PS
1494 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1495 unassign_capability($capability, $roleid, $context->id);
1496 return true;
9a81a606 1497 }
1498
e922fe23 1499 $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
9a81a606 1500
e922fe23
PS
1501 if ($existing and !$overwrite) { // We want to keep whatever is there already
1502 return true;
9a81a606 1503 }
1504
e922fe23
PS
1505 $cap = new stdClass();
1506 $cap->contextid = $context->id;
1507 $cap->roleid = $roleid;
1508 $cap->capability = $capability;
1509 $cap->permission = $permission;
1510 $cap->timemodified = time();
1511 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
e92c286c 1512
e922fe23
PS
1513 if ($existing) {
1514 $cap->id = $existing->id;
1515 $DB->update_record('role_capabilities', $cap);
1516 } else {
1517 if ($DB->record_exists('context', array('id'=>$context->id))) {
1518 $DB->insert_record('role_capabilities', $cap);
1519 }
9a81a606 1520 }
e922fe23 1521 return true;
9a81a606 1522}
1523
17b0efae 1524/**
e922fe23 1525 * Unassign a capability from a role.
17b0efae 1526 *
e922fe23
PS
1527 * NOTE: use $context->mark_dirty() after this
1528 *
1529 * @param string $capability the name of the capability
1530 * @param int $roleid the role id
1531 * @param int|context $contextid null means all contexts
1532 * @return boolean true or exception
17b0efae 1533 */
e922fe23 1534function unassign_capability($capability, $roleid, $contextid = null) {
5a4e7398 1535 global $DB;
17b0efae 1536
e922fe23
PS
1537 if (!empty($contextid)) {
1538 if ($contextid instanceof context) {
1539 $context = $contextid;
1540 } else {
1541 $context = context::instance_by_id($contextid);
1542 }
1543 // delete from context rel, if this is the last override in this context
1544 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1545 } else {
1546 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
17b0efae 1547 }
1548 return true;
1549}
1550
00653161 1551/**
e922fe23 1552 * Get the roles that have a given capability assigned to it
00653161 1553 *
e922fe23
PS
1554 * This function does not resolve the actual permission of the capability.
1555 * It just checks for permissions and overrides.
1556 * Use get_roles_with_cap_in_context() if resolution is required.
1557 *
34223e03
SH
1558 * @param string $capability capability name (string)
1559 * @param string $permission optional, the permission defined for this capability
e922fe23 1560 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
34223e03 1561 * @param stdClass $context null means any
e922fe23 1562 * @return array of role records
00653161 1563 */
e922fe23
PS
1564function get_roles_with_capability($capability, $permission = null, $context = null) {
1565 global $DB;
00653161 1566
e922fe23
PS
1567 if ($context) {
1568 $contexts = $context->get_parent_context_ids(true);
1569 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1570 $contextsql = "AND rc.contextid $insql";
1571 } else {
1572 $params = array();
1573 $contextsql = '';
00653161 1574 }
1575
e922fe23
PS
1576 if ($permission) {
1577 $permissionsql = " AND rc.permission = :permission";
1578 $params['permission'] = $permission;
1579 } else {
1580 $permissionsql = '';
00653161 1581 }
e922fe23
PS
1582
1583 $sql = "SELECT r.*
1584 FROM {role} r
1585 WHERE r.id IN (SELECT rc.roleid
1586 FROM {role_capabilities} rc
1587 WHERE rc.capability = :capname
1588 $contextsql
1589 $permissionsql)";
1590 $params['capname'] = $capability;
1591
1592
1593 return $DB->get_records_sql($sql, $params);
00653161 1594}
1595
bbbf2d40 1596/**
e922fe23 1597 * This function makes a role-assignment (a role for a user in a particular context)
46808d7c 1598 *
e922fe23
PS
1599 * @param int $roleid the role of the id
1600 * @param int $userid userid
1601 * @param int|context $contextid id of the context
1602 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1603 * @param int $itemid id of enrolment/auth plugin
1604 * @param string $timemodified defaults to current time
1605 * @return int new/existing id of the assignment
bbbf2d40 1606 */
e922fe23
PS
1607function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1608 global $USER, $DB;
d9a35e12 1609
e922fe23
PS
1610 // first of all detect if somebody is using old style parameters
1611 if ($contextid === 0 or is_numeric($component)) {
1612 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
8ba412da 1613 }
1614
e922fe23
PS
1615 // now validate all parameters
1616 if (empty($roleid)) {
1617 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
a36a3a3f 1618 }
1619
e922fe23
PS
1620 if (empty($userid)) {
1621 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1622 }
d0e538ba 1623
e922fe23
PS
1624 if ($itemid) {
1625 if (strpos($component, '_') === false) {
1626 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
65bcf17b 1627 }
e922fe23
PS
1628 } else {
1629 $itemid = 0;
1630 if ($component !== '' and strpos($component, '_') === false) {
1631 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
65bcf17b 1632 }
e922fe23 1633 }
65bcf17b 1634
e922fe23
PS
1635 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1636 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1637 }
65bcf17b 1638
e922fe23
PS
1639 if ($contextid instanceof context) {
1640 $context = $contextid;
1641 } else {
1642 $context = context::instance_by_id($contextid, MUST_EXIST);
e5605780 1643 }
1644
e922fe23
PS
1645 if (!$timemodified) {
1646 $timemodified = time();
1647 }
65bcf17b 1648
e968c5f9 1649 // Check for existing entry
e922fe23 1650 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
65bcf17b 1651
e922fe23
PS
1652 if ($ras) {
1653 // role already assigned - this should not happen
1654 if (count($ras) > 1) {
1655 // very weird - remove all duplicates!
1656 $ra = array_shift($ras);
1657 foreach ($ras as $r) {
1658 $DB->delete_records('role_assignments', array('id'=>$r->id));
1659 }
1660 } else {
1661 $ra = reset($ras);
65bcf17b 1662 }
e5605780 1663
e922fe23
PS
1664 // actually there is no need to update, reset anything or trigger any event, so just return
1665 return $ra->id;
1666 }
5a4e7398 1667
e922fe23
PS
1668 // Create a new entry
1669 $ra = new stdClass();
1670 $ra->roleid = $roleid;
1671 $ra->contextid = $context->id;
1672 $ra->userid = $userid;
1673 $ra->component = $component;
1674 $ra->itemid = $itemid;
1675 $ra->timemodified = $timemodified;
1676 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
65bcf17b 1677
e922fe23 1678 $ra->id = $DB->insert_record('role_assignments', $ra);
65bcf17b 1679
e922fe23
PS
1680 // mark context as dirty - again expensive, but needed
1681 $context->mark_dirty();
65bcf17b 1682
e922fe23
PS
1683 if (!empty($USER->id) && $USER->id == $userid) {
1684 // If the user is the current user, then do full reload of capabilities too.
1685 reload_all_capabilities();
ccfc5ecc 1686 }
0468976c 1687
e922fe23 1688 events_trigger('role_assigned', $ra);
bbbf2d40 1689
e922fe23
PS
1690 return $ra->id;
1691}
cee0901c 1692
340ea4e8 1693/**
e922fe23 1694 * Removes one role assignment
cc3edaa4 1695 *
e922fe23
PS
1696 * @param int $roleid
1697 * @param int $userid
1698 * @param int|context $contextid
1699 * @param string $component
1700 * @param int $itemid
1701 * @return void
340ea4e8 1702 */
e922fe23
PS
1703function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1704 // first make sure the params make sense
1705 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1706 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
340ea4e8 1707 }
1708
e922fe23
PS
1709 if ($itemid) {
1710 if (strpos($component, '_') === false) {
1711 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1712 }
1713 } else {
1714 $itemid = 0;
1715 if ($component !== '' and strpos($component, '_') === false) {
1716 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1717 }
340ea4e8 1718 }
1719
e922fe23 1720 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
340ea4e8 1721}
1722
8737be58 1723/**
e922fe23
PS
1724 * Removes multiple role assignments, parameters may contain:
1725 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
cc3edaa4 1726 *
e922fe23
PS
1727 * @param array $params role assignment parameters
1728 * @param bool $subcontexts unassign in subcontexts too
1729 * @param bool $includemanual include manual role assignments too
1730 * @return void
01a2ce80 1731 */
e922fe23
PS
1732function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1733 global $USER, $CFG, $DB;
01a2ce80 1734
e922fe23
PS
1735 if (!$params) {
1736 throw new coding_exception('Missing parameters in role_unsassign_all() call');
1737 }
01a2ce80 1738
e922fe23
PS
1739 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1740 foreach ($params as $key=>$value) {
1741 if (!in_array($key, $allowed)) {
1742 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
01a2ce80
PS
1743 }
1744 }
1745
e922fe23
PS
1746 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1747 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
28765cfc 1748 }
e922fe23
PS
1749
1750 if ($includemanual) {
1751 if (!isset($params['component']) or $params['component'] === '') {
1752 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1753 }
35716b86
PS
1754 }
1755
e922fe23
PS
1756 if ($subcontexts) {
1757 if (empty($params['contextid'])) {
1758 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1759 }
35716b86
PS
1760 }
1761
e922fe23
PS
1762 $ras = $DB->get_records('role_assignments', $params);
1763 foreach($ras as $ra) {
1764 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1765 if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1766 // this is a bit expensive but necessary
1767 $context->mark_dirty();
34223e03 1768 // If the user is the current user, then do full reload of capabilities too.
e922fe23
PS
1769 if (!empty($USER->id) && $USER->id == $ra->userid) {
1770 reload_all_capabilities();
1771 }
1772 }
1773 events_trigger('role_unassigned', $ra);
35716b86 1774 }
e922fe23
PS
1775 unset($ras);
1776
1777 // process subcontexts
1778 if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1779 if ($params['contextid'] instanceof context) {
1780 $context = $params['contextid'];
1781 } else {
1782 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1783 }
35716b86 1784
e922fe23
PS
1785 if ($context) {
1786 $contexts = $context->get_child_contexts();
1787 $mparams = $params;
1788 foreach($contexts as $context) {
1789 $mparams['contextid'] = $context->id;
1790 $ras = $DB->get_records('role_assignments', $mparams);
1791 foreach($ras as $ra) {
1792 $DB->delete_records('role_assignments', array('id'=>$ra->id));
1793 // this is a bit expensive but necessary
1794 $context->mark_dirty();
34223e03 1795 // If the user is the current user, then do full reload of capabilities too.
e922fe23
PS
1796 if (!empty($USER->id) && $USER->id == $ra->userid) {
1797 reload_all_capabilities();
1798 }
1799 events_trigger('role_unassigned', $ra);
1800 }
1801 }
1802 }
35716b86
PS
1803 }
1804
e922fe23
PS
1805 // do this once more for all manual role assignments
1806 if ($includemanual) {
1807 $params['component'] = '';
1808 role_unassign_all($params, $subcontexts, false);
1809 }
35716b86
PS
1810}
1811
e922fe23
PS
1812/**
1813 * Determines if a user is currently logged in
1814 *
f76249cc
PS
1815 * @category access
1816 *
e922fe23
PS
1817 * @return bool
1818 */
1819function isloggedin() {
1820 global $USER;
bbbf2d40 1821
e922fe23
PS
1822 return (!empty($USER->id));
1823}
bbbf2d40 1824
cee0901c 1825/**
e922fe23 1826 * Determines if a user is logged in as real guest user with username 'guest'.
cc3edaa4 1827 *
f76249cc
PS
1828 * @category access
1829 *
e922fe23
PS
1830 * @param int|object $user mixed user object or id, $USER if not specified
1831 * @return bool true if user is the real guest user, false if not logged in or other user
bbbf2d40 1832 */
e922fe23
PS
1833function isguestuser($user = null) {
1834 global $USER, $DB, $CFG;
eef868d1 1835
e922fe23
PS
1836 // make sure we have the user id cached in config table, because we are going to use it a lot
1837 if (empty($CFG->siteguest)) {
1838 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1839 // guest does not exist yet, weird
1840 return false;
1841 }
1842 set_config('siteguest', $guestid);
4f0c2d00 1843 }
e922fe23
PS
1844 if ($user === null) {
1845 $user = $USER;
4f0c2d00
PS
1846 }
1847
e922fe23
PS
1848 if ($user === null) {
1849 // happens when setting the $USER
1850 return false;
31f26796 1851
e922fe23
PS
1852 } else if (is_numeric($user)) {
1853 return ($CFG->siteguest == $user);
eef868d1 1854
e922fe23
PS
1855 } else if (is_object($user)) {
1856 if (empty($user->id)) {
1857 return false; // not logged in means is not be guest
1858 } else {
1859 return ($CFG->siteguest == $user->id);
1860 }
b5959f30 1861
e922fe23
PS
1862 } else {
1863 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1864 }
bbbf2d40 1865}
1866
8420bee9 1867/**
e922fe23 1868 * Does user have a (temporary or real) guest access to course?
cc3edaa4 1869 *
f76249cc
PS
1870 * @category access
1871 *
e922fe23
PS
1872 * @param context $context
1873 * @param stdClass|int $user
1874 * @return bool
8420bee9 1875 */
e922fe23
PS
1876function is_guest(context $context, $user = null) {
1877 global $USER;
c421ad4b 1878
e922fe23
PS
1879 // first find the course context
1880 $coursecontext = $context->get_course_context();
c421ad4b 1881
e922fe23
PS
1882 // make sure there is a real user specified
1883 if ($user === null) {
1884 $userid = isset($USER->id) ? $USER->id : 0;
1885 } else {
1886 $userid = is_object($user) ? $user->id : $user;
1887 }
60ace1e1 1888
e922fe23
PS
1889 if (isguestuser($userid)) {
1890 // can not inspect or be enrolled
1891 return true;
1892 }
5a4e7398 1893
e922fe23
PS
1894 if (has_capability('moodle/course:view', $coursecontext, $user)) {
1895 // viewing users appear out of nowhere, they are neither guests nor participants
1896 return false;
1897 }
5a4e7398 1898
e922fe23
PS
1899 // consider only real active enrolments here
1900 if (is_enrolled($coursecontext, $user, '', true)) {
1901 return false;
1902 }
8420bee9 1903
4f0c2d00 1904 return true;
8420bee9 1905}
1906
bbbf2d40 1907/**
e922fe23
PS
1908 * Returns true if the user has moodle/course:view capability in the course,
1909 * this is intended for admins, managers (aka small admins), inspectors, etc.
46808d7c 1910 *
f76249cc
PS
1911 * @category access
1912 *
e922fe23 1913 * @param context $context
34223e03 1914 * @param int|stdClass $user if null $USER is used
e922fe23
PS
1915 * @param string $withcapability extra capability name
1916 * @return bool
bbbf2d40 1917 */
e922fe23
PS
1918function is_viewing(context $context, $user = null, $withcapability = '') {
1919 // first find the course context
1920 $coursecontext = $context->get_course_context();
eef868d1 1921
e922fe23
PS
1922 if (isguestuser($user)) {
1923 // can not inspect
1924 return false;
98882637 1925 }
eef868d1 1926
e922fe23
PS
1927 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1928 // admins are allowed to inspect courses
1929 return false;
e7876c1e 1930 }
1931
e922fe23
PS
1932 if ($withcapability and !has_capability($withcapability, $context, $user)) {
1933 // site admins always have the capability, but the enrolment above blocks
1934 return false;
e7876c1e 1935 }
e922fe23 1936
4f0c2d00 1937 return true;
bbbf2d40 1938}
1939
bbbf2d40 1940/**
e922fe23
PS
1941 * Returns true if user is enrolled (is participating) in course
1942 * this is intended for students and teachers.
117bd748 1943 *
bbfdff34
PS
1944 * Since 2.2 the result for active enrolments and current user are cached.
1945 *
f76249cc
PS
1946 * @package core_enrol
1947 * @category access
1948 *
e922fe23 1949 * @param context $context
34223e03 1950 * @param int|stdClass $user if null $USER is used, otherwise user object or id expected
e922fe23
PS
1951 * @param string $withcapability extra capability name
1952 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1953 * @return bool
bbbf2d40 1954 */
e922fe23
PS
1955function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1956 global $USER, $DB;
eef868d1 1957
e922fe23
PS
1958 // first find the course context
1959 $coursecontext = $context->get_course_context();
1960
1961 // make sure there is a real user specified
1962 if ($user === null) {
1963 $userid = isset($USER->id) ? $USER->id : 0;
98882637 1964 } else {
e922fe23 1965 $userid = is_object($user) ? $user->id : $user;
98882637 1966 }
5a4e7398 1967
e922fe23
PS
1968 if (empty($userid)) {
1969 // not-logged-in!
1970 return false;
1971 } else if (isguestuser($userid)) {
1972 // guest account can not be enrolled anywhere
1973 return false;
448aad7f
PS
1974 }
1975
e922fe23
PS
1976 if ($coursecontext->instanceid == SITEID) {
1977 // everybody participates on frontpage
ec7a8b79 1978 } else {
bbfdff34
PS
1979 // try cached info first - the enrolled flag is set only when active enrolment present
1980 if ($USER->id == $userid) {
1981 $coursecontext->reload_if_dirty();
1982 if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1983 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
a386e6e0
ARN
1984 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1985 return false;
1986 }
bbfdff34 1987 return true;
e922fe23 1988 }
e922fe23 1989 }
bbfdff34
PS
1990 }
1991
1992 if ($onlyactive) {
1993 // look for active enrolments only
1994 $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1995
1996 if ($until === false) {
e922fe23
PS
1997 return false;
1998 }
eef868d1 1999
bbfdff34
PS
2000 if ($USER->id == $userid) {
2001 if ($until == 0) {
2002 $until = ENROL_MAX_TIMESTAMP;
2003 }
2004 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
2005 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
2006 unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
2007 remove_temp_course_roles($coursecontext);
2008 }
2009 }
2010
e922fe23
PS
2011 } else {
2012 // any enrolment is good for us here, even outdated, disabled or inactive
2013 $sql = "SELECT 'x'
2014 FROM {user_enrolments} ue
2015 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2016 JOIN {user} u ON u.id = ue.userid
2017 WHERE ue.userid = :userid AND u.deleted = 0";
2018 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2019 if (!$DB->record_exists_sql($sql, $params)) {
2020 return false;
2021 }
2022 }
2023 }
bbbf2d40 2024
e922fe23
PS
2025 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2026 return false;
2027 }
f33e1ed4 2028
e922fe23 2029 return true;
bbbf2d40 2030}
2031
bbbf2d40 2032/**
e922fe23 2033 * Returns true if the user is able to access the course.
117bd748 2034 *
e922fe23
PS
2035 * This function is in no way, shape, or form a substitute for require_login.
2036 * It should only be used in circumstances where it is not possible to call require_login
2037 * such as the navigation.
2038 *
2039 * This function checks many of the methods of access to a course such as the view
2040 * capability, enrollments, and guest access. It also makes use of the cache
2041 * generated by require_login for guest access.
2042 *
2043 * The flags within the $USER object that are used here should NEVER be used outside
2044 * of this function can_access_course and require_login. Doing so WILL break future
2045 * versions.
2046 *
1344b0ca
PS
2047 * @param stdClass $course record
2048 * @param stdClass|int|null $user user record or id, current user if null
e922fe23
PS
2049 * @param string $withcapability Check for this capability as well.
2050 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
e922fe23
PS
2051 * @return boolean Returns true if the user is able to access the course
2052 */
1344b0ca 2053function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
e922fe23 2054 global $DB, $USER;
eef868d1 2055
1344b0ca
PS
2056 // this function originally accepted $coursecontext parameter
2057 if ($course instanceof context) {
2058 if ($course instanceof context_course) {
2059 debugging('deprecated context parameter, please use $course record');
2060 $coursecontext = $course;
2061 $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2062 } else {
2063 debugging('Invalid context parameter, please use $course record');
2064 return false;
2065 }
2066 } else {
2067 $coursecontext = context_course::instance($course->id);
2068 }
2069
2070 if (!isset($USER->id)) {
2071 // should never happen
2072 $USER->id = 0;
c90e6b46 2073 debugging('Course access check being performed on a user with no ID.', DEBUG_DEVELOPER);
1344b0ca
PS
2074 }
2075
2076 // make sure there is a user specified
2077 if ($user === null) {
2078 $userid = $USER->id;
2079 } else {
2080 $userid = is_object($user) ? $user->id : $user;
2081 }
2082 unset($user);
bbbf2d40 2083
1344b0ca
PS
2084 if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2085 return false;
2086 }
2087
2088 if ($userid == $USER->id) {
2089 if (!empty($USER->access['rsw'][$coursecontext->path])) {
2090 // the fact that somebody switched role means they can access the course no matter to what role they switched
2091 return true;
2092 }
2093 }
2094
0f14c827 2095 if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
1344b0ca
PS
2096 return false;
2097 }
2098
2099 if (is_viewing($coursecontext, $userid)) {
e922fe23 2100 return true;
bbbf2d40 2101 }
2102
1344b0ca
PS
2103 if ($userid != $USER->id) {
2104 // for performance reasons we do not verify temporary guest access for other users, sorry...
2105 return is_enrolled($coursecontext, $userid, '', $onlyactive);
2106 }
2107
0f14c827
PS
2108 // === from here we deal only with $USER ===
2109
bbfdff34
PS
2110 $coursecontext->reload_if_dirty();
2111
1344b0ca 2112 if (isset($USER->enrol['enrolled'][$course->id])) {
bbfdff34 2113 if ($USER->enrol['enrolled'][$course->id] > time()) {
1344b0ca
PS
2114 return true;
2115 }
2116 }
2117 if (isset($USER->enrol['tempguest'][$course->id])) {
bbfdff34 2118 if ($USER->enrol['tempguest'][$course->id] > time()) {
1344b0ca
PS
2119 return true;
2120 }
2121 }
7700027f 2122
bbfdff34 2123 if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
1344b0ca 2124 return true;
96608a55 2125 }
c421ad4b 2126
1344b0ca
PS
2127 // if not enrolled try to gain temporary guest access
2128 $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2129 $enrols = enrol_get_plugins(true);
2130 foreach($instances as $instance) {
2131 if (!isset($enrols[$instance->enrol])) {
2132 continue;
2133 }
bbfdff34 2134 // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
1344b0ca 2135 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
bbfdff34 2136 if ($until !== false and $until > time()) {
1344b0ca
PS
2137 $USER->enrol['tempguest'][$course->id] = $until;
2138 return true;
e922fe23 2139 }
4e5f3064 2140 }
bbfdff34
PS
2141 if (isset($USER->enrol['tempguest'][$course->id])) {
2142 unset($USER->enrol['tempguest'][$course->id]);
2143 remove_temp_course_roles($coursecontext);
2144 }
1344b0ca
PS
2145
2146 return false;
bbbf2d40 2147}
2148
bbbf2d40 2149/**
e922fe23
PS
2150 * Returns array with sql code and parameters returning all ids
2151 * of users enrolled into course.
cc3edaa4 2152 *
e922fe23
PS
2153 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2154 *
f76249cc
PS
2155 * @package core_enrol
2156 * @category access
2157 *
e922fe23
PS
2158 * @param context $context
2159 * @param string $withcapability
2160 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2161 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2162 * @return array list($sql, $params)
bbbf2d40 2163 */
e922fe23
PS
2164function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2165 global $DB, $CFG;
4f0c2d00 2166
e922fe23
PS
2167 // use unique prefix just in case somebody makes some SQL magic with the result
2168 static $i = 0;
2169 $i++;
2170 $prefix = 'eu'.$i.'_';
4f0c2d00 2171
e922fe23
PS
2172 // first find the course context
2173 $coursecontext = $context->get_course_context();
4f0c2d00 2174
e922fe23 2175 $isfrontpage = ($coursecontext->instanceid == SITEID);
4f0c2d00 2176
e922fe23
PS
2177 $joins = array();
2178 $wheres = array();
2179 $params = array();
4f0c2d00 2180
e922fe23 2181 list($contextids, $contextpaths) = get_context_info_list($context);
4f0c2d00 2182
e922fe23
PS
2183 // get all relevant capability info for all roles
2184 if ($withcapability) {
2185 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2186 $cparams['cap'] = $withcapability;
4f0c2d00 2187
e922fe23
PS
2188 $defs = array();
2189 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2190 FROM {role_capabilities} rc
2191 JOIN {context} ctx on rc.contextid = ctx.id
2192 WHERE rc.contextid $incontexts AND rc.capability = :cap";
2193 $rcs = $DB->get_records_sql($sql, $cparams);
2194 foreach ($rcs as $rc) {
2195 $defs[$rc->path][$rc->roleid] = $rc->permission;
df997f84 2196 }
4f0c2d00 2197
e922fe23
PS
2198 $access = array();
2199 if (!empty($defs)) {
2200 foreach ($contextpaths as $path) {
2201 if (empty($defs[$path])) {
2202 continue;
2203 }
2204 foreach($defs[$path] as $roleid => $perm) {
2205 if ($perm == CAP_PROHIBIT) {
2206 $access[$roleid] = CAP_PROHIBIT;
2207 continue;
2208 }
2209 if (!isset($access[$roleid])) {
2210 $access[$roleid] = (int)$perm;
2211 }
2212 }
df997f84
PS
2213 }
2214 }
4f0c2d00 2215
e922fe23
PS
2216 unset($defs);
2217
2218 // make lists of roles that are needed and prohibited
2219 $needed = array(); // one of these is enough
2220 $prohibited = array(); // must not have any of these
2221 foreach ($access as $roleid => $perm) {
2222 if ($perm == CAP_PROHIBIT) {
2223 unset($needed[$roleid]);
2224 $prohibited[$roleid] = true;
2225 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2226 $needed[$roleid] = true;
df997f84
PS
2227 }
2228 }
4f0c2d00 2229
e922fe23
PS
2230 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2231 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
4f0c2d00 2232
e922fe23 2233 $nobody = false;
df997f84 2234
e922fe23
PS
2235 if ($isfrontpage) {
2236 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2237 $nobody = true;
2238 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2239 // everybody not having prohibit has the capability
2240 $needed = array();
2241 } else if (empty($needed)) {
2242 $nobody = true;
2243 }
2244 } else {
2245 if (!empty($prohibited[$defaultuserroleid])) {
2246 $nobody = true;
2247 } else if (!empty($needed[$defaultuserroleid])) {
2248 // everybody not having prohibit has the capability
2249 $needed = array();
2250 } else if (empty($needed)) {
2251 $nobody = true;
2252 }
2253 }
4f0c2d00 2254
e922fe23
PS
2255 if ($nobody) {
2256 // nobody can match so return some SQL that does not return any results
2257 $wheres[] = "1 = 2";
4f0c2d00 2258
e922fe23 2259 } else {
4f0c2d00 2260
e922fe23
PS
2261 if ($needed) {
2262 $ctxids = implode(',', $contextids);
2263 $roleids = implode(',', array_keys($needed));
2264 $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))";
2265 }
4f0c2d00 2266
e922fe23
PS
2267 if ($prohibited) {
2268 $ctxids = implode(',', $contextids);
2269 $roleids = implode(',', array_keys($prohibited));
2270 $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))";
2271 $wheres[] = "{$prefix}ra4.id IS NULL";
2272 }
4f0c2d00 2273
e922fe23
PS
2274 if ($groupid) {
2275 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2276 $params["{$prefix}gmid"] = $groupid;
2277 }
2278 }
4f0c2d00 2279
e922fe23
PS
2280 } else {
2281 if ($groupid) {
2282 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2283 $params["{$prefix}gmid"] = $groupid;
4f0c2d00 2284 }
e922fe23 2285 }
4f0c2d00 2286
e922fe23
PS
2287 $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2288 $params["{$prefix}guestid"] = $CFG->siteguest;
2289
2290 if ($isfrontpage) {
2291 // all users are "enrolled" on the frontpage
4f0c2d00 2292 } else {
e922fe23
PS
2293 $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2294 $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2295 $params[$prefix.'courseid'] = $coursecontext->instanceid;
2296
2297 if ($onlyactive) {
2298 $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2299 $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2300 $now = round(time(), -2); // rounding helps caching in DB
2301 $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2302 $prefix.'active'=>ENROL_USER_ACTIVE,
2303 $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2304 }
4f0c2d00 2305 }
e922fe23
PS
2306
2307 $joins = implode("\n", $joins);
2308 $wheres = "WHERE ".implode(" AND ", $wheres);
2309
2310 $sql = "SELECT DISTINCT {$prefix}u.id
2311 FROM {user} {$prefix}u
2312 $joins
2313 $wheres";
2314
2315 return array($sql, $params);
4f0c2d00
PS
2316}
2317
2318/**
e922fe23 2319 * Returns list of users enrolled into course.
4f0c2d00 2320 *
f76249cc
PS
2321 * @package core_enrol
2322 * @category access
2323 *
e922fe23
PS
2324 * @param context $context
2325 * @param string $withcapability
2326 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2327 * @param string $userfields requested user record fields
2328 * @param string $orderby
2329 * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2330 * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
38c1dd19 2331 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
e922fe23 2332 * @return array of user records
4f0c2d00 2333 */
38c1dd19
RT
2334function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = null,
2335 $limitfrom = 0, $limitnum = 0, $onlyactive = false) {
e922fe23 2336 global $DB;
5fd9e798 2337
38c1dd19 2338 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
e922fe23
PS
2339 $sql = "SELECT $userfields
2340 FROM {user} u
2341 JOIN ($esql) je ON je.id = u.id
2342 WHERE u.deleted = 0";
4f0c2d00 2343
e922fe23
PS
2344 if ($orderby) {
2345 $sql = "$sql ORDER BY $orderby";
4f0c2d00 2346 } else {
9695ff81
TH
2347 list($sort, $sortparams) = users_order_by_sql('u');
2348 $sql = "$sql ORDER BY $sort";
2349 $params = array_merge($params, $sortparams);
4f0c2d00
PS
2350 }
2351
e922fe23
PS
2352 return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2353}
4f0c2d00 2354
e922fe23
PS
2355/**
2356 * Counts list of users enrolled into course (as per above function)
2357 *
f76249cc
PS
2358 * @package core_enrol
2359 * @category access
2360 *
e922fe23
PS
2361 * @param context $context
2362 * @param string $withcapability
2363 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
38c1dd19 2364 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
e922fe23
PS
2365 * @return array of user records
2366 */
38c1dd19 2367function count_enrolled_users(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
e922fe23 2368 global $DB;
4f0c2d00 2369
38c1dd19 2370 list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid, $onlyactive);
e922fe23
PS
2371 $sql = "SELECT count(u.id)
2372 FROM {user} u
2373 JOIN ($esql) je ON je.id = u.id
2374 WHERE u.deleted = 0";
2375
2376 return $DB->count_records_sql($sql, $params);
2377}
2378
2379/**
2380 * Loads the capability definitions for the component (from file).
2381 *
2382 * Loads the capability definitions for the component (from file). If no
2383 * capabilities are defined for the component, we simply return an empty array.
2384 *
f76249cc 2385 * @access private
e922fe23
PS
2386 * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2387 * @return array array of capabilities
2388 */
2389function load_capability_def($component) {
2390 $defpath = get_component_directory($component).'/db/access.php';
2391
2392 $capabilities = array();
2393 if (file_exists($defpath)) {
2394 require($defpath);
2395 if (!empty(${$component.'_capabilities'})) {
2396 // BC capability array name
2397 // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
99ddfdf4 2398 debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
e922fe23
PS
2399 $capabilities = ${$component.'_capabilities'};
2400 }
4f0c2d00
PS
2401 }
2402
e922fe23 2403 return $capabilities;
4f0c2d00
PS
2404}
2405
e922fe23
PS
2406/**
2407 * Gets the capabilities that have been cached in the database for this component.
2408 *
f76249cc 2409 * @access private
e922fe23
PS
2410 * @param string $component - examples: 'moodle', 'mod_forum'
2411 * @return array array of capabilities
2412 */
2413function get_cached_capabilities($component = 'moodle') {
2414 global $DB;
2415 return $DB->get_records('capabilities', array('component'=>$component));
2416}
4f0c2d00
PS
2417
2418/**
e922fe23 2419 * Returns default capabilities for given role archetype.
4f0c2d00 2420 *
e922fe23
PS
2421 * @param string $archetype role archetype
2422 * @return array
4f0c2d00 2423 */
e922fe23
PS
2424function get_default_capabilities($archetype) {
2425 global $DB;
4f0c2d00 2426
e922fe23
PS
2427 if (!$archetype) {
2428 return array();
4f0c2d00
PS
2429 }
2430
e922fe23
PS
2431 $alldefs = array();
2432 $defaults = array();
2433 $components = array();
2434 $allcaps = $DB->get_records('capabilities');
4f0c2d00 2435
e922fe23
PS
2436 foreach ($allcaps as $cap) {
2437 if (!in_array($cap->component, $components)) {
2438 $components[] = $cap->component;
2439 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2440 }
2441 }
2442 foreach($alldefs as $name=>$def) {
2443 // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2444 if (isset($def['archetypes'])) {
2445 if (isset($def['archetypes'][$archetype])) {
2446 $defaults[$name] = $def['archetypes'][$archetype];
2447 }
2448 // 'legacy' is for backward compatibility with 1.9 access.php
2449 } else {
2450 if (isset($def['legacy'][$archetype])) {
2451 $defaults[$name] = $def['legacy'][$archetype];
2452 }
2453 }
4f0c2d00
PS
2454 }
2455
e922fe23 2456 return $defaults;
4f0c2d00
PS
2457}
2458
2459/**
e922fe23
PS
2460 * Reset role capabilities to default according to selected role archetype.
2461 * If no archetype selected, removes all capabilities.
4f0c2d00 2462 *
e922fe23
PS
2463 * @param int $roleid
2464 * @return void
4f0c2d00 2465 */
e922fe23
PS
2466function reset_role_capabilities($roleid) {
2467 global $DB;
4f0c2d00 2468
e922fe23
PS
2469 $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2470 $defaultcaps = get_default_capabilities($role->archetype);
4f0c2d00 2471
e922fe23 2472 $systemcontext = context_system::instance();
df997f84 2473
e922fe23 2474 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
4f0c2d00 2475
e922fe23
PS
2476 foreach($defaultcaps as $cap=>$permission) {
2477 assign_capability($cap, $permission, $roleid, $systemcontext->id);
4f0c2d00 2478 }
4f0c2d00
PS
2479}
2480
ed1d72ea 2481/**
e922fe23
PS
2482 * Updates the capabilities table with the component capability definitions.
2483 * If no parameters are given, the function updates the core moodle
2484 * capabilities.
ed1d72ea 2485 *
e922fe23
PS
2486 * Note that the absence of the db/access.php capabilities definition file
2487 * will cause any stored capabilities for the component to be removed from
2488 * the database.
ed1d72ea 2489 *
f76249cc 2490 * @access private
e922fe23
PS
2491 * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2492 * @return boolean true if success, exception in case of any problems
ed1d72ea 2493 */
e922fe23
PS
2494function update_capabilities($component = 'moodle') {
2495 global $DB, $OUTPUT;
ed1d72ea 2496
e922fe23 2497 $storedcaps = array();
ed1d72ea 2498
e922fe23
PS
2499 $filecaps = load_capability_def($component);
2500 foreach($filecaps as $capname=>$unused) {
2501 if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2502 debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2503 }
ed1d72ea
SH
2504 }
2505
e922fe23
PS
2506 $cachedcaps = get_cached_capabilities($component);
2507 if ($cachedcaps) {
2508 foreach ($cachedcaps as $cachedcap) {
2509 array_push($storedcaps, $cachedcap->name);
2510 // update risk bitmasks and context levels in existing capabilities if needed
2511 if (array_key_exists($cachedcap->name, $filecaps)) {
2512 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2513 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2514 }
2515 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2516 $updatecap = new stdClass();
2517 $updatecap->id = $cachedcap->id;
2518 $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2519 $DB->update_record('capabilities', $updatecap);
2520 }
2521 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2522 $updatecap = new stdClass();
2523 $updatecap->id = $cachedcap->id;
2524 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2525 $DB->update_record('capabilities', $updatecap);
2526 }
ed1d72ea 2527
e922fe23
PS
2528 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2529 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2530 }
2531 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2532 $updatecap = new stdClass();
2533 $updatecap->id = $cachedcap->id;
2534 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2535 $DB->update_record('capabilities', $updatecap);
2536 }
ed1d72ea 2537 }
e922fe23
PS
2538 }
2539 }
2540
2541 // Are there new capabilities in the file definition?
2542 $newcaps = array();
2543
2544 foreach ($filecaps as $filecap => $def) {
2545 if (!$storedcaps ||
2546 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2547 if (!array_key_exists('riskbitmask', $def)) {
2548 $def['riskbitmask'] = 0; // no risk if not specified
ed1d72ea 2549 }
e922fe23 2550 $newcaps[$filecap] = $def;
ed1d72ea
SH
2551 }
2552 }
e922fe23 2553 // Add new capabilities to the stored definition.
a36e170f 2554 $existingcaps = $DB->get_records_menu('capabilities', array(), 'id', 'id, name');
e922fe23
PS
2555 foreach ($newcaps as $capname => $capdef) {
2556 $capability = new stdClass();
2557 $capability->name = $capname;
2558 $capability->captype = $capdef['captype'];
2559 $capability->contextlevel = $capdef['contextlevel'];
2560 $capability->component = $component;
2561 $capability->riskbitmask = $capdef['riskbitmask'];
ed1d72ea 2562
e922fe23
PS
2563 $DB->insert_record('capabilities', $capability, false);
2564
a36e170f 2565 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $existingcaps)){
e922fe23
PS
2566 if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2567 foreach ($rolecapabilities as $rolecapability){
2568 //assign_capability will update rather than insert if capability exists
2569 if (!assign_capability($capname, $rolecapability->permission,
2570 $rolecapability->roleid, $rolecapability->contextid, true)){
2571 echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2572 }
2573 }
2574 }
2575 // we ignore archetype key if we have cloned permissions
2576 } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2577 assign_legacy_capabilities($capname, $capdef['archetypes']);
2578 // 'legacy' is for backward compatibility with 1.9 access.php
2579 } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2580 assign_legacy_capabilities($capname, $capdef['legacy']);
ed1d72ea
SH
2581 }
2582 }
e922fe23
PS
2583 // Are there any capabilities that have been removed from the file
2584 // definition that we need to delete from the stored capabilities and
2585 // role assignments?
2586 capabilities_cleanup($component, $filecaps);
2587
2588 // reset static caches
2589 accesslib_clear_all_caches(false);
2590
2591 return true;
ed1d72ea
SH
2592}
2593
4f0c2d00 2594/**
e922fe23
PS
2595 * Deletes cached capabilities that are no longer needed by the component.
2596 * Also unassigns these capabilities from any roles that have them.
df997f84 2597 *
f76249cc 2598 * @access private
e922fe23
PS
2599 * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2600 * @param array $newcapdef array of the new capability definitions that will be
2601 * compared with the cached capabilities
2602 * @return int number of deprecated capabilities that have been removed
4f0c2d00 2603 */
e922fe23
PS
2604function capabilities_cleanup($component, $newcapdef = null) {
2605 global $DB;
4f0c2d00 2606
e922fe23 2607 $removedcount = 0;
4f0c2d00 2608
e922fe23
PS
2609 if ($cachedcaps = get_cached_capabilities($component)) {
2610 foreach ($cachedcaps as $cachedcap) {
2611 if (empty($newcapdef) ||
2612 array_key_exists($cachedcap->name, $newcapdef) === false) {
4f0c2d00 2613
e922fe23
PS
2614 // Remove from capabilities cache.
2615 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2616 $removedcount++;
2617 // Delete from roles.
2618 if ($roles = get_roles_with_capability($cachedcap->name)) {
2619 foreach($roles as $role) {
2620 if (!unassign_capability($cachedcap->name, $role->id)) {
2621 print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2622 }
2623 }
2624 }
2625 } // End if.
2626 }
2627 }
2628 return $removedcount;
2629}
2630
e922fe23
PS
2631/**
2632 * Returns an array of all the known types of risk
2633 * The array keys can be used, for example as CSS class names, or in calls to
2634 * print_risk_icon. The values are the corresponding RISK_ constants.
2635 *
2636 * @return array all the known types of risk.
2637 */
2638function get_all_risks() {
2639 return array(
2640 'riskmanagetrust' => RISK_MANAGETRUST,
2641 'riskconfig' => RISK_CONFIG,
2642 'riskxss' => RISK_XSS,
2643 'riskpersonal' => RISK_PERSONAL,
2644 'riskspam' => RISK_SPAM,
2645 'riskdataloss' => RISK_DATALOSS,
2646 );
2647}
2648
2649/**
2650 * Return a link to moodle docs for a given capability name
2651 *
f76249cc 2652 * @param stdClass $capability a capability - a row from the mdl_capabilities table.
e922fe23
PS
2653 * @return string the human-readable capability name as a link to Moodle Docs.
2654 */
2655function get_capability_docs_link($capability) {
2656 $url = get_docs_url('Capabilities/' . $capability->name);
2657 return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2658}
2659
2660/**
2661 * This function pulls out all the resolved capabilities (overrides and
2662 * defaults) of a role used in capability overrides in contexts at a given
2663 * context.
2664 *
e922fe23 2665 * @param int $roleid
34223e03 2666 * @param context $context
e922fe23 2667 * @param string $cap capability, optional, defaults to ''
34223e03 2668 * @return array Array of capabilities
e922fe23
PS
2669 */
2670function role_context_capabilities($roleid, context $context, $cap = '') {
2671 global $DB;
2672
2673 $contexts = $context->get_parent_context_ids(true);
2674 $contexts = '('.implode(',', $contexts).')';
2675
2676 $params = array($roleid);
2677
2678 if ($cap) {
2679 $search = " AND rc.capability = ? ";
2680 $params[] = $cap;
2681 } else {
2682 $search = '';
2683 }
2684
2685 $sql = "SELECT rc.*
2686 FROM {role_capabilities} rc, {context} c
2687 WHERE rc.contextid in $contexts
2688 AND rc.roleid = ?
2689 AND rc.contextid = c.id $search
2690 ORDER BY c.contextlevel DESC, rc.capability DESC";
2691
2692 $capabilities = array();
2693
2694 if ($records = $DB->get_records_sql($sql, $params)) {
2695 // We are traversing via reverse order.
2696 foreach ($records as $record) {
2697 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2698 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2699 $capabilities[$record->capability] = $record->permission;
2700 }
2701 }
2702 }
2703 return $capabilities;
2704}
2705
2706/**
2707 * Constructs array with contextids as first parameter and context paths,
2708 * in both cases bottom top including self.
2709 *
f76249cc 2710 * @access private
e922fe23
PS
2711 * @param context $context
2712 * @return array
2713 */
2714function get_context_info_list(context $context) {
2715 $contextids = explode('/', ltrim($context->path, '/'));
2716 $contextpaths = array();
2717 $contextids2 = $contextids;
2718 while ($contextids2) {
2719 $contextpaths[] = '/' . implode('/', $contextids2);
2720 array_pop($contextids2);
2721 }
2722 return array($contextids, $contextpaths);
2723}
2724
2725/**
2726 * Check if context is the front page context or a context inside it
2727 *
2728 * Returns true if this context is the front page context, or a context inside it,
2729 * otherwise false.
2730 *
2731 * @param context $context a context object.
2732 * @return bool
2733 */
2734function is_inside_frontpage(context $context) {
2735 $frontpagecontext = context_course::instance(SITEID);
2736 return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2737}
2738
2739/**
2740 * Returns capability information (cached)
2741 *
2742 * @param string $capabilityname
f76249cc 2743 * @return stdClass or null if capability not found
e922fe23
PS
2744 */
2745function get_capability_info($capabilityname) {
2746 global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2747
2748 //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2749
2750 if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2751 $ACCESSLIB_PRIVATE->capabilities = array();
2752 $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2753 foreach ($caps as $cap) {
2754 $capname = $cap->name;
2755 unset($cap->id);
2756 unset($cap->name);
2757 $cap->riskbitmask = (int)$cap->riskbitmask;
2758 $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2759 }
2760 }
2761
2762 return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2763}
2764
2765/**
2766 * Returns the human-readable, translated version of the capability.
2767 * Basically a big switch statement.
2768 *
2769 * @param string $capabilityname e.g. mod/choice:readresponses
2770 * @return string
2771 */
2772function get_capability_string($capabilityname) {
2773
2774 // Typical capability name is 'plugintype/pluginname:capabilityname'
2775 list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2776
2777 if ($type === 'moodle') {
2778 $component = 'core_role';
2779 } else if ($type === 'quizreport') {
2780 //ugly hack!!
2781 $component = 'quiz_'.$name;
2782 } else {
2783 $component = $type.'_'.$name;
2784 }
2785
2786 $stringname = $name.':'.$capname;
2787
2788 if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2789 return get_string($stringname, $component);
2790 }
2791
2792 $dir = get_component_directory($component);
2793 if (!file_exists($dir)) {
2794 // plugin broken or does not exist, do not bother with printing of debug message
2795 return $capabilityname.' ???';
2796 }
2797
2798 // something is wrong in plugin, better print debug
2799 return get_string($stringname, $component);
2800}
2801
2802/**
2803 * This gets the mod/block/course/core etc strings.
2804 *
2805 * @param string $component
2806 * @param int $contextlevel
2807 * @return string|bool String is success, false if failed
2808 */
2809function get_component_string($component, $contextlevel) {
2810
2811 if ($component === 'moodle' or $component === 'core') {
2812 switch ($contextlevel) {
2813 // TODO: this should probably use context level names instead
2814 case CONTEXT_SYSTEM: return get_string('coresystem');
2815 case CONTEXT_USER: return get_string('users');
2816 case CONTEXT_COURSECAT: return get_string('categories');
2817 case CONTEXT_COURSE: return get_string('course');
2818 case CONTEXT_MODULE: return get_string('activities');
2819 case CONTEXT_BLOCK: return get_string('block');
2820 default: print_error('unknowncontext');
2821 }
2822 }
2823
2824 list($type, $name) = normalize_component($component);
2825 $dir = get_plugin_directory($type, $name);
2826 if (!file_exists($dir)) {
2827 // plugin not installed, bad luck, there is no way to find the name
2828 return $component.' ???';
2829 }
2830
2831 switch ($type) {
2832 // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2833 case 'quiz': return get_string($name.':componentname', $component);// insane hack!!!
2834 case 'repository': return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2835 case 'gradeimport': return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2836 case 'gradeexport': return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2837 case 'gradereport': return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2838 case 'webservice': return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2839 case 'block': return get_string('block').': '.get_string('pluginname', basename($component));
2840 case 'mod':
2841 if (get_string_manager()->string_exists('pluginname', $component)) {
2842 return get_string('activity').': '.get_string('pluginname', $component);
2843 } else {
2844 return get_string('activity').': '.get_string('modulename', $component);
2845 }
2846 default: return get_string('pluginname', $component);
2847 }
2848}
2849
2850/**
2851 * Gets the list of roles assigned to this context and up (parents)
2852 * from the list of roles that are visible on user profile page
2853 * and participants page.
2854 *
2855 * @param context $context
2856 * @return array
2857 */
2858function get_profile_roles(context $context) {
2859 global $CFG, $DB;
2860
2861 if (empty($CFG->profileroles)) {
2862 return array();
2863 }
2864
2865 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2866 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2867 $params = array_merge($params, $cparams);
2868
c52551dc
PS
2869 if ($coursecontext = $context->get_course_context(false)) {
2870 $params['coursecontext'] = $coursecontext->id;
2871 } else {
2872 $params['coursecontext'] = 0;
2873 }
2874
2875 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
e922fe23 2876 FROM {role_assignments} ra, {role} r
c52551dc 2877 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
e922fe23
PS
2878 WHERE r.id = ra.roleid
2879 AND ra.contextid $contextlist
2880 AND r.id $rallowed
2881 ORDER BY r.sortorder ASC";
2882
2883 return $DB->get_records_sql($sql, $params);
2884}
2885
2886/**
2887 * Gets the list of roles assigned to this context and up (parents)
2888 *
2889 * @param context $context
2890 * @return array
2891 */
2892function get_roles_used_in_context(context $context) {
2893 global $DB;
2894
c52551dc
PS
2895 list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'cl');
2896
2897 if ($coursecontext = $context->get_course_context(false)) {
2898 $params['coursecontext'] = $coursecontext->id;
2899 } else {
2900 $params['coursecontext'] = 0;
2901 }
e922fe23 2902
c52551dc 2903 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
e922fe23 2904 FROM {role_assignments} ra, {role} r
c52551dc 2905 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
e922fe23
PS
2906 WHERE r.id = ra.roleid
2907 AND ra.contextid $contextlist
2908 ORDER BY r.sortorder ASC";
2909
2910 return $DB->get_records_sql($sql, $params);
2911}
2912
2913/**
2914 * This function is used to print roles column in user profile page.
2915 * It is using the CFG->profileroles to limit the list to only interesting roles.
2916 * (The permission tab has full details of user role assignments.)
2917 *
2918 * @param int $userid
2919 * @param int $courseid
2920 * @return string
2921 */
2922function get_user_roles_in_course($userid, $courseid) {
2923 global $CFG, $DB;
2924
2925 if (empty($CFG->profileroles)) {
2926 return '';
2927 }
2928
2929 if ($courseid == SITEID) {
2930 $context = context_system::instance();
2931 } else {
2932 $context = context_course::instance($courseid);
2933 }
2934
2935 if (empty($CFG->profileroles)) {
2936 return array();
2937 }
2938
2939 list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2940 list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2941 $params = array_merge($params, $cparams);
2942
c52551dc
PS
2943 if ($coursecontext = $context->get_course_context(false)) {
2944 $params['coursecontext'] = $coursecontext->id;
2945 } else {
2946 $params['coursecontext'] = 0;
2947 }
2948
2949 $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder, rn.name AS coursealias
e922fe23 2950 FROM {role_assignments} ra, {role} r
c52551dc 2951 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
e922fe23
PS
2952 WHERE r.id = ra.roleid
2953 AND ra.contextid $contextlist
2954 AND r.id $rallowed
2955 AND ra.userid = :userid
2956 ORDER BY r.sortorder ASC";
2957 $params['userid'] = $userid;
2958
2959 $rolestring = '';
2960
2961 if ($roles = $DB->get_records_sql($sql, $params)) {
c52551dc 2962 $rolenames = role_fix_names($roles, $context, ROLENAME_ALIAS, true); // Substitute aliases
e922fe23
PS
2963
2964 foreach ($rolenames as $roleid => $rolename) {
2965 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
2966 }
2967 $rolestring = implode(',', $rolenames);
2968 }
2969
2970 return $rolestring;
2971}
2972
2973/**
2974 * Checks if a user can assign users to a particular role in this context
2975 *
2976 * @param context $context
2977 * @param int $targetroleid - the id of the role you want to assign users to
2978 * @return boolean
2979 */
2980function user_can_assign(context $context, $targetroleid) {
2981 global $DB;
2982
3370f216
AG
2983 // First check to see if the user is a site administrator.
2984 if (is_siteadmin()) {
2985 return true;
2986 }
2987
2988 // Check if user has override capability.
2989 // If not return false.
e922fe23
PS
2990 if (!has_capability('moodle/role:assign', $context)) {
2991 return false;
2992 }
2993 // pull out all active roles of this user from this context(or above)
2994 if ($userroles = get_user_roles($context)) {
2995 foreach ($userroles as $userrole) {
2996 // if any in the role_allow_override table, then it's ok
2997 if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2998 return true;
2999 }
3000 }
3001 }
3002
3003 return false;
3004}
3005
3006/**
3007 * Returns all site roles in correct sort order.
3008 *
fa0ad435
PS
3009 * Note: this method does not localise role names or descriptions,
3010 * use role_get_names() if you need role names.
3011 *
c52551dc
PS
3012 * @param context $context optional context for course role name aliases
3013 * @return array of role records with optional coursealias property
e922fe23 3014 */
c52551dc 3015function get_all_roles(context $context = null) {
e922fe23 3016 global $DB;
c52551dc
PS
3017
3018 if (!$context or !$coursecontext = $context->get_course_context(false)) {
3019 $coursecontext = null;
3020 }
3021
3022 if ($coursecontext) {
3023 $sql = "SELECT r.*, rn.name AS coursealias
3024 FROM {role} r
3025 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
3026 ORDER BY r.sortorder ASC";
3027 return $DB->get_records_sql($sql, array('coursecontext'=>$coursecontext->id));
3028
3029 } else {
3030 return $DB->get_records('role', array(), 'sortorder ASC');
3031 }
e922fe23
PS
3032}
3033
3034/**
3035 * Returns roles of a specified archetype
3036 *
3037 * @param string $archetype
3038 * @return array of full role records
3039 */
3040function get_archetype_roles($archetype) {
3041 global $DB;
3042 return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
3043}
3044
3045/**
3046 * Gets all the user roles assigned in this context, or higher contexts
3047 * this is mainly used when checking if a user can assign a role, or overriding a role
3048 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3049 * allow_override tables
3050 *
3051 * @param context $context
3052 * @param int $userid
3053 * @param bool $checkparentcontexts defaults to true
3054 * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
3055 * @return array
3056 */
3057function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
3058 global $USER, $DB;
3059
3060 if (empty($userid)) {
3061 if (empty($USER->id)) {
3062 return array();
3063 }
3064 $userid = $USER->id;
3065 }
3066
3067 if ($checkparentcontexts) {
3068 $contextids = $context->get_parent_context_ids();
3069 } else {
3070 $contextids = array();
3071 }
3072 $contextids[] = $context->id;
3073
3074 list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
3075
3076 array_unshift($params, $userid);
3077
3078 $sql = "SELECT ra.*, r.name, r.shortname
3079 FROM {role_assignments} ra, {role} r, {context} c
3080 WHERE ra.userid = ?
3081 AND ra.roleid = r.id
3082 AND ra.contextid = c.id
3083 AND ra.contextid $contextids
3084 ORDER BY $order";
3085
3086 return $DB->get_records_sql($sql ,$params);
3087}
3088
ab0c7007
TH
3089/**
3090 * Like get_user_roles, but adds in the authenticated user role, and the front
3091 * page roles, if applicable.
3092 *
3093 * @param context $context the context.
3094 * @param int $userid optional. Defaults to $USER->id
3095 * @return array of objects with fields ->userid, ->contextid and ->roleid.
3096 */
3097function get_user_roles_with_special(context $context, $userid = 0) {
3098 global $CFG, $USER;
3099
3100 if (empty($userid)) {
3101 if (empty($USER->id)) {
3102 return array();
3103 }
3104 $userid = $USER->id;
3105 }
3106
3107 $ras = get_user_roles($context, $userid);
3108
3109 // Add front-page role if relevant.
3110 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3111 $isfrontpage = ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) ||
3112 is_inside_frontpage($context);
3113 if ($defaultfrontpageroleid && $isfrontpage) {
3114 $frontpagecontext = context_course::instance(SITEID);
3115 $ra = new stdClass();
3116 $ra->userid = $userid;
3117 $ra->contextid = $frontpagecontext->id;
3118 $ra->roleid = $defaultfrontpageroleid;
3119 $ras[] = $ra;
3120 }
3121
3122 // Add authenticated user role if relevant.
3123 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3124 if ($defaultuserroleid && !isguestuser($userid)) {
3125 $systemcontext = context_system::instance();
3126 $ra = new stdClass();
3127 $ra->userid = $userid;
3128 $ra->contextid = $systemcontext->id;
3129 $ra->roleid = $defaultuserroleid;
3130 $ras[] = $ra;
3131 }
3132
3133 return $ras;
3134}
3135
e922fe23
PS
3136/**
3137 * Creates a record in the role_allow_override table
3138 *
3139 * @param int $sroleid source roleid
3140 * @param int $troleid target roleid
3141 * @return void
3142 */
3143function allow_override($sroleid, $troleid) {
3144 global $DB;
3145
3146 $record = new stdClass();
3147 $record->roleid = $sroleid;
3148 $record->allowoverride = $troleid;
3149 $DB->insert_record('role_allow_override', $record);
3150}
3151
3152/**
3153 * Creates a record in the role_allow_assign table
3154 *
3155 * @param int $fromroleid source roleid
3156 * @param int $targetroleid target roleid
3157 * @return void
3158 */
3159function allow_assign($fromroleid, $targetroleid) {
3160 global $DB;
3161
3162 $record = new stdClass();
3163 $record->roleid = $fromroleid;
3164 $record->allowassign = $targetroleid;
3165 $DB->insert_record('role_allow_assign', $record);
3166}
3167
3168/**
3169 * Creates a record in the role_allow_switch table
3170 *
3171 * @param int $fromroleid source roleid
3172 * @param int $targetroleid target roleid
3173 * @return void
3174 */
3175function allow_switch($fromroleid, $targetroleid) {
3176 global $DB;
3177
3178 $record = new stdClass();
3179 $record->roleid = $fromroleid;
3180 $record->allowswitch = $targetroleid;
3181 $DB->insert_record('role_allow_switch', $record);
3182}
3183
3184/**
3185 * Gets a list of roles that this user can assign in this context
3186 *
3187 * @param context $context the context.
3188 * @param int $rolenamedisplay the type of role name to display. One of the
3189 * ROLENAME_X constants. Default ROLENAME_ALIAS.
3190 * @param bool $withusercounts if true, count the number of users with each role.
3191 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3192 * @return array if $withusercounts is false, then an array $roleid => $rolename.
3193 * if $withusercounts is true, returns a list of three arrays,
3194 * $rolenames, $rolecounts, and $nameswithcounts.
3195 */
3196function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3197 global $USER, $DB;
3198
3199 // make sure there is a real user specified
3200 if ($user === null) {
3201 $userid = isset($USER->id) ? $USER->id : 0;
3202 } else {
3203 $userid = is_object($user) ? $user->id : $user;
3204 }
3205
3206 if (!has_capability('moodle/role:assign', $context, $userid)) {
3207 if ($withusercounts) {
3208 return array(array(), array(), array());
3209 } else {
3210 return array();
3211 }
3212 }
3213
e922fe23
PS
3214 $params = array();
3215 $extrafields = '';
e922fe23
PS
3216
3217 if ($withusercounts) {
3218 $extrafields = ', (SELECT count(u.id)
3219 FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3220 WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3221 ) AS usercount';
3222 $params['conid'] = $context->id;
3223 }
3224
3225 if (is_siteadmin($userid)) {
3226 // show all roles allowed in this context to admins
3227 $assignrestriction = "";
3228 } else {
c52551dc
PS
3229 $parents = $context->get_parent_context_ids(true);
3230 $contexts = implode(',' , $parents);
e922fe23
PS
3231 $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3232 FROM {role_allow_assign} raa
3233 JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3234 WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3235 ) ar ON ar.id = r.id";
3236 $params['userid'] = $userid;
3237 }
3238 $params['contextlevel'] = $context->contextlevel;
c52551dc
PS
3239
3240 if ($coursecontext = $context->get_course_context(false)) {
3241 $params['coursecontext'] = $coursecontext->id;
3242 } else {
3243 $params['coursecontext'] = 0; // no course aliases
3244 $coursecontext = null;
3245 }
3246 $sql = "SELECT r.id, r.name, r.shortname, rn.name AS coursealias $extrafields
e922fe23
PS
3247 FROM {role} r
3248 $assignrestriction
c52551dc
PS
3249 JOIN {role_context_levels} rcl ON (rcl.contextlevel = :contextlevel AND r.id = rcl.roleid)
3250 LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
e922fe23
PS
3251 ORDER BY r.sortorder ASC";
3252 $roles = $DB->get_records_sql($sql, $params);
3253