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