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