Take out debugging & merge branch 'w05_MDL-26198_20_completion' of git://github.com...
[moodle.git] / lib / accesslib.php
CommitLineData
46808d7c 1<?php
2
117bd748
PS
3// This file is part of Moodle - http://moodle.org/
4//
46808d7c 5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
117bd748 14//
46808d7c 15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
6cdd0f9c 17
92e53168 18/**
46808d7c 19 * This file contains functions for managing user access
20 *
cc3edaa4 21 * <b>Public API vs internals</b>
5a4e7398 22 *
92e53168 23 * General users probably only care about
24 *
dcd6a775 25 * Context handling
26 * - get_context_instance()
27 * - get_context_instance_by_id()
28 * - get_parent_contexts()
29 * - get_child_contexts()
5a4e7398 30 *
dcd6a775 31 * Whether the user can do something...
92e53168 32 * - has_capability()
8a1b1c32 33 * - has_any_capability()
34 * - has_all_capabilities()
efd6fce5 35 * - require_capability()
dcd6a775 36 * - require_login() (from moodlelib)
37 *
38 * What courses has this user access to?
92e53168 39 * - get_user_courses_bycap()
dcd6a775 40 *
db70c4bd 41 * What users can do X in this context?
42 * - get_users_by_capability()
43 *
dcd6a775 44 * Enrol/unenrol
ad833c42 45 * - enrol_into_course()
46 * - role_assign()/role_unassign()
5a4e7398 47 *
92e53168 48 *
49 * Advanced use
dcd6a775 50 * - load_all_capabilities()
51 * - reload_all_capabilities()
bb2c22bd 52 * - has_capability_in_accessdata()
dcd6a775 53 * - is_siteadmin()
54 * - get_user_access_sitewide()
a2cf7f1b 55 * - load_subcontext()
dcd6a775 56 * - get_role_access_bycontext()
57 *
cc3edaa4 58 * <b>Name conventions</b>
5a4e7398 59 *
cc3edaa4 60 * "ctx" means context
92e53168 61 *
cc3edaa4 62 * <b>accessdata</b>
92e53168 63 *
64 * Access control data is held in the "accessdata" array
65 * which - for the logged-in user, will be in $USER->access
5a4e7398 66 *
d867e696 67 * For other users can be generated and passed around (but may also be cached
68 * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser.
92e53168 69 *
bb2c22bd 70 * $accessdata is a multidimensional array, holding
5a4e7398 71 * role assignments (RAs), role-capabilities-perm sets
51be70d2 72 * (role defs) and a list of courses we have loaded
92e53168 73 * data for.
74 *
5a4e7398 75 * Things are keyed on "contextpaths" (the path field of
92e53168 76 * the context table) for fast walking up/down the tree.
cc3edaa4 77 * <code>
bb2c22bd 78 * $accessdata[ra][$contextpath]= array($roleid)
79 * [$contextpath]= array($roleid)
5a4e7398 80 * [$contextpath]= array($roleid)
117bd748 81 * </code>
92e53168 82 *
83 * Role definitions are stored like this
84 * (no cap merge is done - so it's compact)
85 *
cc3edaa4 86 * <code>
bb2c22bd 87 * $accessdata[rdef][$contextpath:$roleid][mod/forum:viewpost] = 1
88 * [mod/forum:editallpost] = -1
89 * [mod/forum:startdiscussion] = -1000
cc3edaa4 90 * </code>
92e53168 91 *
bb2c22bd 92 * See how has_capability_in_accessdata() walks up/down the tree.
92e53168 93 *
94 * Normally - specially for the logged-in user, we only load
95 * rdef and ra down to the course level, but not below. This
96 * keeps accessdata small and compact. Below-the-course ra/rdef
97 * are loaded as needed. We keep track of which courses we
5a4e7398 98 * have loaded ra/rdef in
cc3edaa4 99 * <code>
5a4e7398 100 * $accessdata[loaded] = array($contextpath, $contextpath)
cc3edaa4 101 * </code>
92e53168 102 *
cc3edaa4 103 * <b>Stale accessdata</b>
92e53168 104 *
105 * For the logged-in user, accessdata is long-lived.
106 *
d867e696 107 * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
92e53168 108 * context paths affected by changes. Any check at-or-below
109 * a dirty context will trigger a transparent reload of accessdata.
5a4e7398 110 *
4f65e0fb 111 * Changes at the system level will force the reload for everyone.
92e53168 112 *
cc3edaa4 113 * <b>Default role caps</b>
5a4e7398 114 * The default role assignment is not in the DB, so we
115 * add it manually to accessdata.
92e53168 116 *
117 * This means that functions that work directly off the
118 * DB need to ensure that the default role caps
5a4e7398 119 * are dealt with appropriately.
92e53168 120 *
78bfb562
PS
121 * @package core
122 * @subpackage role
123 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
124 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
92e53168 125 */
bbbf2d40 126
78bfb562
PS
127defined('MOODLE_INTERNAL') || die();
128
cc3edaa4 129/** permission definitions */
e49e61bf 130define('CAP_INHERIT', 0);
cc3edaa4 131/** permission definitions */
bbbf2d40 132define('CAP_ALLOW', 1);
cc3edaa4 133/** permission definitions */
bbbf2d40 134define('CAP_PREVENT', -1);
cc3edaa4 135/** permission definitions */
bbbf2d40 136define('CAP_PROHIBIT', -1000);
137
cc3edaa4 138/** context definitions */
bbbf2d40 139define('CONTEXT_SYSTEM', 10);
cc3edaa4 140/** context definitions */
4b10f08b 141define('CONTEXT_USER', 30);
cc3edaa4 142/** context definitions */
bbbf2d40 143define('CONTEXT_COURSECAT', 40);
cc3edaa4 144/** context definitions */
bbbf2d40 145define('CONTEXT_COURSE', 50);
cc3edaa4 146/** context definitions */
bbbf2d40 147define('CONTEXT_MODULE', 70);
cc3edaa4 148/** context definitions */
bbbf2d40 149define('CONTEXT_BLOCK', 80);
150
cc3edaa4 151/** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
21b6db6e 152define('RISK_MANAGETRUST', 0x0001);
cc3edaa4 153/** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
a6b02b65 154define('RISK_CONFIG', 0x0002);
cc3edaa4 155/** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
21b6db6e 156define('RISK_XSS', 0x0004);
cc3edaa4 157/** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
21b6db6e 158define('RISK_PERSONAL', 0x0008);
cc3edaa4 159/** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
21b6db6e 160define('RISK_SPAM', 0x0010);
cc3edaa4 161/** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
3a0c6cca 162define('RISK_DATALOSS', 0x0020);
21b6db6e 163
cc3edaa4 164/** rolename displays - the name as defined in the role definition */
165define('ROLENAME_ORIGINAL', 0);
166/** rolename displays - the name as defined by a role alias */
167define('ROLENAME_ALIAS', 1);
168/** rolename displays - Both, like this: Role alias (Original)*/
169define('ROLENAME_BOTH', 2);
170/** rolename displays - the name as defined in the role definition and the shortname in brackets*/
171define('ROLENAME_ORIGINALANDSHORT', 3);
172/** rolename displays - the name as defined by a role alias, in raw form suitable for editing*/
173define('ROLENAME_ALIAS_RAW', 4);
df997f84
PS
174/** rolename displays - the name is simply short role name*/
175define('ROLENAME_SHORT', 5);
cc3edaa4 176
d0e538ba
PS
177/**
178 * Internal class provides a cache of context information. The cache is
179 * restricted in size.
180 *
181 * This cache should NOT be used outside accesslib.php!
182 *
183 * @private
184 * @author Sam Marshall
185 */
186class context_cache {
187 private $contextsbyid;
188 private $contexts;
189 private $count;
190
191 /**
192 * @var int Maximum number of contexts that will be cached.
193 */
194 const MAX_SIZE = 2500;
195 /**
196 * @var int Once contexts reach maximum number, this many will be removed from cache.
197 */
198 const REDUCE_SIZE = 1000;
199
200 /**
201 * Initialises (empty)
202 */
203 public function __construct() {
204 $this->reset();
205 }
206
207 /**
208 * Resets the cache to remove all data.
209 */
210 public function reset() {
211 $this->contexts = array();
212 $this->contextsbyid = array();
213 $this->count = 0;
214 }
215
216 /**
217 * Adds a context to the cache. If the cache is full, discards a batch of
218 * older entries.
219 * @param stdClass $context New context to add
220 */
221 public function add(stdClass $context) {
222 if ($this->count >= self::MAX_SIZE) {
223 for ($i=0; $i<self::REDUCE_SIZE; $i++) {
224 if ($first = reset($this->contextsbyid)) {
225 unset($this->contextsbyid[$first->id]);
226 unset($this->contexts[$first->contextlevel][$first->instanceid]);
227 }
228 }
229 $this->count -= self::REDUCE_SIZE;
230 if ($this->count < 0) {
231 // most probably caused by the drift, the reset() above
232 // might have returned false because there might not be any more elements
233 $this->count = 0;
234 }
235 }
236
237 $this->contexts[$context->contextlevel][$context->instanceid] = $context;
238 $this->contextsbyid[$context->id] = $context;
239
240 // Note the count may get out of synch slightly if you cache a context
241 // that is already cached, but it doesn't really matter much and I
242 // didn't think it was worth the performance hit.
243 $this->count++;
244 }
245
246 /**
247 * Removes a context from the cache.
248 * @param stdClass $context Context object to remove (must include fields
249 * ->id, ->contextlevel, ->instanceid at least)
250 */
251 public function remove(stdClass $context) {
252 unset($this->contexts[$context->contextlevel][$context->instanceid]);
253 unset($this->contextsbyid[$context->id]);
254
255 // Again the count may get a bit out of synch if you remove things
256 // that don't exist
257 $this->count--;
258
259 if ($this->count < 0) {
260 $this->count = 0;
261 }
262 }
263
264 /**
265 * Gets a context from the cache.
266 * @param int $contextlevel Context level
267 * @param int $instance Instance ID
268 * @return stdClass|bool Context or false if not in cache
269 */
270 public function get($contextlevel, $instance) {
271 if (isset($this->contexts[$contextlevel][$instance])) {
272 return $this->contexts[$contextlevel][$instance];
273 }
274 return false;
275 }
276
277 /**
278 * Gets a context from the cache based on its id.
279 * @param int $id Context ID
280 * @return stdClass|bool Context or false if not in cache
281 */
282 public function get_by_id($id) {
283 if (isset($this->contextsbyid[$id])) {
284 return $this->contextsbyid[$id];
285 }
286 return false;
287 }
288
289 /**
290 * @return int Count of contexts in cache (approximately)
291 */
292 public function get_approx_count() {
293 return $this->count;
294 }
4d10247f 295}
296
cc3edaa4 297/**
117bd748 298 * Although this looks like a global variable, it isn't really.
cc3edaa4 299 *
117bd748
PS
300 * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
301 * It is used to cache various bits of data between function calls for performance reasons.
4f65e0fb 302 * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
cc3edaa4 303 * as methods of a class, instead of functions.
304 *
305 * @global stdClass $ACCESSLIB_PRIVATE
306 * @name $ACCESSLIB_PRIVATE
307 */
f14438dc 308global $ACCESSLIB_PRIVATE;
62e65b21 309$ACCESSLIB_PRIVATE = new stdClass();
d0e538ba 310$ACCESSLIB_PRIVATE->contexcache = new context_cache();
62e65b21
PS
311$ACCESSLIB_PRIVATE->systemcontext = null; // Used in get_system_context
312$ACCESSLIB_PRIVATE->dirtycontexts = null; // Dirty contexts cache
d867e696 313$ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the $accessdata structure for users other than $USER
62e65b21
PS
314$ACCESSLIB_PRIVATE->roledefinitions = array(); // role definitions cache - helps a lot with mem usage in cron
315$ACCESSLIB_PRIVATE->croncache = array(); // Used in get_role_access
d867e696 316$ACCESSLIB_PRIVATE->preloadedcourses = array(); // Used in preload_course_contexts.
62e65b21 317$ACCESSLIB_PRIVATE->capabilities = null; // detailed information about the capabilities
bbbf2d40 318
d867e696 319/**
46808d7c 320 * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
117bd748 321 *
d867e696 322 * This method should ONLY BE USED BY UNIT TESTS. It clears all of
323 * accesslib's private caches. You need to do this before setting up test data,
4f65e0fb 324 * and also at the end of the tests.
d867e696 325 */
326function accesslib_clear_all_caches_for_unit_testing() {
327 global $UNITTEST, $USER, $ACCESSLIB_PRIVATE;
328 if (empty($UNITTEST->running)) {
329 throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
330 }
d0e538ba 331 $ACCESSLIB_PRIVATE->contexcache = new context_cache();
62e65b21
PS
332 $ACCESSLIB_PRIVATE->systemcontext = null;
333 $ACCESSLIB_PRIVATE->dirtycontexts = null;
d867e696 334 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
62e65b21
PS
335 $ACCESSLIB_PRIVATE->roledefinitions = array();
336 $ACCESSLIB_PRIVATE->croncache = array();
d867e696 337 $ACCESSLIB_PRIVATE->preloadedcourses = array();
62e65b21 338 $ACCESSLIB_PRIVATE->capabilities = null;
d867e696 339
340 unset($USER->access);
341}
342
46808d7c 343/**
344 * This is really slow!!! do not use above course context level
345 *
346 * @param int $roleid
347 * @param object $context
348 * @return array
349 */
eef879ec 350function get_role_context_caps($roleid, $context) {
f33e1ed4 351 global $DB;
352
eef879ec 353 //this is really slow!!!! - do not use above course context level!
354 $result = array();
355 $result[$context->id] = array();
e7876c1e 356
eef879ec 357 // first emulate the parent context capabilities merging into context
358 $searchcontexts = array_reverse(get_parent_contexts($context));
359 array_push($searchcontexts, $context->id);
360 foreach ($searchcontexts as $cid) {
f33e1ed4 361 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
eef879ec 362 foreach ($capabilities as $cap) {
363 if (!array_key_exists($cap->capability, $result[$context->id])) {
364 $result[$context->id][$cap->capability] = 0;
365 }
366 $result[$context->id][$cap->capability] += $cap->permission;
367 }
368 }
369 }
e7876c1e 370
eef879ec 371 // now go through the contexts bellow given context
19bb8a05 372 $searchcontexts = array_keys(get_child_contexts($context));
eef879ec 373 foreach ($searchcontexts as $cid) {
f33e1ed4 374 if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
eef879ec 375 foreach ($capabilities as $cap) {
376 if (!array_key_exists($cap->contextid, $result)) {
377 $result[$cap->contextid] = array();
378 }
379 $result[$cap->contextid][$cap->capability] = $cap->permission;
380 }
381 }
e7876c1e 382 }
383
eef879ec 384 return $result;
385}
386
eef879ec 387/**
46808d7c 388 * Gets the accessdata for role "sitewide" (system down to course)
343effbe 389 *
46808d7c 390 * @param int $roleid
62e65b21 391 * @param array $accessdata defaults to null
e0376a62 392 * @return array
eef879ec 393 */
62e65b21 394function get_role_access($roleid, $accessdata = null) {
f33e1ed4 395 global $CFG, $DB;
eef879ec 396
e0376a62 397 /* Get it in 1 cheap DB query...
398 * - relevant role caps at the root and down
399 * to the course level - but not below
400 */
bb2c22bd 401 if (is_null($accessdata)) {
402 $accessdata = array(); // named list
403 $accessdata['ra'] = array();
404 $accessdata['rdef'] = array();
405 $accessdata['loaded'] = array();
e7876c1e 406 }
407
e0376a62 408 //
409 // Overrides for the role IN ANY CONTEXTS
410 // down to COURSE - not below -
411 //
412 $sql = "SELECT ctx.path,
413 rc.capability, rc.permission
f33e1ed4 414 FROM {context} ctx
415 JOIN {role_capabilities} rc
416 ON rc.contextid=ctx.id
417 WHERE rc.roleid = ?
418 AND ctx.contextlevel <= ".CONTEXT_COURSE."
419 ORDER BY ctx.depth, ctx.path";
420 $params = array($roleid);
133d5a97 421
a91b910e 422 // we need extra caching in CLI scripts and cron
423 if (CLI_SCRIPT) {
d867e696 424 global $ACCESSLIB_PRIVATE;
133d5a97 425
d867e696 426 if (!isset($ACCESSLIB_PRIVATE->croncache[$roleid])) {
427 $ACCESSLIB_PRIVATE->croncache[$roleid] = array();
afa559e9
EL
428 $rs = $DB->get_recordset_sql($sql, $params);
429 foreach ($rs as $rd) {
430 $ACCESSLIB_PRIVATE->croncache[$roleid][] = $rd;
133d5a97 431 }
afa559e9 432 $rs->close();
133d5a97 433 }
434
d867e696 435 foreach ($ACCESSLIB_PRIVATE->croncache[$roleid] as $rd) {
03cedd62 436 $k = "{$rd->path}:{$roleid}";
437 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
e0376a62 438 }
5a4e7398 439
133d5a97 440 } else {
afa559e9
EL
441 $rs = $DB->get_recordset_sql($sql, $params);
442 if ($rs->valid()) {
f33e1ed4 443 foreach ($rs as $rd) {
133d5a97 444 $k = "{$rd->path}:{$roleid}";
445 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
446 }
447 unset($rd);
133d5a97 448 }
afa559e9 449 $rs->close();
8d2b18a8 450 }
e0376a62 451
bb2c22bd 452 return $accessdata;
e7876c1e 453}
454
4e1fe7d1 455/**
46808d7c 456 * Gets the accessdata for role "sitewide" (system down to course)
4e1fe7d1 457 *
46808d7c 458 * @param int $roleid
62e65b21 459 * @param array $accessdata defaults to null
4e1fe7d1 460 * @return array
461 */
62e65b21 462function get_default_frontpage_role_access($roleid, $accessdata = null) {
4e1fe7d1 463
f33e1ed4 464 global $CFG, $DB;
5a4e7398 465
4e1fe7d1 466 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
467 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
5a4e7398 468
4e1fe7d1 469 //
470 // Overrides for the role in any contexts related to the course
471 //
472 $sql = "SELECT ctx.path,
473 rc.capability, rc.permission
f33e1ed4 474 FROM {context} ctx
475 JOIN {role_capabilities} rc
476 ON rc.contextid=ctx.id
477 WHERE rc.roleid = ?
478 AND (ctx.id = ".SYSCONTEXTID." OR ctx.path LIKE ?)
479 AND ctx.contextlevel <= ".CONTEXT_COURSE."
480 ORDER BY ctx.depth, ctx.path";
481 $params = array($roleid, "$base/%");
5a4e7398 482
afa559e9
EL
483 $rs = $DB->get_recordset_sql($sql, $params);
484 if ($rs->valid()) {
f33e1ed4 485 foreach ($rs as $rd) {
03cedd62 486 $k = "{$rd->path}:{$roleid}";
487 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
4e1fe7d1 488 }
03cedd62 489 unset($rd);
4e1fe7d1 490 }
afa559e9 491 $rs->close();
4e1fe7d1 492
493 return $accessdata;
494}
495
496
8f8ed475 497/**
498 * Get the default guest role
117bd748 499 *
62e65b21 500 * @return stdClass role
8f8ed475 501 */
502function get_guest_role() {
f33e1ed4 503 global $CFG, $DB;
ebce32b5 504
505 if (empty($CFG->guestroleid)) {
4f0c2d00 506 if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
ebce32b5 507 $guestrole = array_shift($roles); // Pick the first one
508 set_config('guestroleid', $guestrole->id);
509 return $guestrole;
510 } else {
511 debugging('Can not find any guest role!');
512 return false;
513 }
8f8ed475 514 } else {
f33e1ed4 515 if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
ebce32b5 516 return $guestrole;
517 } else {
518 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
519 set_config('guestroleid', '');
520 return get_guest_role();
521 }
8f8ed475 522 }
523}
524
128f0984 525/**
4f65e0fb 526 * Check whether a user has a particular capability in a given context.
46808d7c 527 *
41e87d30 528 * For example::
529 * $context = get_context_instance(CONTEXT_MODULE, $cm->id);
530 * has_capability('mod/forum:replypost',$context)
46808d7c 531 *
4f65e0fb 532 * By default checks the capabilities of the current user, but you can pass a
4f0c2d00
PS
533 * different userid. By default will return true for admin users, but you can override that with the fourth argument.
534 *
535 * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
536 * or capabilities with XSS, config or data loss risks.
117bd748 537 *
41e87d30 538 * @param string $capability the name of the capability to check. For example mod/forum:view
539 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
62e65b21 540 * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
4f0c2d00 541 * @param boolean $doanything If false, ignores effect of admin role assignment
41e87d30 542 * @return boolean true if the user has this capability. Otherwise false.
128f0984 543 */
62e65b21 544function has_capability($capability, $context, $user = null, $doanything = true) {
d867e696 545 global $USER, $CFG, $DB, $SCRIPT, $ACCESSLIB_PRIVATE;
18818abf 546
31a99877 547 if (during_initial_install()) {
18818abf 548 if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cliupgrade.php") {
549 // we are in an installer - roles can not work yet
550 return true;
551 } else {
552 return false;
553 }
554 }
7f97ea29 555
4f0c2d00
PS
556 if (strpos($capability, 'moodle/legacy:') === 0) {
557 throw new coding_exception('Legacy capabilities can not be used any more!');
558 }
559
7d0c81b3 560 // the original $CONTEXT here was hiding serious errors
128f0984 561 // for security reasons do not reuse previous context
7d0c81b3 562 if (empty($context)) {
563 debugging('Incorrect context specified');
564 return false;
74ac5b66 565 }
4f0c2d00
PS
566 if (!is_bool($doanything)) {
567 throw new coding_exception('Capability parameter "doanything" is wierd ("'.$doanything.'"). This has to be fixed in code.');
568 }
7f97ea29 569
4f0c2d00 570 // make sure there is a real user specified
62e65b21 571 if ($user === null) {
4f0c2d00
PS
572 $userid = !empty($USER->id) ? $USER->id : 0;
573 } else {
574 $userid = !empty($user->id) ? $user->id : $user;
cc3d5e10 575 }
576
4f0c2d00
PS
577 // capability must exist
578 if (!$capinfo = get_capability_info($capability)) {
579 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
580 return false;
581 }
582 // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
583 if (($capinfo->captype === 'write') or ((int)$capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
584 if (isguestuser($userid) or $userid == 0) {
585 return false;
c84a2dbe 586 }
7f97ea29 587 }
588
128f0984 589 if (is_null($context->path) or $context->depth == 0) {
590 //this should not happen
591 $contexts = array(SYSCONTEXTID, $context->id);
592 $context->path = '/'.SYSCONTEXTID.'/'.$context->id;
593 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()', DEBUG_DEVELOPER);
594
7f97ea29 595 } else {
596 $contexts = explode('/', $context->path);
597 array_shift($contexts);
598 }
599
a91b910e 600 if (CLI_SCRIPT && !isset($USER->access)) {
1a9b6787 601 // In cron, some modules setup a 'fake' $USER,
602 // ensure we load the appropriate accessdata.
d867e696 603 if (isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
62e65b21 604 $ACCESSLIB_PRIVATE->dirtycontexts = null; //load fresh dirty contexts
128f0984 605 } else {
1a9b6787 606 load_user_accessdata($userid);
d867e696 607 $ACCESSLIB_PRIVATE->dirtycontexts = array();
1a9b6787 608 }
d867e696 609 $USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
7d0c81b3 610
7fde45a7 611 } else if (isset($USER->id) && ($USER->id == $userid) && !isset($USER->access)) {
7d0c81b3 612 // caps not loaded yet - better to load them to keep BC with 1.8
128f0984 613 // not-logged-in user or $USER object set up manually first time here
7d0c81b3 614 load_all_capabilities();
d867e696 615 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // reset the cache for other users too, the dirty contexts are empty now
616 $ACCESSLIB_PRIVATE->roledefinitions = array();
1a9b6787 617 }
618
128f0984 619 // Load dirty contexts list if needed
d867e696 620 if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
7be3be1b 621 if (isset($USER->access['time'])) {
d867e696 622 $ACCESSLIB_PRIVATE->dirtycontexts = get_dirty_contexts($USER->access['time']);
7be3be1b 623 }
624 else {
d867e696 625 $ACCESSLIB_PRIVATE->dirtycontexts = array();
7be3be1b 626 }
148eb2a7 627 }
128f0984 628
629 // Careful check for staleness...
d867e696 630 if (count($ACCESSLIB_PRIVATE->dirtycontexts) !== 0 and is_contextpath_dirty($contexts, $ACCESSLIB_PRIVATE->dirtycontexts)) {
ef989bd9 631 // reload all capabilities - preserving loginas, roleswitches, etc
632 // and then cleanup any marks of dirtyness... at least from our short
633 // term memory! :-)
d867e696 634 $ACCESSLIB_PRIVATE->accessdatabyuser = array();
635 $ACCESSLIB_PRIVATE->roledefinitions = array();
128f0984 636
a91b910e 637 if (CLI_SCRIPT) {
128f0984 638 load_user_accessdata($userid);
d867e696 639 $USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
640 $ACCESSLIB_PRIVATE->dirtycontexts = array();
128f0984 641
642 } else {
643 reload_all_capabilities();
644 }
148eb2a7 645 }
128f0984 646
4f0c2d00
PS
647 // Find out if user is admin - it is not possible to override the doanything in any way
648 // and it is not possible to switch to admin role either.
649 if ($doanything) {
650 if (is_siteadmin($userid)) {
7abbc5c2
PS
651 if ($userid != $USER->id) {
652 return true;
653 }
654 // make sure switchrole is not used in this context
655 if (empty($USER->access['rsw'])) {
656 return true;
657 }
658 $parts = explode('/', trim($context->path, '/'));
659 $path = '';
660 $switched = false;
661 foreach ($parts as $part) {
662 $path .= '/' . $part;
663 if (!empty($USER->access['rsw'][$path])) {
664 $switched = true;
665 break;
666 }
667 }
668 if (!$switched) {
669 return true;
670 }
671 //ok, admin switched role in this context, let's use normal access control rules
4f0c2d00
PS
672 }
673 }
674
13a79475 675 // divulge how many times we are called
676 //// error_log("has_capability: id:{$context->id} path:{$context->path} userid:$userid cap:$capability");
677
7fde45a7 678 if (isset($USER->id) && ($USER->id == $userid)) { // we must accept strings and integers in $userid
74ac5b66 679 //
680 // For the logged in user, we have $USER->access
681 // which will have all RAs and caps preloaded for
682 // course and above contexts.
683 //
684 // Contexts below courses && contexts that do not
685 // hang from courses are loaded into $USER->access
686 // on demand, and listed in $USER->access[loaded]
687 //
7f97ea29 688 if ($context->contextlevel <= CONTEXT_COURSE) {
689 // Course and above are always preloaded
4f0c2d00 690 return has_capability_in_accessdata($capability, $context, $USER->access);
7f97ea29 691 }
420bfab1 692 // Load accessdata for below-the-course contexts
31c2de82 693 if (!path_inaccessdata($context->path,$USER->access)) {
6100dad0 694 // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
74ac5b66 695 // $bt = debug_backtrace();
696 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
a2cf7f1b 697 load_subcontext($USER->id, $context, $USER->access);
74ac5b66 698 }
4f0c2d00 699 return has_capability_in_accessdata($capability, $context, $USER->access);
7f97ea29 700 }
bb2c22bd 701
d867e696 702 if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
204a369c 703 load_user_accessdata($userid);
704 }
4f0c2d00 705
420bfab1 706 if ($context->contextlevel <= CONTEXT_COURSE) {
707 // Course and above are always preloaded
4f0c2d00 708 return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
420bfab1 709 }
710 // Load accessdata for below-the-course contexts as needed
d867e696 711 if (!path_inaccessdata($context->path, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
6100dad0 712 // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
420bfab1 713 // $bt = debug_backtrace();
714 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
d867e696 715 load_subcontext($userid, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
420bfab1 716 }
4f0c2d00 717 return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
7f97ea29 718}
719
3fc3ebf2 720/**
41e87d30 721 * Check if the user has any one of several capabilities from a list.
46808d7c 722 *
41e87d30 723 * This is just a utility method that calls has_capability in a loop. Try to put
724 * the capabilities that most users are likely to have first in the list for best
725 * performance.
3fc3ebf2 726 *
727 * There are probably tricks that could be done to improve the performance here, for example,
728 * check the capabilities that are already cached first.
729 *
46808d7c 730 * @see has_capability()
41e87d30 731 * @param array $capabilities an array of capability names.
732 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
62e65b21 733 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
4f0c2d00 734 * @param boolean $doanything If false, ignore effect of admin role assignment
41e87d30 735 * @return boolean true if the user has any of these capabilities. Otherwise false.
3fc3ebf2 736 */
62e65b21 737function has_any_capability($capabilities, $context, $userid = null, $doanything = true) {
41e87d30 738 if (!is_array($capabilities)) {
739 debugging('Incorrect $capabilities parameter in has_any_capabilities() call - must be an array');
740 return false;
741 }
3fc3ebf2 742 foreach ($capabilities as $capability) {
59664877 743 if (has_capability($capability, $context, $userid, $doanything)) {
3fc3ebf2 744 return true;
745 }
746 }
747 return false;
748}
749
8a1b1c32 750/**
41e87d30 751 * Check if the user has all the capabilities in a list.
46808d7c 752 *
41e87d30 753 * This is just a utility method that calls has_capability in a loop. Try to put
754 * the capabilities that fewest users are likely to have first in the list for best
755 * performance.
8a1b1c32 756 *
757 * There are probably tricks that could be done to improve the performance here, for example,
758 * check the capabilities that are already cached first.
759 *
46808d7c 760 * @see has_capability()
41e87d30 761 * @param array $capabilities an array of capability names.
762 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
62e65b21 763 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
4f0c2d00 764 * @param boolean $doanything If false, ignore effect of admin role assignment
41e87d30 765 * @return boolean true if the user has all of these capabilities. Otherwise false.
8a1b1c32 766 */
62e65b21 767function has_all_capabilities($capabilities, $context, $userid = null, $doanything = true) {
3ce50127 768 if (!is_array($capabilities)) {
769 debugging('Incorrect $capabilities parameter in has_all_capabilities() call - must be an array');
770 return false;
771 }
8a1b1c32 772 foreach ($capabilities as $capability) {
773 if (!has_capability($capability, $context, $userid, $doanything)) {
774 return false;
775 }
776 }
777 return true;
778}
779
128f0984 780/**
4f0c2d00 781 * Check if the user is an admin at the site level.
46808d7c 782 *
4f0c2d00
PS
783 * Please note that use of proper capabilities is always encouraged,
784 * this function is supposed to be used from core or for temporary hacks.
39407442 785 *
4f0c2d00
PS
786 * @param int|object $user_or_id user id or user object
787 * @returns bool true if user is one of the administrators, false otherwise
39407442 788 */
62e65b21 789function is_siteadmin($user_or_id = null) {
4f0c2d00 790 global $CFG, $USER;
39407442 791
62e65b21 792 if ($user_or_id === null) {
4f0c2d00
PS
793 $user_or_id = $USER;
794 }
6cab02ac 795
4f0c2d00
PS
796 if (empty($user_or_id)) {
797 return false;
798 }
799 if (!empty($user_or_id->id)) {
800 // we support
801 $userid = $user_or_id->id;
802 } else {
803 $userid = $user_or_id;
804 }
6cab02ac 805
4f0c2d00
PS
806 $siteadmins = explode(',', $CFG->siteadmins);
807 return in_array($userid, $siteadmins);
6cab02ac 808}
809
bbdb7070 810/**
4f0c2d00 811 * Returns true if user has at least one role assign
df997f84 812 * of 'coursecontact' role (is potentially listed in some course descriptions).
62e65b21 813 *
4f0c2d00 814 * @param $userid
62e65b21 815 * @return stdClass
bbdb7070 816 */
df997f84 817function has_coursecontact_role($userid) {
2fb34345 818 global $DB, $CFG;
bbdb7070 819
df997f84 820 if (empty($CFG->coursecontact)) {
4f0c2d00
PS
821 return false;
822 }
823 $sql = "SELECT 1
824 FROM {role_assignments}
df997f84 825 WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
b2cd6570 826 return $DB->record_exists_sql($sql, array('userid'=>$userid));
bbdb7070 827}
828
46808d7c 829/**
830 * @param string $path
831 * @return string
832 */
4f0c2d00 833function get_course_from_path($path) {
7f97ea29 834 // assume that nothing is more than 1 course deep
835 if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
836 return $matches[1];
837 }
838 return false;
839}
840
46808d7c 841/**
842 * @param string $path
843 * @param array $accessdata
844 * @return bool
845 */
bb2c22bd 846function path_inaccessdata($path, $accessdata) {
4f0c2d00
PS
847 if (empty($accessdata['loaded'])) {
848 return false;
849 }
74ac5b66 850
851 // assume that contexts hang from sys or from a course
852 // this will only work well with stuff that hangs from a course
bb2c22bd 853 if (in_array($path, $accessdata['loaded'], true)) {
b738808b 854 // error_log("found it!");
74ac5b66 855 return true;
856 }
857 $base = '/' . SYSCONTEXTID;
858 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
859 $path = $matches[1];
860 if ($path === $base) {
861 return false;
862 }
bb2c22bd 863 if (in_array($path, $accessdata['loaded'], true)) {
74ac5b66 864 return true;
865 }
866 }
867 return false;
868}
869
128f0984 870/**
01a2ce80 871 * Does the user have a capability to do something?
46808d7c 872 *
31c2de82 873 * Walk the accessdata array and return true/false.
6a8d9a38 874 * Deals with prohibits, roleswitching, aggregating
875 * capabilities, etc.
876 *
877 * The main feature of here is being FAST and with no
5a4e7398 878 * side effects.
6a8d9a38 879 *
3ac81bd1 880 * Notes:
881 *
882 * Switch Roles exits early
01a2ce80 883 * ------------------------
3ac81bd1 884 * cap checks within a switchrole need to exit early
885 * in our bottom up processing so they don't "see" that
886 * there are real RAs that can do all sorts of things.
887 *
3d034f77 888 * Switch Role merges with default role
889 * ------------------------------------
890 * If you are a teacher in course X, you have at least
891 * teacher-in-X + defaultloggedinuser-sitewide. So in the
892 * course you'll have techer+defaultloggedinuser.
893 * We try to mimic that in switchrole.
894 *
01a2ce80
PS
895 * Permission evaluation
896 * ---------------------
4f65e0fb 897 * Originally there was an extremely complicated way
01a2ce80 898 * to determine the user access that dealt with
4f65e0fb
PS
899 * "locality" or role assignments and role overrides.
900 * Now we simply evaluate access for each role separately
01a2ce80
PS
901 * and then verify if user has at least one role with allow
902 * and at the same time no role with prohibit.
903 *
46808d7c 904 * @param string $capability
905 * @param object $context
906 * @param array $accessdata
46808d7c 907 * @return bool
6a8d9a38 908 */
4f0c2d00 909function has_capability_in_accessdata($capability, $context, array $accessdata) {
3ac81bd1 910 global $CFG;
911
01a2ce80
PS
912 if (empty($context->id)) {
913 throw new coding_exception('Invalid context specified');
7f97ea29 914 }
3ac81bd1 915
01a2ce80
PS
916 // Build $paths as a list of current + all parent "paths" with order bottom-to-top
917 $contextids = explode('/', trim($context->path, '/'));
918 $paths = array($context->path);
919 while ($contextids) {
920 array_pop($contextids);
921 $paths[] = '/' . implode('/', $contextids);
3ac81bd1 922 }
01a2ce80 923 unset($contextids);
3ac81bd1 924
01a2ce80
PS
925 $roles = array();
926 $switchedrole = false;
6a8d9a38 927
01a2ce80
PS
928 // Find out if role switched
929 if (!empty($accessdata['rsw'])) {
6a8d9a38 930 // From the bottom up...
01a2ce80 931 foreach ($paths as $path) {
1209cb5c 932 if (isset($accessdata['rsw'][$path])) {
01a2ce80 933 // Found a switchrole assignment - check for that role _plus_ the default user role
62e65b21 934 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
01a2ce80
PS
935 $switchedrole = true;
936 break;
6a8d9a38 937 }
938 }
939 }
940
01a2ce80
PS
941 if (!$switchedrole) {
942 // get all users roles in this context and above
943 foreach ($paths as $path) {
944 if (isset($accessdata['ra'][$path])) {
945 foreach ($accessdata['ra'][$path] as $roleid) {
62e65b21 946 $roles[$roleid] = null;
7f97ea29 947 }
01a2ce80
PS
948 }
949 }
7f97ea29 950 }
951
01a2ce80
PS
952 // Now find out what access is given to each role, going bottom-->up direction
953 foreach ($roles as $roleid => $ignored) {
954 foreach ($paths as $path) {
955 if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
956 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
957 if ($perm === CAP_PROHIBIT or is_null($roles[$roleid])) {
958 $roles[$roleid] = $perm;
959 }
960 }
7f97ea29 961 }
01a2ce80
PS
962 }
963 // any CAP_PROHIBIT found means no permission for the user
964 if (array_search(CAP_PROHIBIT, $roles) !== false) {
965 return false;
7f97ea29 966 }
967
01a2ce80
PS
968 // at least one CAP_ALLOW means the user has a permission
969 return (array_search(CAP_ALLOW, $roles) !== false);
7f97ea29 970}
018d4b52 971
46808d7c 972/**
973 * @param object $context
974 * @param array $accessdata
975 * @return array
976 */
bb2c22bd 977function aggregate_roles_from_accessdata($context, $accessdata) {
018d4b52 978
979 $path = $context->path;
980
981 // build $contexts as a list of "paths" of the current
982 // contexts and parents with the order top-to-bottom
983 $contexts = array($path);
984 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
985 $path = $matches[1];
986 array_unshift($contexts, $path);
987 }
018d4b52 988
989 $cc = count($contexts);
990
991 $roles = array();
992 // From the bottom up...
62e65b21 993 for ($n=$cc-1; $n>=0; $n--) {
018d4b52 994 $ctxp = $contexts[$n];
bb2c22bd 995 if (isset($accessdata['ra'][$ctxp]) && count($accessdata['ra'][$ctxp])) {
6cc59cb2 996 // Found assignments on this leaf
bb2c22bd 997 $addroles = $accessdata['ra'][$ctxp];
6cc59cb2 998 $roles = array_merge($roles, $addroles);
018d4b52 999 }
1000 }
1001
1002 return array_unique($roles);
1003}
1004
0468976c 1005/**
41e87d30 1006 * A convenience function that tests has_capability, and displays an error if
1007 * the user does not have that capability.
8a9c1c1c 1008 *
41e87d30 1009 * NOTE before Moodle 2.0, this function attempted to make an appropriate
1010 * require_login call before checking the capability. This is no longer the case.
1011 * You must call require_login (or one of its variants) if you want to check the
1012 * user is logged in, before you call this function.
efd6fce5 1013 *
46808d7c 1014 * @see has_capability()
1015 *
41e87d30 1016 * @param string $capability the name of the capability to check. For example mod/forum:view
1017 * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
62e65b21 1018 * @param integer $userid A user id. By default (null) checks the permissions of the current user.
4f0c2d00 1019 * @param bool $doanything If false, ignore effect of admin role assignment
41e87d30 1020 * @param string $errorstring The error string to to user. Defaults to 'nopermissions'.
1021 * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
1022 * @return void terminates with an error if the user does not have the given capability.
0468976c 1023 */
62e65b21 1024function require_capability($capability, $context, $userid = null, $doanything = true,
41e87d30 1025 $errormessage = 'nopermissions', $stringfile = '') {
d74067e8 1026 if (!has_capability($capability, $context, $userid, $doanything)) {
9a0df45a 1027 throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
0468976c 1028 }
1029}
1030
128f0984 1031/**
46808d7c 1032 * Get an array of courses where cap requested is available
df997f84 1033 * and user is enrolled, this can be relatively slow.
46808d7c 1034 *
e1d5e5c1 1035 * @param string $capability - name of the capability
df997f84
PS
1036 * @param array $accessdata_ignored
1037 * @param bool $doanything_ignored
e1d5e5c1 1038 * @param string $sort - sorting fields - prefix each fieldname with "c."
1039 * @param array $fields - additional fields you are interested in...
df997f84 1040 * @param int $limit_ignored
e1d5e5c1 1041 * @return array $courses - ordered array of course objects - see notes above
e1d5e5c1 1042 */
62e65b21 1043function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) {
e1d5e5c1 1044
df997f84 1045 //TODO: this should be most probably deprecated
e1d5e5c1 1046
df997f84
PS
1047 $courses = enrol_get_users_courses($userid, true, $fields, $sort);
1048 foreach ($courses as $id=>$course) {
1049 $context = get_context_instance(CONTEXT_COURSE, $id);
1050 if (!has_capability($cap, $context, $userid)) {
1051 unset($courses[$id]);
573674bf 1052 }
e1d5e5c1 1053 }
5a4e7398 1054
e1d5e5c1 1055 return $courses;
1056}
1057
b5a645b4 1058
a9bee37e 1059/**
46808d7c 1060 * Return a nested array showing role assignments
a9bee37e 1061 * all relevant role capabilities for the user at
df997f84 1062 * site/course_category/course levels
a9bee37e 1063 *
1064 * We do _not_ delve deeper than courses because the number of
1065 * overrides at the module/block levels is HUGE.
1066 *
f5930992 1067 * [ra] => [/path/][]=roleid
a9bee37e 1068 * [rdef] => [/path/:roleid][capability]=permission
74ac5b66 1069 * [loaded] => array('/path', '/path')
a9bee37e 1070 *
62e65b21
PS
1071 * @param int $userid - the id of the user
1072 * @return array
a9bee37e 1073 */
74ac5b66 1074function get_user_access_sitewide($userid) {
f33e1ed4 1075 global $CFG, $DB;
a9bee37e 1076
a9bee37e 1077 /* Get in 3 cheap DB queries...
f5930992 1078 * - role assignments
a9bee37e 1079 * - relevant role caps
f5930992 1080 * - above and within this user's RAs
a9bee37e 1081 * - below this user's RAs - limited to course level
1082 */
1083
62e65b21 1084 $accessdata = array(); // named list
bb2c22bd 1085 $accessdata['ra'] = array();
1086 $accessdata['rdef'] = array();
1087 $accessdata['loaded'] = array();
a9bee37e 1088
a9bee37e 1089 //
f5930992 1090 // Role assignments
a9bee37e 1091 //
f5930992 1092 $sql = "SELECT ctx.path, ra.roleid
f33e1ed4 1093 FROM {role_assignments} ra
f5930992 1094 JOIN {context} ctx ON ctx.id=ra.contextid
1095 WHERE ra.userid = ? AND ctx.contextlevel <= ".CONTEXT_COURSE;
f33e1ed4 1096 $params = array($userid);
1097 $rs = $DB->get_recordset_sql($sql, $params);
f5930992 1098
018d4b52 1099 //
1100 // raparents collects paths & roles we need to walk up
1101 // the parenthood to build the rdef
1102 //
a9bee37e 1103 $raparents = array();
128f0984 1104 if ($rs) {
f33e1ed4 1105 foreach ($rs as $ra) {
03cedd62 1106 // RAs leafs are arrays to support multi
1107 // role assignments...
1108 if (!isset($accessdata['ra'][$ra->path])) {
1109 $accessdata['ra'][$ra->path] = array();
1110 }
3c447ebe 1111 $accessdata['ra'][$ra->path][$ra->roleid] = $ra->roleid;
f5930992 1112
1113 // Concatenate as string the whole path (all related context)
1114 // for this role. This is damn faster than using array_merge()
1115 // Will unique them later
1116 if (isset($raparents[$ra->roleid])) {
1117 $raparents[$ra->roleid] .= $ra->path;
1118 } else {
1119 $raparents[$ra->roleid] = $ra->path;
03cedd62 1120 }
a9bee37e 1121 }
03cedd62 1122 unset($ra);
f33e1ed4 1123 $rs->close();
a9bee37e 1124 }
a9bee37e 1125
1126 // Walk up the tree to grab all the roledefs
1127 // of interest to our user...
f5930992 1128 //
a9bee37e 1129 // NOTE: we use a series of IN clauses here - which
1130 // might explode on huge sites with very convoluted nesting of
1131 // categories... - extremely unlikely that the number of categories
1132 // and roletypes is so large that we hit the limits of IN()
f5930992 1133 $clauses = '';
f33e1ed4 1134 $cparams = array();
f5930992 1135 foreach ($raparents as $roleid=>$strcontexts) {
1136 $contexts = implode(',', array_unique(explode('/', trim($strcontexts, '/'))));
a9bee37e 1137 if ($contexts ==! '') {
f5930992 1138 if ($clauses) {
1139 $clauses .= ' OR ';
1140 }
1141 $clauses .= "(roleid=? AND contextid IN ($contexts))";
f33e1ed4 1142 $cparams[] = $roleid;
a9bee37e 1143 }
1144 }
f5930992 1145
d4c4ecb8 1146 if ($clauses !== '') {
1147 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
62e65b21
PS
1148 FROM {role_capabilities} rc
1149 JOIN {context} ctx ON rc.contextid=ctx.id
1150 WHERE $clauses";
f5930992 1151
d4c4ecb8 1152 unset($clauses);
f5930992 1153 $rs = $DB->get_recordset_sql($sql, $cparams);
a9bee37e 1154
0dbb2191 1155 if ($rs) {
f33e1ed4 1156 foreach ($rs as $rd) {
0dbb2191 1157 $k = "{$rd->path}:{$rd->roleid}";
1158 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1159 }
1160 unset($rd);
f33e1ed4 1161 $rs->close();
a9bee37e 1162 }
1163 }
a9bee37e 1164
1165 //
1166 // Overrides for the role assignments IN SUBCONTEXTS
1167 // (though we still do _not_ go below the course level.
1168 //
1169 // NOTE that the JOIN w sctx is with 3-way triangulation to
1170 // catch overrides to the applicable role in any subcontext, based
1171 // on the path field of the parent.
1172 //
1173 $sql = "SELECT sctx.path, ra.roleid,
1174 ctx.path AS parentpath,
1175 rco.capability, rco.permission
f33e1ed4 1176 FROM {role_assignments} ra
1177 JOIN {context} ctx
1178 ON ra.contextid=ctx.id
1179 JOIN {context} sctx
5a4e7398 1180 ON (sctx.path LIKE " . $DB->sql_concat('ctx.path',"'/%'"). " )
f33e1ed4 1181 JOIN {role_capabilities} rco
1182 ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
1183 WHERE ra.userid = ?
62e65b21
PS
1184 AND ctx.contextlevel <= ".CONTEXT_COURSECAT."
1185 AND sctx.contextlevel <= ".CONTEXT_COURSE."
f33e1ed4 1186 ORDER BY sctx.depth, sctx.path, ra.roleid";
1187 $params = array($userid);
1188 $rs = $DB->get_recordset_sql($sql, $params);
0dbb2191 1189 if ($rs) {
f33e1ed4 1190 foreach ($rs as $rd) {
0dbb2191 1191 $k = "{$rd->path}:{$rd->roleid}";
1192 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1193 }
1194 unset($rd);
f33e1ed4 1195 $rs->close();
a9bee37e 1196 }
bb2c22bd 1197 return $accessdata;
a9bee37e 1198}
1199
74ac5b66 1200/**
46808d7c 1201 * Add to the access ctrl array the data needed by a user for a given context
74ac5b66 1202 *
46808d7c 1203 * @param integer $userid the id of the user
1204 * @param object $context needs path!
1205 * @param array $accessdata accessdata array
62e65b21 1206 * @return void
74ac5b66 1207 */
a2cf7f1b 1208function load_subcontext($userid, $context, &$accessdata) {
f33e1ed4 1209 global $CFG, $DB;
018d4b52 1210
1211 /* Get the additional RAs and relevant rolecaps
74ac5b66 1212 * - role assignments - with role_caps
1213 * - relevant role caps
1214 * - above this user's RAs
1215 * - below this user's RAs - limited to course level
1216 */
1217
74ac5b66 1218 $base = "/" . SYSCONTEXTID;
1219
53fb75dc 1220 //
1221 // Replace $context with the target context we will
1222 // load. Normally, this will be a course context, but
1223 // may be a different top-level context.
1224 //
1225 // We have 3 cases
74ac5b66 1226 //
1227 // - Course
1228 // - BLOCK/PERSON/USER/COURSE(sitecourse) hanging from SYSTEM
1229 // - BLOCK/MODULE/GROUP hanging from a course
1230 //
1231 // For course contexts, we _already_ have the RAs
1232 // but the cost of re-fetching is minimal so we don't care.
74ac5b66 1233 //
5a4e7398 1234 if ($context->contextlevel !== CONTEXT_COURSE
53fb75dc 1235 && $context->path !== "$base/{$context->id}") {
1236 // Case BLOCK/MODULE/GROUP hanging from a course
74ac5b66 1237 // Assumption: the course _must_ be our parent
1238 // If we ever see stuff nested further this needs to
1239 // change to do 1 query over the exploded path to
1240 // find out which one is the course
c2f10673 1241 $courses = explode('/',get_course_from_path($context->path));
1242 $targetid = array_pop($courses);
53fb75dc 1243 $context = get_context_instance_by_id($targetid);
5a4e7398 1244
74ac5b66 1245 }
1246
1247 //
53fb75dc 1248 // Role assignments in the context and below
74ac5b66 1249 //
53fb75dc 1250 $sql = "SELECT ctx.path, ra.roleid
f33e1ed4 1251 FROM {role_assignments} ra
1252 JOIN {context} ctx
1253 ON ra.contextid=ctx.id
1254 WHERE ra.userid = ?
1255 AND (ctx.path = ? OR ctx.path LIKE ?)
082e777a 1256 ORDER BY ctx.depth, ctx.path, ra.roleid";
f33e1ed4 1257 $params = array($userid, $context->path, $context->path."/%");
1258 $rs = $DB->get_recordset_sql($sql, $params);
74ac5b66 1259
5a4e7398 1260 //
082e777a 1261 // Read in the RAs, preventing duplicates
018d4b52 1262 //
f33e1ed4 1263 if ($rs) {
1264 $localroles = array();
082e777a 1265 $lastseen = '';
f33e1ed4 1266 foreach ($rs as $ra) {
1267 if (!isset($accessdata['ra'][$ra->path])) {
1268 $accessdata['ra'][$ra->path] = array();
1269 }
082e777a 1270 // only add if is not a repeat caused
1271 // by capability join...
1272 // (this check is cheaper than in_array())
1273 if ($lastseen !== $ra->path.':'.$ra->roleid) {
1274 $lastseen = $ra->path.':'.$ra->roleid;
3c447ebe 1275 $accessdata['ra'][$ra->path][$ra->roleid] = $ra->roleid;
082e777a 1276 array_push($localroles, $ra->roleid);
1277 }
74ac5b66 1278 }
f33e1ed4 1279 $rs->close();
74ac5b66 1280 }
74ac5b66 1281
018d4b52 1282 //
53fb75dc 1283 // Walk up and down the tree to grab all the roledefs
74ac5b66 1284 // of interest to our user...
018d4b52 1285 //
53fb75dc 1286 // NOTES
1287 // - we use IN() but the number of roles is very limited.
1288 //
bb2c22bd 1289 $courseroles = aggregate_roles_from_accessdata($context, $accessdata);
53fb75dc 1290
1291 // Do we have any interesting "local" roles?
1292 $localroles = array_diff($localroles,$courseroles); // only "new" local roles
1293 $wherelocalroles='';
1294 if (count($localroles)) {
1295 // Role defs for local roles in 'higher' contexts...
1296 $contexts = substr($context->path, 1); // kill leading slash
1297 $contexts = str_replace('/', ',', $contexts);
1298 $localroleids = implode(',',$localroles);
5a4e7398 1299 $wherelocalroles="OR (rc.roleid IN ({$localroleids})
53fb75dc 1300 AND ctx.id IN ($contexts))" ;
74ac5b66 1301 }
1302
53fb75dc 1303 // We will want overrides for all of them
7e17f43b 1304 $whereroles = '';
1305 if ($roleids = implode(',',array_merge($courseroles,$localroles))) {
1306 $whereroles = "rc.roleid IN ($roleids) AND";
1307 }
53fb75dc 1308 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
f33e1ed4 1309 FROM {role_capabilities} rc
1310 JOIN {context} ctx
1311 ON rc.contextid=ctx.id
1312 WHERE ($whereroles
1313 (ctx.id=? OR ctx.path LIKE ?))
1314 $wherelocalroles
1315 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1316 $params = array($context->id, $context->path."/%");
53fb75dc 1317
a2cf7f1b 1318 $newrdefs = array();
afa559e9
EL
1319 $rs = $DB->get_recordset_sql($sql, $params);
1320 foreach ($rs as $rd) {
1321 $k = "{$rd->path}:{$rd->roleid}";
1322 if (!array_key_exists($k, $newrdefs)) {
1323 $newrdefs[$k] = array();
74ac5b66 1324 }
afa559e9 1325 $newrdefs[$k][$rd->capability] = $rd->permission;
74ac5b66 1326 }
afa559e9 1327 $rs->close();
74ac5b66 1328
a2cf7f1b 1329 compact_rdefs($newrdefs);
1330 foreach ($newrdefs as $key=>$value) {
1331 $accessdata['rdef'][$key] =& $newrdefs[$key];
1332 }
74ac5b66 1333
6100dad0 1334 // error_log("loaded {$context->path}");
bb2c22bd 1335 $accessdata['loaded'][] = $context->path;
74ac5b66 1336}
2f1a4248 1337
eef879ec 1338/**
46808d7c 1339 * Add to the access ctrl array the data needed by a role for a given context.
6f1bce30 1340 *
1341 * The data is added in the rdef key.
1342 *
1343 * This role-centric function is useful for role_switching
1344 * and to get an overview of what a role gets under a
1345 * given context and below...
1346 *
46808d7c 1347 * @param integer $roleid the id of the user
1348 * @param object $context needs path!
62e65b21 1349 * @param array $accessdata accessdata array null by default
46808d7c 1350 * @return array
6f1bce30 1351 */
62e65b21 1352function get_role_access_bycontext($roleid, $context, $accessdata = null) {
f33e1ed4 1353 global $CFG, $DB;
6f1bce30 1354
1355 /* Get the relevant rolecaps into rdef
1356 * - relevant role caps
1357 * - at ctx and above
1358 * - below this ctx
1359 */
1360
bb2c22bd 1361 if (is_null($accessdata)) {
1362 $accessdata = array(); // named list
1363 $accessdata['ra'] = array();
1364 $accessdata['rdef'] = array();
1365 $accessdata['loaded'] = array();
6f1bce30 1366 }
5a4e7398 1367
6f1bce30 1368 $contexts = substr($context->path, 1); // kill leading slash
1369 $contexts = str_replace('/', ',', $contexts);
1370
1371 //
1372 // Walk up and down the tree to grab all the roledefs
1373 // of interest to our role...
1374 //
1375 // NOTE: we use an IN clauses here - which
1376 // might explode on huge sites with very convoluted nesting of
1377 // categories... - extremely unlikely that the number of nested
1378 // categories is so large that we hit the limits of IN()
1379 //
1380 $sql = "SELECT ctx.path, rc.capability, rc.permission
f33e1ed4 1381 FROM {role_capabilities} rc
1382 JOIN {context} ctx
1383 ON rc.contextid=ctx.id
1384 WHERE rc.roleid=? AND
5a4e7398 1385 ( ctx.id IN ($contexts) OR
f33e1ed4 1386 ctx.path LIKE ? )
1387 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1388 $params = array($roleid, $context->path."/%");
1389
afa559e9
EL
1390 $rs = $DB->get_recordset_sql($sql, $params);
1391 foreach ($rs as $rd) {
1392 $k = "{$rd->path}:{$roleid}";
1393 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
6f1bce30 1394 }
afa559e9 1395 $rs->close();
6f1bce30 1396
bb2c22bd 1397 return $accessdata;
6f1bce30 1398}
1399
a2cf7f1b 1400/**
46808d7c 1401 * Load accessdata for a user into the $ACCESSLIB_PRIVATE->accessdatabyuser global
204a369c 1402 *
1403 * Used by has_capability() - but feel free
5a4e7398 1404 * to call it if you are about to run a BIG
204a369c 1405 * cron run across a bazillion users.
1406 *
46808d7c 1407 * @param int $userid
1408 * @return array returns ACCESSLIB_PRIVATE->accessdatabyuser[userid]
5a4e7398 1409 */
204a369c 1410function load_user_accessdata($userid) {
d867e696 1411 global $CFG, $ACCESSLIB_PRIVATE;
6f1bce30 1412
7293b3c6 1413 $base = '/'.SYSCONTEXTID;
204a369c 1414
bb2c22bd 1415 $accessdata = get_user_access_sitewide($userid);
5a4e7398 1416 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
3ac81bd1 1417 //
7293b3c6 1418 // provide "default role" & set 'dr'
3ac81bd1 1419 //
7d0c81b3 1420 if (!empty($CFG->defaultuserroleid)) {
1421 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1422 if (!isset($accessdata['ra'][$base])) {
3c447ebe 1423 $accessdata['ra'][$base] = array();
7d0c81b3 1424 }
3c447ebe 1425 $accessdata['ra'][$base][$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
7d0c81b3 1426 $accessdata['dr'] = $CFG->defaultuserroleid;
204a369c 1427 }
1428
4e1fe7d1 1429 //
1430 // provide "default frontpage role"
1431 //
3d811bc1 1432 if (!empty($CFG->defaultfrontpageroleid)) {
4e1fe7d1 1433 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
3d811bc1 1434 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
4e1fe7d1 1435 if (!isset($accessdata['ra'][$base])) {
3c447ebe 1436 $accessdata['ra'][$base] = array();
4e1fe7d1 1437 }
3c447ebe 1438 $accessdata['ra'][$base][$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
4e1fe7d1 1439 }
128f0984 1440 // for dirty timestamps in cron
1441 $accessdata['time'] = time();
1442
d867e696 1443 $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1444 compact_rdefs($ACCESSLIB_PRIVATE->accessdatabyuser[$userid]['rdef']);
a2cf7f1b 1445
d867e696 1446 return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
204a369c 1447}
ef989bd9 1448
a2cf7f1b 1449/**
4f65e0fb 1450 * Use shared copy of role definitions stored in ACCESSLIB_PRIVATE->roledefinitions;
cc3edaa4 1451 *
a2cf7f1b 1452 * @param array $rdefs array of role definitions in contexts
1453 */
1454function compact_rdefs(&$rdefs) {
d867e696 1455 global $ACCESSLIB_PRIVATE;
a2cf7f1b 1456
1457 /*
1458 * This is a basic sharing only, we could also
1459 * use md5 sums of values. The main purpose is to
d867e696 1460 * reduce mem in cron jobs - many users in $ACCESSLIB_PRIVATE->accessdatabyuser array.
a2cf7f1b 1461 */
1462
1463 foreach ($rdefs as $key => $value) {
d867e696 1464 if (!array_key_exists($key, $ACCESSLIB_PRIVATE->roledefinitions)) {
1465 $ACCESSLIB_PRIVATE->roledefinitions[$key] = $rdefs[$key];
a2cf7f1b 1466 }
d867e696 1467 $rdefs[$key] =& $ACCESSLIB_PRIVATE->roledefinitions[$key];
a2cf7f1b 1468 }
1469}
1470
6f1bce30 1471/**
46808d7c 1472 * A convenience function to completely load all the capabilities
1473 * for the current user. This is what gets called from complete_user_login()
1474 * for example. Call it only _after_ you've setup $USER and called
1475 * check_enrolment_plugins();
1476 * @see check_enrolment_plugins()
117bd748 1477 *
62e65b21 1478 * @return void
2f1a4248 1479 */
1480function load_all_capabilities() {
b545e27a
PS
1481 global $CFG, $ACCESSLIB_PRIVATE;
1482
1483 //NOTE: we can not use $USER here because it may no be linked to $_SESSION['USER'] yet!
bbbf2d40 1484
18818abf 1485 // roles not installed yet - we are in the middle of installation
31a99877 1486 if (during_initial_install()) {
1045a007 1487 return;
1488 }
1489
e0376a62 1490 $base = '/'.SYSCONTEXTID;
1491
b545e27a 1492 if (isguestuser($_SESSION['USER'])) {
e0376a62 1493 $guest = get_guest_role();
1494
1495 // Load the rdefs
b545e27a 1496 $_SESSION['USER']->access = get_role_access($guest->id);
e0376a62 1497 // Put the ghost enrolment in place...
3c447ebe 1498 $_SESSION['USER']->access['ra'][$base] = array($guest->id => $guest->id);
eef879ec 1499
7293b3c6 1500
f2b7f454 1501 } else if (!empty($_SESSION['USER']->id)) { // can not use isloggedin() yet
eef879ec 1502
b545e27a 1503 $accessdata = get_user_access_sitewide($_SESSION['USER']->id);
3887fe4a 1504
7293b3c6 1505 //
1506 // provide "default role" & set 'dr'
1507 //
7d0c81b3 1508 if (!empty($CFG->defaultuserroleid)) {
1509 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1510 if (!isset($accessdata['ra'][$base])) {
3c447ebe 1511 $accessdata['ra'][$base] = array();
7d0c81b3 1512 }
3c447ebe 1513 $accessdata['ra'][$base][$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
7d0c81b3 1514 $accessdata['dr'] = $CFG->defaultuserroleid;
c0aa9f09 1515 }
7293b3c6 1516
4e1fe7d1 1517 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
de5e137a 1518
4e1fe7d1 1519 //
1520 // provide "default frontpage role"
1521 //
3d811bc1 1522 if (!empty($CFG->defaultfrontpageroleid)) {
4e1fe7d1 1523 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1524 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1525 if (!isset($accessdata['ra'][$base])) {
3c447ebe 1526 $accessdata['ra'][$base] = array();
4e1fe7d1 1527 }
3c447ebe 1528 $accessdata['ra'][$base][$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
5a4e7398 1529 }
b545e27a 1530 $_SESSION['USER']->access = $accessdata;
5a4e7398 1531
7d0c81b3 1532 } else if (!empty($CFG->notloggedinroleid)) {
b545e27a 1533 $_SESSION['USER']->access = get_role_access($CFG->notloggedinroleid);
3c447ebe 1534 $_SESSION['USER']->access['ra'][$base] = array($CFG->notloggedinroleid => $CFG->notloggedinroleid);
2f1a4248 1535 }
55e68c29 1536
128f0984 1537 // Timestamp to read dirty context timestamps later
b545e27a 1538 $_SESSION['USER']->access['time'] = time();
d867e696 1539 $ACCESSLIB_PRIVATE->dirtycontexts = array();
55e68c29 1540
1541 // Clear to force a refresh
b545e27a 1542 unset($_SESSION['USER']->mycourses);
bbbf2d40 1543}
1544
ef989bd9 1545/**
5a4e7398 1546 * A convenience function to completely reload all the capabilities
ef989bd9 1547 * for the current user when roles have been updated in a relevant
5a4e7398 1548 * context -- but PRESERVING switchroles and loginas.
ef989bd9 1549 *
1550 * That is - completely transparent to the user.
5a4e7398 1551 *
ef989bd9 1552 * Note: rewrites $USER->access completely.
1553 *
62e65b21 1554 * @return void
ef989bd9 1555 */
1556function reload_all_capabilities() {
f33e1ed4 1557 global $USER, $DB;
ef989bd9 1558
b738808b 1559 // error_log("reloading");
ef989bd9 1560 // copy switchroles
1561 $sw = array();
1562 if (isset($USER->access['rsw'])) {
1563 $sw = $USER->access['rsw'];
b738808b 1564 // error_log(print_r($sw,1));
ef989bd9 1565 }
1566
1567 unset($USER->access);
54f9d9ae 1568 unset($USER->mycourses);
5a4e7398 1569
ef989bd9 1570 load_all_capabilities();
1571
1572 foreach ($sw as $path => $roleid) {
f33e1ed4 1573 $context = $DB->get_record('context', array('path'=>$path));
ef989bd9 1574 role_switch($roleid, $context);
1575 }
1576
1577}
2f1a4248 1578
f33e1ed4 1579/**
343effbe 1580 * Adds a temp role to an accessdata array.
1581 *
1582 * Useful for the "temporary guest" access
1583 * we grant to logged-in users.
1584 *
1585 * Note - assumes a course context!
1586 *
46808d7c 1587 * @param object $content
1588 * @param int $roleid
1589 * @param array $accessdata
1590 * @return array Returns access data
343effbe 1591 */
df997f84 1592function load_temp_role($context, $roleid, array $accessdata) {
f33e1ed4 1593 global $CFG, $DB;
343effbe 1594
1595 //
1596 // Load rdefs for the role in -
1597 // - this context
1598 // - all the parents
1599 // - and below - IOWs overrides...
1600 //
5a4e7398 1601
343effbe 1602 // turn the path into a list of context ids
1603 $contexts = substr($context->path, 1); // kill leading slash
1604 $contexts = str_replace('/', ',', $contexts);
1605
f33e1ed4 1606 $sql = "SELECT ctx.path, rc.capability, rc.permission
1607 FROM {context} ctx
1608 JOIN {role_capabilities} rc
1609 ON rc.contextid=ctx.id
1610 WHERE (ctx.id IN ($contexts)
1611 OR ctx.path LIKE ?)
1612 AND rc.roleid = ?
1613 ORDER BY ctx.depth, ctx.path";
5a4e7398 1614 $params = array($context->path."/%", $roleid);
afa559e9
EL
1615 $rs = $DB->get_recordset_sql($sql, $params);
1616 foreach ($rs as $rd) {
1617 $k = "{$rd->path}:{$roleid}";
1618 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
f33e1ed4 1619 }
afa559e9 1620 $rs->close();
343effbe 1621
1622 //
1623 // Say we loaded everything for the course context
1624 // - which we just did - if the user gets a proper
1625 // RA in this session, this data will need to be reloaded,
1626 // but that is handled by the complete accessdata reload
1627 //
bb2c22bd 1628 array_push($accessdata['loaded'], $context->path);
343effbe 1629
1630 //
1631 // Add the ghost RA
1632 //
3c447ebe
PS
1633 if (!isset($accessdata['ra'][$context->path])) {
1634 $accessdata['ra'][$context->path] = array();
343effbe 1635 }
3c447ebe 1636 $accessdata['ra'][$context->path][$roleid] = $roleid;
343effbe 1637
bb2c22bd 1638 return $accessdata;
343effbe 1639}
1640
efe12f6c 1641/**
3c447ebe 1642 * Removes any extra guest roles from accessdata
df997f84
PS
1643 * @param object $context
1644 * @param array $accessdata
1645 * @return array access data
64026e8c 1646 */
df997f84
PS
1647function remove_temp_roles($context, array $accessdata) {
1648 global $DB, $USER;
1649 $sql = "SELECT DISTINCT ra.roleid AS id
1650 FROM {role_assignments} ra
1651 WHERE ra.contextid = :contextid AND ra.userid = :userid";
1652 $ras = $DB->get_records_sql($sql, array('contextid'=>$context->id, 'userid'=>$USER->id));
e4ec4e41 1653
0831484c
PS
1654 if ($ras) {
1655 $accessdata['ra'][$context->path] = array_combine(array_keys($ras), array_keys($ras));
1656 } else {
1657 $accessdata['ra'][$context->path] = array();
1658 }
1659
df997f84 1660 return $accessdata;
64026e8c 1661}
1662
3562486b 1663/**
4f0c2d00 1664 * Returns array of all role archetypes.
cc3edaa4 1665 *
46808d7c 1666 * @return array
3562486b 1667 */
4f0c2d00 1668function get_role_archetypes() {
3562486b 1669 return array(
4f0c2d00
PS
1670 'manager' => 'manager',
1671 'coursecreator' => 'coursecreator',
1672 'editingteacher' => 'editingteacher',
1673 'teacher' => 'teacher',
1674 'student' => 'student',
1675 'guest' => 'guest',
1676 'user' => 'user',
1677 'frontpage' => 'frontpage'
3562486b 1678 );
1679}
1680
bbbf2d40 1681/**
4f65e0fb 1682 * Assign the defaults found in this capability definition to roles that have
bbbf2d40 1683 * the corresponding legacy capabilities assigned to them.
cc3edaa4 1684 *
46808d7c 1685 * @param string $capability
1686 * @param array $legacyperms an array in the format (example):
bbbf2d40 1687 * 'guest' => CAP_PREVENT,
1688 * 'student' => CAP_ALLOW,
1689 * 'teacher' => CAP_ALLOW,
1690 * 'editingteacher' => CAP_ALLOW,
1691 * 'coursecreator' => CAP_ALLOW,
4f0c2d00 1692 * 'manager' => CAP_ALLOW
46808d7c 1693 * @return boolean success or failure.
bbbf2d40 1694 */
1695function assign_legacy_capabilities($capability, $legacyperms) {
eef868d1 1696
4f0c2d00 1697 $archetypes = get_role_archetypes();
3562486b 1698
bbbf2d40 1699 foreach ($legacyperms as $type => $perm) {
eef868d1 1700
21c9bace 1701 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
4f0c2d00
PS
1702 if ($type === 'admin') {
1703 debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1704 $type = 'manager';
1705 }
eef868d1 1706
4f0c2d00 1707 if (!array_key_exists($type, $archetypes)) {
e49ef64a 1708 print_error('invalidlegacy', '', '', $type);
3562486b 1709 }
eef868d1 1710
4f0c2d00 1711 if ($roles = get_archetype_roles($type)) {
2e85fffe 1712 foreach ($roles as $role) {
1713 // Assign a site level capability.
1714 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1715 return false;
1716 }
bbbf2d40 1717 }
1718 }
1719 }
1720 return true;
1721}
1722
faf75fe7 1723/**
ed149942
PS
1724 * @param object $capability a capability - a row from the capabilities table.
1725 * @return boolean whether this capability is safe - that is, whether people with the
faf75fe7 1726 * safeoverrides capability should be allowed to change it.
1727 */
1728function is_safe_capability($capability) {
4659454a 1729 return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
faf75fe7 1730}
cee0901c 1731
1732/**********************************
bbbf2d40 1733 * Context Manipulation functions *
1734 **********************************/
1735
bbbf2d40 1736/**
a0760047 1737 * Context creation - internal implementation.
46808d7c 1738 *
9991d157 1739 * Create a new context record for use by all roles-related stuff
4881f2d3 1740 * assumes that the caller has done the homework.
1741 *
a0760047
PS
1742 * DO NOT CALL THIS DIRECTLY, instead use {@link get_context_instance}!
1743 *
46808d7c 1744 * @param int $contextlevel
1745 * @param int $instanceid
4f0c2d00 1746 * @param int $strictness
e40413be 1747 * @return object newly created context
bbbf2d40 1748 */
62e65b21 1749function create_context($contextlevel, $instanceid, $strictness = IGNORE_MISSING) {
5a4e7398 1750 global $CFG, $DB;
e40413be 1751
4881f2d3 1752 if ($contextlevel == CONTEXT_SYSTEM) {
7875b1fd 1753 return get_system_context();
4881f2d3 1754 }
c421ad4b 1755
365a5941 1756 $context = new stdClass();
4881f2d3 1757 $context->contextlevel = $contextlevel;
1758 $context->instanceid = $instanceid;
e40413be 1759
1760 // Define $context->path based on the parent
1761 // context. In other words... Who is your daddy?
ca92b391 1762 $basepath = '/' . SYSCONTEXTID;
1763 $basedepth = 1;
e40413be 1764
7d0c81b3 1765 $result = true;
62e65b21 1766 $error_message = null;
7d0c81b3 1767
e40413be 1768 switch ($contextlevel) {
1769 case CONTEXT_COURSECAT:
5a4e7398 1770 $sql = "SELECT ctx.path, ctx.depth
1771 FROM {context} ctx
1772 JOIN {course_categories} cc
1773 ON (cc.parent=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
1774 WHERE cc.id=?";
1775 $params = array($instanceid);
1776 if ($p = $DB->get_record_sql($sql, $params)) {
ca92b391 1777 $basepath = $p->path;
1778 $basedepth = $p->depth;
4f0c2d00 1779 } else if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), '*', $strictness)) {
7d0c81b3 1780 if (empty($category->parent)) {
1781 // ok - this is a top category
1782 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $category->parent)) {
1783 $basepath = $parent->path;
1784 $basedepth = $parent->depth;
1785 } else {
1786 // wrong parent category - no big deal, this can be fixed later
62e65b21 1787 $basepath = null;
7d0c81b3 1788 $basedepth = 0;
1789 }
1790 } else {
1791 // incorrect category id
f689028c 1792 $error_message = "incorrect course category id ($instanceid)";
7d0c81b3 1793 $result = false;
e40413be 1794 }
1795 break;
1796
1797 case CONTEXT_COURSE:
ca92b391 1798 $sql = "SELECT ctx.path, ctx.depth
5a4e7398 1799 FROM {context} ctx
1800 JOIN {course} c
1801 ON (c.category=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
1802 WHERE c.id=? AND c.id !=" . SITEID;
1803 $params = array($instanceid);
1804 if ($p = $DB->get_record_sql($sql, $params)) {
ca92b391 1805 $basepath = $p->path;
1806 $basedepth = $p->depth;
4f0c2d00 1807 } else if ($course = $DB->get_record('course', array('id'=>$instanceid), '*', $strictness)) {
7d0c81b3 1808 if ($course->id == SITEID) {
1809 //ok - no parent category
1810 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
1811 $basepath = $parent->path;
1812 $basedepth = $parent->depth;
1813 } else {
1814 // wrong parent category of course - no big deal, this can be fixed later
62e65b21 1815 $basepath = null;
7d0c81b3 1816 $basedepth = 0;
1817 }
1818 } else if ($instanceid == SITEID) {
1819 // no errors for missing site course during installation
1820 return false;
1821 } else {
1822 // incorrect course id
f689028c 1823 $error_message = "incorrect course id ($instanceid)";
7d0c81b3 1824 $result = false;
e40413be 1825 }
1826 break;
1827
1828 case CONTEXT_MODULE:
ca92b391 1829 $sql = "SELECT ctx.path, ctx.depth
5a4e7398 1830 FROM {context} ctx
1831 JOIN {course_modules} cm
1832 ON (cm.course=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
1833 WHERE cm.id=?";
1834 $params = array($instanceid);
1835 if ($p = $DB->get_record_sql($sql, $params)) {
7d0c81b3 1836 $basepath = $p->path;
1837 $basedepth = $p->depth;
4f0c2d00
PS
1838 } else if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), '*', $strictness)) {
1839 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course, $strictness)) {
7d0c81b3 1840 $basepath = $parent->path;
1841 $basedepth = $parent->depth;
1842 } else {
1843 // course does not exist - modules can not exist without a course
f689028c 1844 $error_message = "course does not exist ($cm->course) - modules can not exist without a course";
7d0c81b3 1845 $result = false;
1846 }
1847 } else {
1848 // cm does not exist
837e6a44 1849 $error_message = "cm with id $instanceid does not exist";
7d0c81b3 1850 $result = false;
1851 }
e40413be 1852 break;
1853
1854 case CONTEXT_BLOCK:
ca92b391 1855 $sql = "SELECT ctx.path, ctx.depth
f474a4e5 1856 FROM {context} ctx
13a0d3d3 1857 JOIN {block_instances} bi ON (bi.parentcontextid=ctx.id)
e92c286c 1858 WHERE bi.id = ?";
f474a4e5 1859 $params = array($instanceid, CONTEXT_COURSE);
4f0c2d00 1860 if ($p = $DB->get_record_sql($sql, $params, '*', $strictness)) {
ca92b391 1861 $basepath = $p->path;
1862 $basedepth = $p->depth;
7d0c81b3 1863 } else {
1864 // block does not exist
f474a4e5 1865 $error_message = 'block or parent context does not exist';
7d0c81b3 1866 $result = false;
ca92b391 1867 }
e40413be 1868 break;
1869 case CONTEXT_USER:
1870 // default to basepath
1871 break;
e40413be 1872 }
1873
7d0c81b3 1874 // if grandparents unknown, maybe rebuild_context_path() will solve it later
1875 if ($basedepth != 0) {
1876 $context->depth = $basedepth+1;
1877 }
1878
4f0c2d00 1879 if (!$result) {
4881f2d3 1880 debugging('Error: could not insert new context level "'.
1881 s($contextlevel).'", instance "'.
f689028c 1882 s($instanceid).'". ' . $error_message);
1883
7d0c81b3 1884 return false;
bbbf2d40 1885 }
4f0c2d00
PS
1886
1887 $id = $DB->insert_record('context', $context);
1888 // can't set the full path till we know the id!
1889 if ($basedepth != 0 and !empty($basepath)) {
1890 $DB->set_field('context', 'path', $basepath.'/'. $id, array('id'=>$id));
1891 }
1892 return get_context_instance_by_id($id);
bbbf2d40 1893}
1894
efe12f6c 1895/**
62e65b21 1896 * Returns system context or null if can not be created yet.
46808d7c 1897 *
0ecff22d 1898 * @param bool $cache use caching
62e65b21 1899 * @return mixed system context or null
8ba412da 1900 */
62e65b21 1901function get_system_context($cache = true) {
d867e696 1902 global $DB, $ACCESSLIB_PRIVATE;
7d0c81b3 1903 if ($cache and defined('SYSCONTEXTID')) {
d867e696 1904 if (is_null($ACCESSLIB_PRIVATE->systemcontext)) {
365a5941 1905 $ACCESSLIB_PRIVATE->systemcontext = new stdClass();
d867e696 1906 $ACCESSLIB_PRIVATE->systemcontext->id = SYSCONTEXTID;
1907 $ACCESSLIB_PRIVATE->systemcontext->contextlevel = CONTEXT_SYSTEM;
1908 $ACCESSLIB_PRIVATE->systemcontext->instanceid = 0;
1909 $ACCESSLIB_PRIVATE->systemcontext->path = '/'.SYSCONTEXTID;
1910 $ACCESSLIB_PRIVATE->systemcontext->depth = 1;
7d0c81b3 1911 }
d867e696 1912 return $ACCESSLIB_PRIVATE->systemcontext;
7d0c81b3 1913 }
c23b0ea1 1914 try {
df97c6ee 1915 $context = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM));
0ecff22d 1916 } catch (dml_exception $e) {
c23b0ea1 1917 //table does not exist yet, sorry
62e65b21 1918 return null;
c23b0ea1 1919 }
1920
1921 if (!$context) {
365a5941 1922 $context = new stdClass();
8ba412da 1923 $context->contextlevel = CONTEXT_SYSTEM;
7d0c81b3 1924 $context->instanceid = 0;
1925 $context->depth = 1;
62e65b21 1926 $context->path = null; //not known before insert
7d0c81b3 1927
0ecff22d 1928 try {
a8f3a651 1929 $context->id = $DB->insert_record('context', $context);
0ecff22d 1930 } catch (dml_exception $e) {
a8f3a651 1931 // can not create context yet, sorry
62e65b21 1932 return null;
8ba412da 1933 }
1934 }
7d0c81b3 1935
1936 if (!isset($context->depth) or $context->depth != 1 or $context->instanceid != 0 or $context->path != '/'.$context->id) {
1937 $context->instanceid = 0;
1938 $context->path = '/'.$context->id;
1939 $context->depth = 1;
5a4e7398 1940 $DB->update_record('context', $context);
7d0c81b3 1941 }
1942
1943 if (!defined('SYSCONTEXTID')) {
1944 define('SYSCONTEXTID', $context->id);
1945 }
1946
d867e696 1947 $ACCESSLIB_PRIVATE->systemcontext = $context;
1948 return $ACCESSLIB_PRIVATE->systemcontext;
8ba412da 1949}
b51ece5b 1950
9991d157 1951/**
b51ece5b 1952 * Remove a context record and any dependent entries,
1953 * removes context from static context cache too
cc3edaa4 1954 *
46808d7c 1955 * @param int $level
1956 * @param int $instanceid
582bae08 1957 * @param bool $deleterecord false means keep record for now
196f1a25 1958 * @return bool returns true or throws an exception
9991d157 1959 */
582bae08 1960function delete_context($contextlevel, $instanceid, $deleterecord = true) {
8432f5e6 1961 global $DB, $ACCESSLIB_PRIVATE, $CFG;
b51ece5b 1962
1963 // do not use get_context_instance(), because the related object might not exist,
1964 // or the context does not exist yet and it would be created now
5a4e7398 1965 if ($context = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
582bae08
PS
1966 // delete these first because they might fetch the context and try to recreate it!
1967 blocks_delete_all_for_context($context->id);
1968 filter_delete_all_for_context($context->id);
2ac56258 1969
582bae08
PS
1970 require_once($CFG->dirroot . '/comment/lib.php');
1971 comment::delete_comments(array('contextid'=>$context->id));
b51ece5b 1972
2ac56258
AD
1973 require_once($CFG->dirroot.'/rating/lib.php');
1974 $delopt = new stdclass();
1975 $delopt->contextid = $context->id;
1976 $rm = new rating_manager();
1977 $rm->delete_ratings($delopt);
1978
a05bcfba
PS
1979 // delete all files attached to this context
1980 $fs = get_file_storage();
1981 $fs->delete_area_files($context->id);
1982
582bae08
PS
1983 // now delete stuff from role related tables, role_unassign_all
1984 // and unenrol should be called earlier to do proper cleanup
1985 $DB->delete_records('role_assignments', array('contextid'=>$context->id));
1986 $DB->delete_records('role_capabilities', array('contextid'=>$context->id));
1987 $DB->delete_records('role_names', array('contextid'=>$context->id));
1988
1989 // and finally it is time to delete the context record if requested
1990 if ($deleterecord) {
1991 $DB->delete_records('context', array('id'=>$context->id));
1992 // purge static context cache if entry present
d0e538ba 1993 $ACCESSLIB_PRIVATE->contexcache->remove($context);
582bae08
PS
1994 }
1995
b51ece5b 1996 // do not mark dirty contexts if parents unknown
1997 if (!is_null($context->path) and $context->depth > 0) {
1998 mark_context_dirty($context->path);
1999 }
9991d157 2000 }
196f1a25
PS
2001
2002 return true;
9991d157 2003}
2004
9a81a606 2005/**
2006 * Precreates all contexts including all parents
cc3edaa4 2007 *
46808d7c 2008 * @param int $contextlevel empty means all
9a81a606 2009 * @param bool $buildpaths update paths and depths
2010 * @return void
2011 */
62e65b21 2012function create_contexts($contextlevel = null, $buildpaths = true) {
5a4e7398 2013 global $DB;
9a81a606 2014
2015 //make sure system context exists
2016 $syscontext = get_system_context(false);
2017
5c8e6cb1 2018 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSECAT
2019 or $contextlevel == CONTEXT_COURSE
2020 or $contextlevel == CONTEXT_MODULE
2021 or $contextlevel == CONTEXT_BLOCK) {
5a4e7398 2022 $sql = "INSERT INTO {context} (contextlevel, instanceid)
9a81a606 2023 SELECT ".CONTEXT_COURSECAT.", cc.id
5a4e7398 2024 FROM {course}_categories cc
9a81a606 2025 WHERE NOT EXISTS (SELECT 'x'
5a4e7398 2026 FROM {context} cx
9a81a606 2027 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
5a4e7398 2028 $DB->execute($sql);
9a81a606 2029
2030 }
2031
5c8e6cb1 2032 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSE
2033 or $contextlevel == CONTEXT_MODULE
2034 or $contextlevel == CONTEXT_BLOCK) {
5a4e7398 2035 $sql = "INSERT INTO {context} (contextlevel, instanceid)
9a81a606 2036 SELECT ".CONTEXT_COURSE.", c.id
5a4e7398 2037 FROM {course} c
9a81a606 2038 WHERE NOT EXISTS (SELECT 'x'
5a4e7398 2039 FROM {context} cx
9a81a606 2040 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
5a4e7398 2041 $DB->execute($sql);
9a81a606 2042
2043 }
2044
e92c286c 2045 if (empty($contextlevel) or $contextlevel == CONTEXT_MODULE
2046 or $contextlevel == CONTEXT_BLOCK) {
5a4e7398 2047 $sql = "INSERT INTO {context} (contextlevel, instanceid)
9a81a606 2048 SELECT ".CONTEXT_MODULE.", cm.id
5a4e7398 2049 FROM {course}_modules cm
9a81a606 2050 WHERE NOT EXISTS (SELECT 'x'
5a4e7398 2051 FROM {context} cx
9a81a606 2052 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
5a4e7398 2053 $DB->execute($sql);
9a81a606 2054 }
2055
e92c286c 2056 if (empty($contextlevel) or $contextlevel == CONTEXT_USER
2057 or $contextlevel == CONTEXT_BLOCK) {
5a4e7398 2058 $sql = "INSERT INTO {context} (contextlevel, instanceid)
9a81a606 2059 SELECT ".CONTEXT_USER.", u.id
5a4e7398 2060 FROM {user} u
9a81a606 2061 WHERE u.deleted=0
2062 AND NOT EXISTS (SELECT 'x'
5a4e7398 2063 FROM {context} cx
9a81a606 2064 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
5a4e7398 2065 $DB->execute($sql);
9a81a606 2066
2067 }
2068
e92c286c 2069 if (empty($contextlevel) or $contextlevel == CONTEXT_BLOCK) {
2070 $sql = "INSERT INTO {context} (contextlevel, instanceid)
2071 SELECT ".CONTEXT_BLOCK.", bi.id
2072 FROM {block_instances} bi
2073 WHERE NOT EXISTS (SELECT 'x'
2074 FROM {context} cx
2075 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
2076 $DB->execute($sql);
2077 }
2078
9a81a606 2079 if ($buildpaths) {
5a4e7398 2080 build_context_path(false);
9a81a606 2081 }
2082}
2083
17b0efae 2084/**
2085 * Remove stale context records
2086 *
2087 * @return bool
2088 */
2089function cleanup_contexts() {
5a4e7398 2090 global $DB;
17b0efae 2091
70dd126e 2092 $sql = " SELECT c.contextlevel,
17b0efae 2093 c.instanceid AS instanceid
5a4e7398 2094 FROM {context} c
2095 LEFT OUTER JOIN {course}_categories t
2096 ON c.instanceid = t.id
2097 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
17b0efae 2098 UNION
70dd126e 2099 SELECT c.contextlevel,
2100 c.instanceid
5a4e7398 2101 FROM {context} c
2102 LEFT OUTER JOIN {course} t
2103 ON c.instanceid = t.id
2104 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
17b0efae 2105 UNION
70dd126e 2106 SELECT c.contextlevel,
2107 c.instanceid
5a4e7398 2108 FROM {context} c
2109 LEFT OUTER JOIN {course}_modules t
2110 ON c.instanceid = t.id
2111 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
17b0efae 2112 UNION
70dd126e 2113 SELECT c.contextlevel,
2114 c.instanceid
5a4e7398 2115 FROM {context} c
2116 LEFT OUTER JOIN {user} t
2117 ON c.instanceid = t.id
2118 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
17b0efae 2119 UNION
70dd126e 2120 SELECT c.contextlevel,
2121 c.instanceid
5a4e7398 2122 FROM {context} c
f474a4e5 2123 LEFT OUTER JOIN {block_instances} t
2124 ON c.instanceid = t.id
5a4e7398 2125 WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
17b0efae 2126 ";
d5a8d9aa
PS
2127
2128 // transactions used only for performance reasons here
2129 $transaction = $DB->start_delegated_transaction();
2130
afa559e9
EL
2131 $rs = $DB->get_recordset_sql($sql);
2132 foreach ($rs as $ctx) {
2133 delete_context($ctx->contextlevel, $ctx->instanceid);
17b0efae 2134 }
afa559e9 2135 $rs->close();
d5a8d9aa
PS
2136
2137 $transaction->allow_commit();
17b0efae 2138 return true;
2139}
2140
00653161 2141/**
e92c286c 2142 * Preloads all contexts relating to a course: course, modules. Block contexts
2143 * are no longer loaded here. The contexts for all the blocks on the current
2144 * page are now efficiently loaded by {@link block_manager::load_blocks()}.
00653161 2145 *
2146 * @param int $courseid Course ID
d993468d 2147 * @return void
00653161 2148 */
2149function preload_course_contexts($courseid) {
d867e696 2150 global $DB, $ACCESSLIB_PRIVATE;
00653161 2151
2152 // Users can call this multiple times without doing any harm
d867e696 2153 global $ACCESSLIB_PRIVATE;
2154 if (array_key_exists($courseid, $ACCESSLIB_PRIVATE->preloadedcourses)) {
00653161 2155 return;
2156 }
2157
d993468d 2158 $params = array($courseid, $courseid, $courseid);
2159 $sql = "SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
2160 FROM {course_modules} cm
2161 JOIN {context} x ON x.instanceid=cm.id
2162 WHERE cm.course=? AND x.contextlevel=".CONTEXT_MODULE."
2163
d993468d 2164 UNION ALL
2165
2166 SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
2167 FROM {context} x
2168 WHERE x.instanceid=? AND x.contextlevel=".CONTEXT_COURSE."";
2169
2170 $rs = $DB->get_recordset_sql($sql, $params);
00653161 2171 foreach($rs as $context) {
d0e538ba 2172 $ACCESSLIB_PRIVATE->contexcache->add($context);
00653161 2173 }
2174 $rs->close();
d867e696 2175 $ACCESSLIB_PRIVATE->preloadedcourses[$courseid] = true;
00653161 2176}
2177
bbbf2d40 2178/**
2179 * Get the context instance as an object. This function will create the
2180 * context instance if it does not exist yet.
46808d7c 2181 *
2182 * @todo Remove code branch from previous fix MDL-9016 which is no longer needed
2183 *
e765b5d3 2184 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2185 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
46808d7c 2186 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
4f0c2d00
PS
2187 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
2188 * MUST_EXIST means throw exception if no record or multiple records found
e765b5d3 2189 * @return object The context object.
bbbf2d40 2190 */
62e65b21 2191function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING) {
d867e696 2192 global $DB, $ACCESSLIB_PRIVATE;
8ead7b59 2193 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK);
d9a35e12 2194
7d0c81b3 2195/// System context has special cache
8ba412da 2196 if ($contextlevel == CONTEXT_SYSTEM) {
7d0c81b3 2197 return get_system_context();
8ba412da 2198 }
2199
a36a3a3f 2200/// check allowed context levels
2201 if (!in_array($contextlevel, $allowed_contexts)) {
7bfa3101 2202 // fatal error, code must be fixed - probably typo or switched parameters
e49ef64a 2203 print_error('invalidcourselevel');
a36a3a3f 2204 }
2205
d0e538ba
PS
2206 // Various operations rely on context cache
2207 $cache = $ACCESSLIB_PRIVATE->contexcache;
2208
65bcf17b 2209 if (!is_array($instance)) {
2210 /// Check the cache
d0e538ba
PS
2211 $context = $cache->get($contextlevel, $instance);
2212 if ($context) {
2213 return $context;
65bcf17b 2214 }
2215
2216 /// Get it from the database, or create it
5a4e7398 2217 if (!$context = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instance))) {
4f0c2d00 2218 $context = create_context($contextlevel, $instance, $strictness);
65bcf17b 2219 }
2220
2221 /// Only add to cache if context isn't empty.
2222 if (!empty($context)) {
d0e538ba 2223 $cache->add($context);
65bcf17b 2224 }
2225
2226 return $context;
e5605780 2227 }
2228
65bcf17b 2229
2230/// ok, somebody wants to load several contexts to save some db queries ;-)
2231 $instances = $instance;
2232 $result = array();
2233
2234 foreach ($instances as $key=>$instance) {
2235 /// Check the cache first
d0e538ba
PS
2236 if ($context = $cache->get($contextlevel, $instance)) { // Already cached
2237 $result[$instance] = $context;
65bcf17b 2238 unset($instances[$key]);
2239 continue;
2240 }
e5605780 2241 }
2242
65bcf17b 2243 if ($instances) {
5a4e7398 2244 list($instanceids, $params) = $DB->get_in_or_equal($instances, SQL_PARAMS_QM);
2245 array_unshift($params, $contextlevel);
2246 $sql = "SELECT instanceid, id, contextlevel, path, depth
2247 FROM {context}
2248 WHERE contextlevel=? AND instanceid $instanceids";
2249
2250 if (!$contexts = $DB->get_records_sql($sql, $params)) {
65bcf17b 2251 $contexts = array();
2252 }
2253
2254 foreach ($instances as $instance) {
2255 if (isset($contexts[$instance])) {
2256 $context = $contexts[$instance];
2257 } else {
2258 $context = create_context($contextlevel, $instance);
2259 }
2260
2261 if (!empty($context)) {
d0e538ba 2262 $cache->add($context);
65bcf17b 2263 }
2264
2265 $result[$instance] = $context;
2266 }
ccfc5ecc 2267 }
0468976c 2268
65bcf17b 2269 return $result;
bbbf2d40 2270}
2271
cee0901c 2272
340ea4e8 2273/**
e765b5d3 2274 * Get a context instance as an object, from a given context id.
cc3edaa4 2275 *
62e65b21 2276 * @param int $id context id
01a2ce80
PS
2277 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
2278 * MUST_EXIST means throw exception if no record or multiple records found
62e65b21 2279 * @return stdClass|bool the context object or false if not found.
340ea4e8 2280 */
62e65b21 2281function get_context_instance_by_id($id, $strictness = IGNORE_MISSING) {
d867e696 2282 global $DB, $ACCESSLIB_PRIVATE;
d9a35e12 2283
7d0c81b3 2284 if ($id == SYSCONTEXTID) {
2285 return get_system_context();
2286 }
2287
d0e538ba
PS
2288 $cache = $ACCESSLIB_PRIVATE->contexcache;
2289 if ($context = $cache->get_by_id($id)) {
2290 return $context;
340ea4e8 2291 }
2292
01a2ce80 2293 if ($context = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
d0e538ba 2294 $cache->add($context);
340ea4e8 2295 return $context;
2296 }
2297
2298 return false;
2299}
2300
bbbf2d40 2301
8737be58 2302/**
2303 * Get the local override (if any) for a given capability in a role in a context
cc3edaa4 2304 *
46808d7c 2305 * @param int $roleid
2306 * @param int $contextid
2307 * @param string $capability
8737be58 2308 */
2309function get_local_override($roleid, $contextid, $capability) {
5a4e7398 2310 global $DB;
2311 return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
8737be58 2312}
2313
01a2ce80
PS
2314/**
2315 * Returns context instance plus related course and cm instances
2316 * @param int $contextid
2317 * @return array of ($context, $course, $cm)
2318 */
2319function get_context_info_array($contextid) {
2320 global $DB;
2321
2322 $context = get_context_instance_by_id($contextid, MUST_EXIST);
62e65b21
PS
2323 $course = null;
2324 $cm = null;
01a2ce80
PS
2325
2326 if ($context->contextlevel == CONTEXT_COURSE) {
2327 $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
2328
2329 } else if ($context->contextlevel == CONTEXT_MODULE) {
2330 $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
2331 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
2332
2333 } else if ($context->contextlevel == CONTEXT_BLOCK) {
2334 $parentcontexts = get_parent_contexts($context, false);
2335 $parent = reset($parentcontexts);
2336 $parent = get_context_instance_by_id($parent);
2337
2338 if ($parent->contextlevel == CONTEXT_COURSE) {
2339 $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
2340 } else if ($parent->contextlevel == CONTEXT_MODULE) {
2341 $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
2342 $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
2343 }
2344 }
2345
2346 return array($context, $course, $cm);
2347}
8737be58 2348
35716b86
PS
2349/**
2350 * Returns current course id or null if outside of course based on context parameter.
2351 * @param object $context
2352 * @return int|bool related course id or false
2353 */
2354function get_courseid_from_context($context) {
2355 if ($context->contextlevel == CONTEXT_COURSE) {
2356 return $context->instanceid;
2357 }
2358
2359 if ($context->contextlevel < CONTEXT_COURSE) {
2360 return false;
2361 }
2362
2363 if ($context->contextlevel == CONTEXT_MODULE) {
2364 $parentcontexts = get_parent_contexts($context, false);
2365 $parent = reset($parentcontexts);
2366 $parent = get_context_instance_by_id($parent);
2367 return $parent->instanceid;
2368 }
2369
2370 if ($context->contextlevel == CONTEXT_BLOCK) {
2371 $parentcontexts = get_parent_contexts($context, false);
2372 $parent = reset($parentcontexts);
2373 return get_courseid_from_context($parent);
2374 }
2375
2376 return false;
2377}
2378
bbbf2d40 2379
46808d7c 2380//////////////////////////////////////
2381// DB TABLE RELATED FUNCTIONS //
2382//////////////////////////////////////
bbbf2d40 2383
cee0901c 2384/**
bbbf2d40 2385 * function that creates a role
cc3edaa4 2386 *
46808d7c 2387 * @param string $name role name
2388 * @param string $shortname role short name
2389 * @param string $description role description
4f0c2d00 2390 * @param string $archetype
62e65b21 2391 * @return int id or dml_exception
bbbf2d40 2392 */
62e65b21 2393function create_role($name, $shortname, $description, $archetype = '') {
f33e1ed4 2394 global $DB;
eef868d1 2395
4f0c2d00
PS
2396 if (strpos($archetype, 'moodle/legacy:') !== false) {
2397 throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
2398 }
2399
2400 // verify role archetype actually exists
2401 $archetypes = get_role_archetypes();
2402 if (empty($archetypes[$archetype])) {
2403 $archetype = '';
2404 }
2405
bbdb7070 2406 // Get the system context.
19a4a32e 2407 $context = get_context_instance(CONTEXT_SYSTEM);
31f26796 2408
bbdb7070 2409 // Insert the role record.
365a5941 2410 $role = new stdClass();
ac173d3e 2411 $role->name = $name;
2412 $role->shortname = $shortname;
98882637 2413 $role->description = $description;
4f0c2d00 2414 $role->archetype = $archetype;
eef868d1 2415
8420bee9 2416 //find free sortorder number
bbdb7070 2417 $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
716dd163 2418 if (empty($role->sortorder)) {
2419 $role->sortorder = 1;
2420 }
bbdb7070 2421 $id = $DB->insert_record('role', $role);
b5959f30 2422
bbdb7070 2423 return $id;
bbbf2d40 2424}
2425
8420bee9 2426/**
46808d7c 2427 * Function that deletes a role and cleanups up after it
cc3edaa4 2428 *
46808d7c 2429 * @param int $roleid id of role to delete
4f65e0fb 2430 * @return bool always true
8420bee9 2431 */
2432function delete_role($roleid) {
f33e1ed4 2433 global $CFG, $DB;
c421ad4b 2434
4f0c2d00 2435 // first unssign all users
df997f84 2436 role_unassign_all(array('roleid'=>$roleid));
c421ad4b 2437
4f0c2d00
PS
2438 // cleanup all references to this role, ignore errors
2439 $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2440 $DB->delete_records('role_allow_assign', array('roleid'=>$roleid));
2441 $DB->delete_records('role_allow_assign', array('allowassign'=>$roleid));
2442 $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
2443 $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
2444 $DB->delete_records('role_names', array('roleid'=>$roleid));
2445 $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
60ace1e1 2446
4f0c2d00 2447 // finally delete the role itself
cb8cb8bf 2448 // get this before the name is gone for logging
f33e1ed4 2449 $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
5a4e7398 2450
4f0c2d00 2451 $DB->delete_records('role', array('id'=>$roleid));
5a4e7398 2452
4f0c2d00 2453 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
8420bee9 2454
4f0c2d00 2455 return true;
8420bee9 2456}
2457
bbbf2d40 2458/**
2459 * Function to write context specific overrides, or default capabilities.
46808d7c 2460 *
62e65b21
PS
2461 * @param string $capability string name
2462 * @param int $permission CAP_ constants
2463 * @param int $roleid role id
2464 * @param int $contextid context id
2465 * @param bool $overwrite
2466 * @return bool always true or exception
bbbf2d40 2467 */
62e65b21 2468function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
f33e1ed4 2469 global $USER, $DB;
eef868d1 2470
96986241 2471 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
eef868d1 2472 unassign_capability($capability, $roleid, $contextid);
96986241 2473 return true;
98882637 2474 }
eef868d1 2475
f33e1ed4 2476 $existing = $DB->get_record('role_capabilities', array('contextid'=>$contextid, 'roleid'=>$roleid, 'capability'=>$capability));
e7876c1e 2477
2478 if ($existing and !$overwrite) { // We want to keep whatever is there already
2479 return true;
2480 }
2481
365a5941 2482 $cap = new stdClass();
62e65b21
PS
2483 $cap->contextid = $contextid;
2484 $cap->roleid = $roleid;
2485 $cap->capability = $capability;
2486 $cap->permission = $permission;
bbbf2d40 2487 $cap->timemodified = time();
62e65b21 2488 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
e7876c1e 2489
2490 if ($existing) {
2491 $cap->id = $existing->id;
4f0c2d00 2492 $DB->update_record('role_capabilities', $cap);
e7876c1e 2493 } else {
f33e1ed4 2494 $c = $DB->get_record('context', array('id'=>$contextid));
4f0c2d00 2495 $DB->insert_record('role_capabilities', $cap);
e7876c1e 2496 }
4f0c2d00 2497 return true;
bbbf2d40 2498}
2499
bbbf2d40 2500/**
2501 * Unassign a capability from a role.
117bd748 2502 *
46808d7c 2503 * @param string $capability the name of the capability
62e65b21
PS
2504 * @param int $roleid the role id
2505 * @param int $contextid null means all contexts
46808d7c 2506 * @return boolean success or failure
bbbf2d40 2507 */
62e65b21 2508function unassign_capability($capability, $roleid, $contextid = null) {
f33e1ed4 2509 global $DB;
eef868d1 2510
4f0c2d00 2511 if (!empty($contextid)) {
c345bb58 2512 // delete from context rel, if this is the last override in this context
4f0c2d00 2513 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$contextid));
98882637 2514 } else {
4f0c2d00 2515 $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
98882637 2516 }
4f0c2d00 2517 return true;
bbbf2d40 2518}
2519
2520
2521/**
46808d7c 2522 * Get the roles that have a given capability assigned to it
cc3edaa4 2523 *
448aad7f
PS
2524 * This function does not resolve the actual permission of the capability.
2525 * It just checks for permissions and overrides.
2526 * Use get_roles_with_cap_in_context() if resolution is required.
2527 *
46808d7c 2528 * @param string $capability - capability name (string)
4f0c2d00 2529 * @param string $permission - optional, the permission defined for this capability
448aad7f
PS
2530 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
2531 * @param stdClass $context, null means any
2532 * @return array of role objects
bbbf2d40 2533 */
448aad7f
PS
2534function get_roles_with_capability($capability, $permission = null, $context = null) {
2535 global $DB;
5a4e7398 2536
ec7a8b79 2537 if ($context) {
448aad7f
PS
2538 $contexts = get_parent_contexts($context, true);
2539 list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx000');
2540 $contextsql = "AND rc.contextid $insql";
2541 } else {
2542 $params = array();
2543 $contextsql = '';
2544 }
2545
2546 if ($permission) {
2547 $permissionsql = " AND rc.permission = :permission";
2548 $params['permission'] = $permission;
ec7a8b79 2549 } else {
448aad7f 2550 $permissionsql = '';
ec7a8b79 2551 }
eef868d1 2552
448aad7f
PS
2553 $sql = "SELECT r.*
2554 FROM {role} r
2555 WHERE r.id IN (SELECT rc.roleid
2556 FROM {role_capabilities} rc
2557 WHERE rc.capability = :capname
2558 $contextsql
2559 $permissionsql)";
2560 $params['capname'] = $capability;
bbbf2d40 2561
f33e1ed4 2562
448aad7f 2563 return $DB->get_records_sql($sql, $params);
bbbf2d40 2564}
2565
2566
2567/**
df997f84 2568 * This function makes a role-assignment (a role for a user in a particular context)
117bd748 2569 *
46808d7c 2570 * @param int $roleid the role of the id
2571 * @param int $userid userid
46808d7c 2572 * @param int $contextid id of the context
df997f84
PS
2573 * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
2574 * @prama int $itemid id of enrolment/auth plugin
2575 * @param string $timemodified defaults to current time
2576 * @return int new/existing id of the assignment
bbbf2d40 2577 */
df997f84 2578function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
f33e1ed4 2579 global $USER, $CFG, $DB;
bbbf2d40 2580
df997f84
PS
2581 // first of all detect if somebody is using old style parameters
2582 if ($contextid === 0 or is_numeric($component)) {
2583 throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
2584 }
a9e1c058 2585
df997f84 2586 // now validate all parameters
bbbf2d40 2587 if (empty($roleid)) {
df997f84 2588 throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
bbbf2d40 2589 }
2590
e8c2189d 2591 if (empty($userid)) {
df997f84 2592 throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
bbbf2d40 2593 }
eef868d1 2594
df997f84
PS
2595 if ($itemid) {
2596 if (strpos($component, '_') === false) {
2597 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
2598 }
2599 } else {
2600 $itemid = 0;
2601 if ($component !== '' and strpos($component, '_') === false) {
2602 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
2603 }
7700027f 2604 }
bbbf2d40 2605
df997f84
PS
2606 if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
2607 throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
bbbf2d40 2608 }
2609
df997f84 2610 $context = get_context_instance_by_id($contextid, MUST_EXIST);
a9e1c058 2611
69b0088c 2612 if (!$timemodified) {
c421ad4b 2613 $timemodified = time();
69b0088c 2614 }
7700027f 2615
a9e1c058 2616/// Check for existing entry
df997f84
PS
2617 $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
2618
2619 if ($ras) {
2620 // role already assigned - this should not happen
2621 if (count($ras) > 1) {
2622 //very weird - remove all duplicates!
2623 $ra = array_shift($ras);
2624 foreach ($ras as $r) {
2625 $DB->delete_records('role_assignments', array('id'=>$r->id));
2626 }
2627 } else {
2628 $ra = reset($ras);
2629 }
128f0984 2630
df997f84
PS
2631 // actually there is no need to update, reset anything or trigger any event, so just return
2632 return $ra->id;
96608a55 2633 }
c421ad4b 2634
df997f84 2635 // Create a new entry
365a5941 2636 $ra = new stdClass();
df997f84
PS
2637 $ra->roleid = $roleid;
2638 $ra->contextid = $context->id;
2639 $ra->userid = $userid;
2640 $ra->component = $component;
2641 $ra->itemid = $itemid;
2642 $ra->timemodified = $timemodified;
2643 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
eef868d1 2644
df997f84
PS
2645 $ra->id = $DB->insert_record('role_assignments', $ra);
2646
2647 // mark context as dirty - again expensive, but needed
2648 mark_context_dirty($context->path);
2649
2650 if (!empty($USER->id) && $USER->id == $userid) {
2651 // If the user is the current user, then do full reload of capabilities too.
2652 load_all_capabilities();
4e5f3064 2653 }
6eb4f823 2654
96608a55 2655 events_trigger('role_assigned', $ra);
2656
386c151e 2657 return $ra->id;
bbbf2d40 2658}
2659
bbbf2d40 2660/**
df997f84 2661 * Removes one role assignment
cc3edaa4 2662 *
df997f84
PS
2663 * @param int $roleid
2664 * @param int $userid
2665 * @param int $contextid
2666 * @param string $component
2667 * @param int $itemid
2668 * @return void
bbbf2d40 2669 */
df997f84 2670function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
5a4e7398 2671 global $USER, $CFG, $DB;
5a4e7398 2672
df997f84
PS
2673 // first make sure the params make sense
2674 if ($roleid == 0 or $userid == 0 or $contextid == 0) {
2675 throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
6bc1e5d5 2676 }
d74067e8 2677
df997f84
PS
2678 if ($itemid) {
2679 if (strpos($component, '_') === false) {
2680 throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
2681 }
2682 } else {
2683 $itemid = 0;
2684 if ($component !== '' and strpos($component, '_') === false) {
2685 throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
4f0c2d00
PS
2686 }
2687 }
2688
df997f84 2689 role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
4f0c2d00
PS
2690}
2691
2692/**
df997f84
PS
2693 * Removes multiple role assignments, parameters may contain:
2694 * 'roleid', 'userid', 'contextid', 'component', 'enrolid'.
4f0c2d00 2695 *
df997f84
PS
2696 * @param array $params role assignment parameters
2697 * @param bool $subcontexts unassign in subcontexts too
2698 * @param bool $includmanual include manual role assignments too
2699 * @return void
4f0c2d00 2700 */
62e65b21 2701function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
df997f84 2702 global $USER, $CFG, $DB;
4f0c2d00 2703
df997f84
PS
2704 if (!$params) {
2705 throw new coding_exception('Missing parameters in role_unsassign_all() call');
4f0c2d00
PS
2706 }
2707
df997f84
PS
2708 $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
2709 foreach ($params as $key=>$value) {
2710 if (!in_array($key, $allowed)) {
2711 throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
2712 }
2713 }
4f0c2d00 2714
df997f84
PS
2715 if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
2716 throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
2717 }
4f0c2d00 2718
df997f84
PS
2719 if ($includemanual) {
2720 if (!isset($params['component']) or $params['component'] === '') {
2721 throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
4f0c2d00 2722 }
df997f84 2723 }
4f0c2d00 2724
df997f84
PS
2725 if ($subcontexts) {
2726 if (empty($params['contextid'])) {
2727 throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
2728 }
2729 }
4f0c2d00 2730
df997f84
PS
2731 $ras = $DB->get_records('role_assignments', $params);
2732 foreach($ras as $ra) {
2733 $DB->delete_records('role_assignments', array('id'=>$ra->id));
2734 if ($context = get_context_instance_by_id($ra->contextid)) {
2735 // this is a bit expensive but necessary
2736 mark_context_dirty($context->path);
2737 /// If the user is the current user, then do full reload of capabilities too.
2738 if (!empty($USER->id) && $USER->id == $ra->userid) {
2739 load_all_capabilities();
2740 }
2741 }
2742 events_trigger('role_unassigned', $ra);
2743 }
2744 unset($ras);
4f0c2d00 2745
df997f84
PS
2746 // process subcontexts
2747 if ($subcontexts and $context = get_context_instance_by_id($params['contextid'])) {
2748 $contexts = get_child_contexts($context);
2749 $mparams = $params;
2750 foreach($contexts as $context) {
2751 $mparams['contextid'] = $context->id;
2752 $ras = $DB->get_records('role_assignments', $mparams);
2753 foreach($ras as $ra) {
2754 $DB->delete_records('role_assignments', array('id'=>$ra->id));
2755 // this is a bit expensive but necessary
2756 mark_context_dirty($context->path);
2757 /// If the user is the current user, then do full reload of capabilities too.
2758 if (!empty($USER->id) && $USER->id == $ra->userid) {
2759 load_all_capabilities();
2760 }
2761 events_trigger('role_unassigned', $ra);
2762 }
2763 }
4f0c2d00
PS
2764 }
2765
df997f84
PS
2766 // do this once more for all manual role assignments
2767 if ($includemanual) {
2768 $params['component'] = '';
2769 role_unassign_all($params, $subcontexts, false);
2770 }
4f0c2d00
PS
2771}
2772
df997f84 2773
4f0c2d00
PS
2774/**
2775 * Determines if a user is currently logged in
2776 *
2777 * @return bool
2778 */
2779function isloggedin() {
2780 global $USER;
2781
2782 return (!empty($USER->id));
2783}
2784
2785/**
2786 * Determines if a user is logged in as real guest user with username 'guest'.
2787 *
df997f84 2788 * @param int|object $user mixed user object or id, $USER if not specified
4f0c2d00
PS
2789 * @return bool true if user is the real guest user, false if not logged in or other user
2790 */
62e65b21 2791function isguestuser($user = null) {
4f0c2d00
PS
2792 global $USER, $DB, $CFG;
2793
2794 // make sure we have the user id cached in config table, because we are going to use it a lot
2795 if (empty($CFG->siteguest)) {
2796 if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
2797 // guest does not exist yet, weird
2798 return false;
2799 }
2800 set_config('siteguest', $guestid);
2801 }
62e65b21 2802 if ($user === null) {
4f0c2d00
PS
2803 $user = $USER;
2804 }
2805
62e65b21 2806 if ($user === null) {
4f0c2d00
PS
2807 // happens when setting the $USER
2808 return false;
2809
2810 } else if (is_numeric($user)) {
2811 return ($CFG->siteguest == $user);
2812
2813 } else if (is_object($user)) {
2814 if (empty($user->id)) {
2815 return false; // not logged in means is not be guest
2816 } else {
2817 return ($CFG->siteguest == $user->id);
2818 }
2819
2820 } else {
2821 throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
2822 }
2823}
2824
2825/**
2826 * Does user have a (temporary or real) guest access to course?
2827 *
62e65b21
PS
2828 * @param stdClass $context
2829 * @param stdClass|int $user
4f0c2d00
PS
2830 * @return bool
2831 */
62e65b21 2832function is_guest($context, $user = null) {
5fd9e798
PS
2833 global $USER;
2834
4f0c2d00
PS
2835 // first find the course context
2836 $coursecontext = get_course_context($context);
2837
2838 // make sure there is a real user specified
62e65b21 2839 if ($user === null) {
4f0c2d00
PS
2840 $userid = !empty($USER->id) ? $USER->id : 0;
2841 } else {
2842 $userid = !empty($user->id) ? $user->id : $user;
2843 }
2844
2845 if (isguestuser($userid)) {
2846 // can not inspect or be enrolled
2847 return true;
2848 }
2849
2850 if (has_capability('moodle/course:view', $coursecontext, $user)) {
2851 // viewing users appear out of nowhere, they are neither guests nor participants
2852 return false;
2853 }
2854
df997f84
PS
2855 // consider only real active enrolments here
2856 if (is_enrolled($coursecontext, $user, '', true)) {
4f0c2d00
PS
2857 return false;
2858 }
2859
2860 return true;
2861}
2862
2863
2864/**
2418d71e 2865 * Returns true if the user has moodle/course:view capability in the course,
4f0c2d00
PS
2866 * this is intended for admins, managers (aka small admins), inspectors, etc.
2867 *
62e65b21
PS
2868 * @param stdClass $context
2869 * @param int|object $user, if null $USER is used
4f0c2d00
PS
2870 * @param string $withcapability extra capability name
2871 * @return bool
2872 */
62e65b21 2873function is_viewing($context, $user = null, $withcapability = '') {
4f0c2d00
PS
2874 // first find the course context
2875 $coursecontext = get_course_context($context);
2876
2877 if (isguestuser($user)) {
2878 // can not inspect
83bbafaa 2879 return false;
4f0c2d00
PS
2880 }
2881
2882 if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2883 // admins are allowed to inspect courses
2884 return false;
2885 }
2886
2887 if ($withcapability and !has_capability($withcapability, $context, $user)) {
2888 // site admins always have the capability, but the enrolment above blocks
2889 return false;
2890 }
2891
2892 return true;
2893}
2894
2895/**
2896 * Returns true if user is enrolled (is participating) in course
2897 * this is intended for students and teachers.
2898 *
2899 * @param object $context
62e65b21 2900 * @param int|object $user, if null $USER is used, otherwise user object or id expected
4f0c2d00 2901 * @param string $withcapability extra capability name
df997f84 2902 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
4f0c2d00
PS
2903 * @return bool
2904 */
62e65b21 2905function is_enrolled($context, $user = null, $withcapability = '', $onlyactive = false) {
df997f84 2906 global $USER, $DB;
4f0c2d00
PS
2907
2908 // first find the course context
2909 $coursecontext = get_course_context($context);
2910
2911 // make sure there is a real user specified
62e65b21 2912 if ($user === null) {
4f0c2d00
PS
2913 $userid = !empty($USER->id) ? $USER->id : 0;
2914 } else {
2915 $userid = !empty($user->id) ? $user->id : $user;
2916 }
2917
2918 if (empty($userid)) {
2919 // not-logged-in!
2920 return false;
2921 } else if (isguestuser($userid)) {
2922 // guest account can not be enrolled anywhere
2923 return false;
2924 }
2925
df997f84
PS
2926 if ($coursecontext->instanceid == SITEID) {
2927 // everybody participates on frontpage
2928 } else {
2929 if ($onlyactive) {
2930 $sql = "SELECT ue.*
2931 FROM {user_enrolments} ue
2932 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2933 JOIN {user} u ON u.id = ue.userid
2934 WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
2935 $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2936 // this result should be very small, better not do the complex time checks in sql for now ;-)
2937 $enrolments = $DB->get_records_sql($sql, $params);
2938 $now = time();
2939 // make sure the enrol period is ok
2940 $result = false;
2941 foreach ($enrolments as $e) {
2942 if ($e->timestart > $now) {
2943 continue;
2944 }
2945 if ($e->timeend and $e->timeend < $now) {
2946 continue;
2947 }
2948 $result = true;
2949 break;
2950 }
2951 if (!$result) {
2952 return false;
2953 }
2954
2955 } else {
2956 // any enrolment is good for us here, even outdated, disabled or inactive
2957 $sql = "SELECT 'x'
2958 FROM {user_enrolments} ue
2959 JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2960 JOIN {user} u ON u.id = ue.userid
2961 WHERE ue.userid = :userid AND u.deleted = 0";
2962 $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2963 if (!$DB->record_exists_sql($sql, $params)) {
2964 return false;
2965 }
2966 }
4f0c2d00
PS
2967 }
2968
2969 if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2970 return false;
2971 }
2972
2973 return true;
2974}
2975
ed1d72ea
SH
2976/**
2977 * Returns true if the user is able to access the course.
2978 *
2979 * This function is in no way, shape, or form a substitute for require_login.
2980 * It should only be used in circumstances where it is not possible to call require_login
2981 * such as the navigation.
2982 *
2983 * This function checks many of the methods of access to a course such as the view
2984 * capability, enrollments, and guest access. It also makes use of the cache
2985 * generated by require_login for guest access.
2986 *
2987 * The flags within the $USER object that are used here should NEVER be used outside
2988 * of this function can_access_course and require_login. Doing so WILL break future
2989 * versions.
2990 *
2991 * @global moodle_database $DB
2992 * @param stdClass $context
2993 * @param stdClass|null $user
2994 * @param string $withcapability Check for this capability as well.
2995 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2996 * @param boolean $trustcache If set to false guest access will always be checked
2997 * against the enrolment plugins from the course, rather
2998 * than the cache generated by require_login.
2999 * @return boolean Returns true if the user is able to access the course
3000 */
3001function can_access_course($context, $user = null, $withcapability = '', $onlyactive = false, $trustcache = true) {
3002 global $DB, $USER;
3003
3004 $coursecontext = get_course_context($context);
3005 $courseid = $coursecontext->instanceid;
3006
3007 // First check the obvious, is the user viewing or is the user enrolled.
3008 if (is_viewing($coursecontext, $user, $withcapability) || is_enrolled($coursecontext, $user, $withcapability, $onlyactive)) {
3009 // How easy was that!
3010 return true;
3011 }
3012
3013 $access = false;
3014 if (!isset($USER->enrol)) {
3015 // Cache hasn't been generated yet so we can't trust it
3016 $trustcache = false;
3017 /**
3018 * These flags within the $USER object should NEVER be used outside of this
3019 * function can_access_course and the function require_login.
3020 * Doing so WILL break future versions!!!!
3021 */
3022 $USER->enrol = array();
3023 $USER->enrol['enrolled'] = array();
3024 $USER->enrol['tempguest'] = array();
3025 }
3026
3027 // If we don't trust the cache we need to check with the courses enrolment
3028 // plugin instances to see if the user can access the course as a guest.
3029 if (!$trustcache) {
3030 // Ok, off to the database we go!
3031 $instances = $DB->get_records('enrol', array('courseid'=>$courseid, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
3032 $enrols = enrol_get_plugins(true);
3033 foreach($instances as $instance) {
3034 if (!isset($enrols[$instance->enrol])) {
3035 continue;
3036 }
3037 $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3038 if ($until !== false) {
3039 // Never use me anywhere but here and require_login
3040 $USER->enrol['tempguest'][$courseid] = $until;
3041 $access = true;
3042 break;
3043 }
3044 }
3045 }
3046
3047 // If we don't already have access (from above) check the cache and see whether
3048 // there is record of it in there.
3049 if (!$access && isset($USER->enrol['tempguest'][$courseid])) {
3050 // Never use me anywhere but here and require_login
3051 if ($USER->enrol['tempguest'][$courseid] == 0) {
3052 $access = true;
3053 } else if ($USER->enrol['tempguest'][$courseid] > time()) {
3054 $access = true;
3055 } else {
3056 //expired
3057 unset($USER->enrol['tempguest'][$courseid]);
3058 }
3059 }
3060 return $access;
3061}
3062
4f0c2d00
PS
3063/**
3064 * Returns array with sql code and parameters returning all ids
3065 * of users enrolled into course.
df997f84
PS
3066 *
3067 * This function is using 'eu[0-9]+_' prefix for table names and parameters.
3068 *
4f0c2d00
PS
3069 * @param object $context
3070 * @param string $withcapability
3071 * @param int $groupid 0 means ignore groups, any other value limits the result by group id
df997f84 3072 * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
4f0c2d00
PS
3073 * @return array list($sql, $params)
3074 */
df997f84 3075function get_enrolled_sql($context, $withcapability = '', $groupid = 0, $onlyactive = false) {
b3df1764 3076 global $DB, $CFG;
4f0c2d00 3077
df997f84
PS
3078 // use unique prefix just in case somebody makes some SQL magic with the result
3079 static $i = 0;
3080 $i++;
3081 $prefix = 'eu'.$i.'_';
4f0c2d00
PS
3082
3083 // first find the course context
df997f84 3084 $coursecontext = get_course_context($context);
4f0c2d00 3085
df997f84 3086 $isfrontpage = ($coursecontext->instanceid == SITEID);
4f0c2d00 3087
df997f84
PS
3088 $joins = array();
3089 $wheres = array();
3090 $params = array();
4f0c2d00
PS
3091
3092 list($contextids, $contextpaths) = get_context_info_list($context);
4f0c2d00
PS
3093
3094 // get all relevant capability info for all roles
3095 if ($withcapability) {
df997f84
PS
3096 list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx00');
3097 $cparams['cap'] = $withcapability;
3098
3099 $defs = array();
3100 $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
3101 FROM {role_capabilities} rc
3102 JOIN {context} ctx on rc.contextid = ctx.id
3103 WHERE rc.contextid $incontexts AND rc.capability = :cap";
3104 $rcs = $DB->get_records_sql($sql, $cparams);
3105 foreach ($rcs as $rc) {
3106 $defs[$rc->path][$rc->roleid] = $rc->permission;
4f0c2d00 3107 }
4f0c2d00 3108
df997f84
PS
3109 $access = array();
3110 if (!empty($defs)) {
3111 foreach ($contextpaths as $path) {
3112 if (empty($defs[$path])) {
4f0c2d00
PS
3113 continue;
3114 }
df997f84
PS
3115 foreach($defs[$path] as $roleid => $perm) {
3116 if ($perm == CAP_PROHIBIT) {
3117 $access[$roleid] = CAP_PROHIBIT;
3118 continue;
3119 }
3120 if (!isset($access[$roleid])) {
3121 $access[$roleid] = (int)$perm;
3122 }
4f0c2d00
PS
3123 }
3124 }
3125 }
4f0c2d00 3126
df997f84 3127 unset($defs);
4f0c2d00 3128
df997f84
PS
3129 // make lists of roles that are needed and prohibited
3130 $needed = array(); // one of these is enough
3131 $prohibited = array(); // must not have any of these
fafa57e9
PS
3132 foreach ($access as $roleid => $perm) {
3133 if ($perm == CAP_PROHIBIT) {
3134 unset($needed[$roleid]);
3135 $prohibited[$roleid] = true;
3136 } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
3137 $needed[$roleid] = true;
4f0c2d00
PS
3138 }
3139 }
4f0c2d00 3140
62e65b21
PS
3141 $defaultuserroleid = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : null;
3142 $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : null;
2515adf9 3143
df997f84 3144 $nobody = false;
2515adf9 3145
4f0c2d00
PS
3146 if ($isfrontpage) {
3147 if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
3148 $nobody = true;
fafa57e9 3149 } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
4f0c2d00
PS
3150 // everybody not having prohibit has the capability
3151 $needed = array();
3152 } else if (empty($needed)) {
3153 $nobody = true;
3154 }
3155 } else {
3156 if (!empty($prohibited[$defaultuserroleid])) {
3157 $nobody = true;
fafa57e9 3158 } else if (!empty($needed[$defaultuserroleid])) {
4f0c2d00
PS
3159 // everybody not having prohibit has the capability