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