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