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