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