MDL-10995 removing previous patch; testing a better one just now
[moodle.git] / lib / accesslib.php
CommitLineData
6cdd0f9c 1<?php // $Id$
2
3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
8// http://moodle.org //
9// //
10// Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
11// //
12// This program is free software; you can redistribute it and/or modify //
13// it under the terms of the GNU General Public License as published by //
14// the Free Software Foundation; either version 2 of the License, or //
15// (at your option) any later version. //
16// //
17// This program is distributed in the hope that it will be useful, //
18// but WITHOUT ANY WARRANTY; without even the implied warranty of //
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20// GNU General Public License for more details: //
21// //
22// http://www.gnu.org/copyleft/gpl.html //
23// //
24///////////////////////////////////////////////////////////////////////////
25
cee0901c 26 /**
27 * Capability session information format
bbbf2d40 28 * 2 x 2 array
29 * [context][capability]
30 * where context is the context id of the table 'context'
31 * and capability is a string defining the capability
32 * e.g.
33 *
34 * [Capabilities] => [26][mod/forum:viewpost] = 1
35 * [26][mod/forum:startdiscussion] = -8990
36 * [26][mod/forum:editallpost] = -1
37 * [273][moodle:blahblah] = 1
38 * [273][moodle:blahblahblah] = 2
39 */
bbbf2d40 40
cdfa3035 41require_once $CFG->dirroot.'/lib/blocklib.php';
42
bbbf2d40 43// permission definitions
e49e61bf 44define('CAP_INHERIT', 0);
bbbf2d40 45define('CAP_ALLOW', 1);
46define('CAP_PREVENT', -1);
47define('CAP_PROHIBIT', -1000);
48
bbbf2d40 49// context definitions
50define('CONTEXT_SYSTEM', 10);
51define('CONTEXT_PERSONAL', 20);
4b10f08b 52define('CONTEXT_USER', 30);
bbbf2d40 53define('CONTEXT_COURSECAT', 40);
54define('CONTEXT_COURSE', 50);
55define('CONTEXT_GROUP', 60);
56define('CONTEXT_MODULE', 70);
57define('CONTEXT_BLOCK', 80);
58
21b6db6e 59// capability risks - see http://docs.moodle.org/en/Hardening_new_Roles_system
60define('RISK_MANAGETRUST', 0x0001);
a6b02b65 61define('RISK_CONFIG', 0x0002);
21b6db6e 62define('RISK_XSS', 0x0004);
63define('RISK_PERSONAL', 0x0008);
64define('RISK_SPAM', 0x0010);
65
f3f7610c 66require_once($CFG->dirroot.'/group/lib.php');
21b6db6e 67
340ea4e8 68$context_cache = array(); // Cache of all used context objects for performance (by level and instance)
69$context_cache_id = array(); // Index to above cache by id
bbbf2d40 70
7700027f 71
eef879ec 72function get_role_context_caps($roleid, $context) {
73 //this is really slow!!!! - do not use above course context level!
74 $result = array();
75 $result[$context->id] = array();
e7876c1e 76
eef879ec 77 // first emulate the parent context capabilities merging into context
78 $searchcontexts = array_reverse(get_parent_contexts($context));
79 array_push($searchcontexts, $context->id);
80 foreach ($searchcontexts as $cid) {
81 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
82 foreach ($capabilities as $cap) {
83 if (!array_key_exists($cap->capability, $result[$context->id])) {
84 $result[$context->id][$cap->capability] = 0;
85 }
86 $result[$context->id][$cap->capability] += $cap->permission;
87 }
88 }
89 }
e7876c1e 90
eef879ec 91 // now go through the contexts bellow given context
92 $searchcontexts = get_child_contexts($context);
93 foreach ($searchcontexts as $cid) {
94 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
95 foreach ($capabilities as $cap) {
96 if (!array_key_exists($cap->contextid, $result)) {
97 $result[$cap->contextid] = array();
98 }
99 $result[$cap->contextid][$cap->capability] = $cap->permission;
100 }
101 }
e7876c1e 102 }
103
eef879ec 104 return $result;
105}
106
107function get_role_caps($roleid) {
108 $result = array();
109 if ($capabilities = get_records_select('role_capabilities',"roleid = $roleid")) {
110 foreach ($capabilities as $cap) {
111 if (!array_key_exists($cap->contextid, $result)) {
112 $result[$cap->contextid] = array();
113 }
114 $result[$cap->contextid][$cap->capability] = $cap->permission;
115 }
e7876c1e 116 }
eef879ec 117 return $result;
118}
e7876c1e 119
eef879ec 120function merge_role_caps($caps, $mergecaps) {
121 if (empty($mergecaps)) {
122 return $caps;
e7876c1e 123 }
124
eef879ec 125 if (empty($caps)) {
126 return $mergecaps;
e7876c1e 127 }
128
eef879ec 129 foreach ($mergecaps as $contextid=>$capabilities) {
130 if (!array_key_exists($contextid, $caps)) {
131 $caps[$contextid] = array();
132 }
133 foreach ($capabilities as $capability=>$permission) {
134 if (!array_key_exists($capability, $caps[$contextid])) {
135 $caps[$contextid][$capability] = 0;
2b91b669 136 }
eef879ec 137 $caps[$contextid][$capability] += $permission;
2b91b669 138 }
139 }
eef879ec 140 return $caps;
141}
cdfa3035 142
eef879ec 143/**
144 * Loads the capabilities for the default guest role to the current user in a
145 * specific context.
146 * @return object
147 */
148function load_guest_role($return=false) {
149 global $USER;
cdfa3035 150
eef879ec 151 static $guestrole = false;
152
153 if ($guestrole === false) {
154 if (!$guestrole = get_guest_role()) {
155 return false;
e7876c1e 156 }
157 }
158
eef879ec 159 if ($return) {
160 return get_role_caps($guestrole->id);
161 } else {
8d2b18a8 162 has_capability('clearcache');
eef879ec 163 $USER->capabilities = get_role_caps($guestrole->id);
8d2b18a8 164 return true;
8d2b18a8 165 }
e7876c1e 166}
167
7700027f 168/**
169 * Load default not logged in role capabilities when user is not logged in
eef868d1 170 * @return bool
7700027f 171 */
eef879ec 172function load_notloggedin_role($return=false) {
20aeb4b8 173 global $CFG, $USER;
174
21c9bace 175 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
7700027f 176 return false;
35a518c5 177 }
178
7700027f 179 if (empty($CFG->notloggedinroleid)) { // Let's set the default to the guest role
8f8ed475 180 if ($role = get_guest_role()) {
7700027f 181 set_config('notloggedinroleid', $role->id);
182 } else {
183 return false;
184 }
185 }
20aeb4b8 186
eef879ec 187 if ($return) {
188 return get_role_caps($CFG->notloggedinroleid);
189 } else {
99ad7633 190 has_capability('clearcache');
eef879ec 191 $USER->capabilities = get_role_caps($CFG->notloggedinroleid);
192 return true;
20aeb4b8 193 }
20aeb4b8 194}
cee0901c 195
8f8ed475 196/**
eef879ec 197 * Load default logged in role capabilities for all logged in users
eef868d1 198 * @return bool
8f8ed475 199 */
8d2b18a8 200function load_defaultuser_role($return=false) {
8f8ed475 201 global $CFG, $USER;
202
21c9bace 203 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
8f8ed475 204 return false;
205 }
206
207 if (empty($CFG->defaultuserroleid)) { // Let's set the default to the guest role
208 if ($role = get_guest_role()) {
209 set_config('defaultuserroleid', $role->id);
210 } else {
211 return false;
212 }
213 }
214
eef879ec 215 $capabilities = get_role_caps($CFG->defaultuserroleid);
8d2b18a8 216
eef879ec 217 // fix the guest user heritage:
218 // If the default role is a guest role, then don't copy legacy:guest,
219 // otherwise this user could get confused with a REAL guest. Also don't copy
220 // course:view, which is a hack that's necessary because guest roles are
221 // not really handled properly (see MDL-7513)
222 if (!empty($capabilities[$sitecontext->id]['moodle/legacy:guest'])) {
223 unset($capabilities[$sitecontext->id]['moodle/legacy:guest']);
224 unset($capabilities[$sitecontext->id]['moodle/course:view']);
8f8ed475 225 }
226
8d2b18a8 227 if ($return) {
eef879ec 228 return $capabilities;
8d2b18a8 229 } else {
230 has_capability('clearcache');
eef879ec 231 $USER->capabilities = $capabilities;
8d2b18a8 232 return true;
233 }
8f8ed475 234}
235
236
237/**
238 * Get the default guest role
239 * @return object role
240 */
241function get_guest_role() {
ebce32b5 242 global $CFG;
243
244 if (empty($CFG->guestroleid)) {
245 if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
246 $guestrole = array_shift($roles); // Pick the first one
247 set_config('guestroleid', $guestrole->id);
248 return $guestrole;
249 } else {
250 debugging('Can not find any guest role!');
251 return false;
252 }
8f8ed475 253 } else {
ebce32b5 254 if ($guestrole = get_record('role','id', $CFG->guestroleid)) {
255 return $guestrole;
256 } else {
257 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
258 set_config('guestroleid', '');
259 return get_guest_role();
260 }
8f8ed475 261 }
262}
263
264
bbbf2d40 265/**
266 * This functions get all the course categories in proper order
40a2a15f 267 * (!)note this only gets course category contexts, and not the site
268 * context
d963740d 269 * @param object $context
bbbf2d40 270 * @param int $type
271 * @return array of contextids
272 */
0468976c 273function get_parent_cats($context, $type) {
eef868d1 274
98882637 275 $parents = array();
eef868d1 276
c5ddc3fd 277 switch ($type) {
40a2a15f 278 // a category can be the parent of another category
279 // there is no limit of depth in this case
98882637 280 case CONTEXT_COURSECAT:
c5ddc3fd 281 if (!$cat = get_record('course_categories','id',$context->instanceid)) {
282 break;
283 }
284
285 while (!empty($cat->parent)) {
286 if (!$context = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
287 break;
288 }
98882637 289 $parents[] = $context->id;
290 $cat = get_record('course_categories','id',$cat->parent);
291 }
98882637 292 break;
40a2a15f 293
294 // a course always fall into a category, unless it's a site course
8ba412da 295 // this happens when SITEID == $course->id
40a2a15f 296 // in this case the parent of the course is site context
98882637 297 case CONTEXT_COURSE:
c5ddc3fd 298 if (!$course = get_record('course', 'id', $context->instanceid)) {
299 break;
300 }
301 if (!$catinstance = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
302 break;
303 }
304
98882637 305 $parents[] = $catinstance->id;
c5ddc3fd 306
307 if (!$cat = get_record('course_categories','id',$course->category)) {
308 break;
309 }
40a2a15f 310 // Yu: Separating site and site course context
311 if ($course->id == SITEID) {
312 break;
313 }
c5ddc3fd 314
315 while (!empty($cat->parent)) {
316 if (!$context = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
317 break;
318 }
98882637 319 $parents[] = $context->id;
320 $cat = get_record('course_categories','id',$cat->parent);
321 }
322 break;
eef868d1 323
98882637 324 default:
325 break;
98882637 326 }
98882637 327 return array_reverse($parents);
bbbf2d40 328}
329
330
cee0901c 331
0468976c 332/**
333 * This function checks for a capability assertion being true. If it isn't
334 * then the page is terminated neatly with a standard error message
335 * @param string $capability - name of the capability
336 * @param object $context - a context object (record from context table)
337 * @param integer $userid - a userid number
d74067e8 338 * @param bool $doanything - if false, ignore do anything
0468976c 339 * @param string $errorstring - an errorstring
d74067e8 340 * @param string $stringfile - which stringfile to get it from
0468976c 341 */
eef868d1 342function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
71483894 343 $errormessage='nopermissions', $stringfile='') {
a9e1c058 344
71483894 345 global $USER, $CFG;
a9e1c058 346
71483894 347/// If the current user is not logged in, then make sure they are (if needed)
a9e1c058 348
6605128e 349 if (empty($userid) and empty($USER->capabilities)) {
aad2ba95 350 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
a9e1c058 351 require_login($context->instanceid);
11ac79ff 352 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
353 if ($cm = get_record('course_modules','id',$context->instanceid)) {
71483894 354 if (!$course = get_record('course', 'id', $cm->course)) {
355 error('Incorrect course.');
356 }
357 require_course_login($course, true, $cm);
358
11ac79ff 359 } else {
360 require_login();
361 }
71483894 362 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
363 if (!empty($CFG->forcelogin)) {
364 require_login();
365 }
366
a9e1c058 367 } else {
368 require_login();
369 }
370 }
eef868d1 371
a9e1c058 372/// OK, if they still don't have the capability then print a nice error message
373
d74067e8 374 if (!has_capability($capability, $context, $userid, $doanything)) {
0468976c 375 $capabilityname = get_capability_string($capability);
376 print_error($errormessage, $stringfile, '', $capabilityname);
377 }
378}
379
e6260a45 380/**
381 * Cheks if current user has allowed permission for any of submitted capabilities
382 * in given or child contexts.
383 * @param object $context - a context object (record from context table)
384 * @param array $capabilitynames array of strings, capability names
385 * @return boolean
386 */
387function has_capability_including_child_contexts($context, $capabilitynames) {
388 global $USER;
389
390 foreach ($capabilitynames as $capname) {
391 if (has_capability($capname, $context)) {
392 return true;
393 }
394 }
395
396 if ($children = get_child_contexts($context)) {
397 foreach ($capabilitynames as $capname) {
398 foreach ($children as $child) {
399 if (isset($USER->capabilities[$child][$capname]) and $USER->capabilities[$child][$capname] == CAP_ALLOW) {
400 // extra check for inherited prevent and prohibit
401 if (has_capability($capname, get_context_instance_by_id($child), $USER->id, false)) {
402 return true;
403 }
404 }
405 }
406 }
407 }
408
409 return false;
410}
0468976c 411
bbbf2d40 412/**
413 * This function returns whether the current user has the capability of performing a function
7d8ea286 414 * For example, we can do has_capability('mod/forum:replypost',$context) in forum
415 * This is a recursive function.
bbbf2d40 416 * @uses $USER
caac8977 417 * @param string $capability - name of the capability (or debugcache or clearcache)
0468976c 418 * @param object $context - a context object (record from context table)
419 * @param integer $userid - a userid number
20aeb4b8 420 * @param bool $doanything - if false, ignore do anything
bbbf2d40 421 * @return bool
422 */
d74067e8 423function has_capability($capability, $context=NULL, $userid=NULL, $doanything=true) {
bbbf2d40 424
20aeb4b8 425 global $USER, $CONTEXT, $CFG;
bbbf2d40 426
922633bd 427 static $capcache = array(); // Cache of capabilities
428
caac8977 429
430/// Cache management
431
432 if ($capability == 'clearcache') {
433 $capcache = array(); // Clear ALL the capability cache
434 return false;
435 }
436
922633bd 437/// Some sanity checks
6d2d91d6 438 if (debugging('',DEBUG_DEVELOPER)) {
922633bd 439 if ($capability == 'debugcache') {
440 print_object($capcache);
441 return true;
442 }
443 if (!record_exists('capabilities', 'name', $capability)) {
444 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
445 }
446 if ($doanything != true and $doanything != false) {
447 debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
448 }
449 if (!is_object($context) && $context !== NULL) {
450 debugging('Incorrect context parameter "'.$context.'" for has_capability(), object expected! This should be fixed in code.');
451 }
a8a7300a 452 }
453
922633bd 454/// Make sure we know the current context
455 if (empty($context)) { // Use default CONTEXT if none specified
456 if (empty($CONTEXT)) {
457 return false;
458 } else {
459 $context = $CONTEXT;
460 }
461 } else { // A context was given to us
462 if (empty($CONTEXT)) {
463 $CONTEXT = $context; // Store FIRST used context in this global as future default
464 }
465 }
466
467/// Check and return cache in case we've processed this one before.
8d2b18a8 468 $requsteduser = empty($userid) ? $USER->id : $userid; // find out the requested user id, $USER->id might have been changed
469 $cachekey = $capability.'_'.$context->id.'_'.intval($requsteduser).'_'.intval($doanything);
caac8977 470
922633bd 471 if (isset($capcache[$cachekey])) {
472 return $capcache[$cachekey];
473 }
474
20aeb4b8 475
922633bd 476/// Load up the capabilities list or item as necessary
8d2b18a8 477 if ($userid) {
478 if (empty($USER->id) or ($userid != $USER->id) or empty($USER->capabilities)) {
8d2b18a8 479
eef879ec 480 //caching - helps user switching in cron
481 static $guestuserid = false; // guest user id
482 static $guestcaps = false; // guest caps
483 static $defcaps = false; // default user caps - this might help cron
484
485 if ($guestuserid === false) {
8d2b18a8 486 $guestuserid = get_field('user', 'id', 'username', 'guest');
487 }
488
489 if ($userid == $guestuserid) {
eef879ec 490 if ($guestcaps === false) {
491 $guestcaps = load_guest_role(true);
492 }
493 $capabilities = $guestcaps;
8d2b18a8 494
495 } else {
6eaa3f09 496 // This big SQL is expensive! We reduce it a little by avoiding checking for changed enrolments (false)
497 $capabilities = load_user_capability($capability, $context, $userid, false);
eef879ec 498 if ($defcaps === false) {
8d2b18a8 499 $defcaps = load_defaultuser_role(true);
500 }
eef879ec 501 $capabilities = merge_role_caps($capabilities, $defcaps);
8d2b18a8 502 }
eef879ec 503
504 } else { //$USER->id == $userid and needed capabilities already present
8d2b18a8 505 $capabilities = $USER->capabilities;
9425b25f 506 }
eef879ec 507
9425b25f 508 } else { // no userid
8d2b18a8 509 if (empty($USER->capabilities)) {
eef879ec 510 load_all_capabilities(); // expensive - but we have to do it once anyway
8d2b18a8 511 }
512 $capabilities = $USER->capabilities;
922633bd 513 $userid = $USER->id;
98882637 514 }
9425b25f 515
caac8977 516/// We act a little differently when switchroles is active
517
518 $switchroleactive = false; // Assume it isn't active in this context
519
bbbf2d40 520
922633bd 521/// First deal with the "doanything" capability
5fe9a11d 522
20aeb4b8 523 if ($doanything) {
2d07587b 524
f4e2d38a 525 /// First make sure that we aren't in a "switched role"
526
f4e2d38a 527 if (!empty($USER->switchrole)) { // Switchrole is active somewhere!
528 if (!empty($USER->switchrole[$context->id])) { // Because of current context
529 $switchroleactive = true;
530 } else { // Check parent contexts
531 if ($parentcontextids = get_parent_contexts($context)) {
532 foreach ($parentcontextids as $parentcontextid) {
533 if (!empty($USER->switchrole[$parentcontextid])) { // Yep, switchroles active here
534 $switchroleactive = true;
535 break;
536 }
537 }
538 }
539 }
540 }
541
542 /// Check the site context for doanything (most common) first
543
544 if (empty($switchroleactive)) { // Ignore site setting if switchrole is active
21c9bace 545 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2d07587b 546 if (isset($capabilities[$sitecontext->id]['moodle/site:doanything'])) {
922633bd 547 $result = (0 < $capabilities[$sitecontext->id]['moodle/site:doanything']);
548 $capcache[$cachekey] = $result;
549 return $result;
2d07587b 550 }
20aeb4b8 551 }
40a2a15f 552 /// If it's not set at site level, it is possible to be set on other levels
553 /// Though this usage is not common and can cause risks
aad2ba95 554 switch ($context->contextlevel) {
eef868d1 555
20aeb4b8 556 case CONTEXT_COURSECAT:
557 // Check parent cats.
558 $parentcats = get_parent_cats($context, CONTEXT_COURSECAT);
559 foreach ($parentcats as $parentcat) {
560 if (isset($capabilities[$parentcat]['moodle/site:doanything'])) {
922633bd 561 $result = (0 < $capabilities[$parentcat]['moodle/site:doanything']);
562 $capcache[$cachekey] = $result;
563 return $result;
20aeb4b8 564 }
cee0901c 565 }
20aeb4b8 566 break;
bbbf2d40 567
20aeb4b8 568 case CONTEXT_COURSE:
569 // Check parent cat.
570 $parentcats = get_parent_cats($context, CONTEXT_COURSE);
98882637 571
20aeb4b8 572 foreach ($parentcats as $parentcat) {
573 if (isset($capabilities[$parentcat]['do_anything'])) {
922633bd 574 $result = (0 < $capabilities[$parentcat]['do_anything']);
575 $capcache[$cachekey] = $result;
576 return $result;
20aeb4b8 577 }
9425b25f 578 }
20aeb4b8 579 break;
bbbf2d40 580
20aeb4b8 581 case CONTEXT_GROUP:
582 // Find course.
5bf243d1 583 $courseid = get_field('groups', 'courseid', 'id', $context->instanceid);
f3f7610c 584 $courseinstance = get_context_instance(CONTEXT_COURSE, $courseid);
9425b25f 585
20aeb4b8 586 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE);
587 foreach ($parentcats as $parentcat) {
b4a1805a 588 if (isset($capabilities[$parentcat]['do_anything'])) {
589 $result = (0 < $capabilities[$parentcat]['do_anything']);
922633bd 590 $capcache[$cachekey] = $result;
591 return $result;
20aeb4b8 592 }
9425b25f 593 }
9425b25f 594
20aeb4b8 595 $coursecontext = '';
596 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
922633bd 597 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
598 $capcache[$cachekey] = $result;
599 return $result;
20aeb4b8 600 }
9425b25f 601
20aeb4b8 602 break;
bbbf2d40 603
20aeb4b8 604 case CONTEXT_MODULE:
605 // Find course.
606 $cm = get_record('course_modules', 'id', $context->instanceid);
607 $courseinstance = get_context_instance(CONTEXT_COURSE, $cm->course);
9425b25f 608
20aeb4b8 609 if ($parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE)) {
610 foreach ($parentcats as $parentcat) {
611 if (isset($capabilities[$parentcat]['do_anything'])) {
922633bd 612 $result = (0 < $capabilities[$parentcat]['do_anything']);
613 $capcache[$cachekey] = $result;
614 return $result;
20aeb4b8 615 }
cee0901c 616 }
9425b25f 617 }
98882637 618
20aeb4b8 619 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
922633bd 620 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
621 $capcache[$cachekey] = $result;
622 return $result;
20aeb4b8 623 }
bbbf2d40 624
20aeb4b8 625 break;
bbbf2d40 626
20aeb4b8 627 case CONTEXT_BLOCK:
2d95f702 628 // not necessarily 1 to 1 to course.
20aeb4b8 629 $block = get_record('block_instance','id',$context->instanceid);
2d95f702 630 if ($block->pagetype == 'course-view') {
631 $courseinstance = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
632 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE);
633
634 foreach ($parentcats as $parentcat) {
635 if (isset($capabilities[$parentcat]['do_anything'])) {
636 $result = (0 < $capabilities[$parentcat]['do_anything']);
637 $capcache[$cachekey] = $result;
638 return $result;
639 }
640 }
641
642 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
643 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
644 $capcache[$cachekey] = $result;
645 return $result;
646 }
20aeb4b8 647 }
c331cf23 648 // blocks that do not have course as parent do not need to do any more checks - already done above
649
20aeb4b8 650 break;
bbbf2d40 651
20aeb4b8 652 default:
4b10f08b 653 // CONTEXT_SYSTEM: CONTEXT_PERSONAL: CONTEXT_USER:
40a2a15f 654 // Do nothing, because the parents are site context
655 // which has been checked already
20aeb4b8 656 break;
657 }
bbbf2d40 658
20aeb4b8 659 // Last: check self.
660 if (isset($capabilities[$context->id]['do_anything'])) {
922633bd 661 $result = (0 < $capabilities[$context->id]['do_anything']);
662 $capcache[$cachekey] = $result;
663 return $result;
20aeb4b8 664 }
98882637 665 }
caac8977 666 // do_anything has not been set, we now look for it the normal way.
667 $result = (0 < capability_search($capability, $context, $capabilities, $switchroleactive));
922633bd 668 $capcache[$cachekey] = $result;
669 return $result;
bbbf2d40 670
9425b25f 671}
bbbf2d40 672
673
674/**
675 * In a separate function so that we won't have to deal with do_anything.
40a2a15f 676 * again. Used by function has_capability().
bbbf2d40 677 * @param $capability - capability string
0468976c 678 * @param $context - the context object
40a2a15f 679 * @param $capabilities - either $USER->capability or loaded array (for other users)
bbbf2d40 680 * @return permission (int)
681 */
caac8977 682function capability_search($capability, $context, $capabilities, $switchroleactive=false) {
759ac72d 683
5785266f 684 global $USER, $CFG;
0468976c 685
11ac79ff 686 if (!isset($context->id)) {
687 return 0;
688 }
40a2a15f 689 // if already set in the array explicitly, no need to look for it in parent
690 // context any longer
0468976c 691 if (isset($capabilities[$context->id][$capability])) {
692 return ($capabilities[$context->id][$capability]);
bbbf2d40 693 }
9425b25f 694
bbbf2d40 695 /* Then, we check the cache recursively */
9425b25f 696 $permission = 0;
697
aad2ba95 698 switch ($context->contextlevel) {
bbbf2d40 699
700 case CONTEXT_SYSTEM: // by now it's a definite an inherit
701 $permission = 0;
702 break;
703
704 case CONTEXT_PERSONAL:
21c9bace 705 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
a2b6ee75 706 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 707 break;
9425b25f 708
4b10f08b 709 case CONTEXT_USER:
21c9bace 710 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
a2b6ee75 711 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 712 break;
9425b25f 713
bbbf2d40 714 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
5785266f 715 $coursecat = get_record('course_categories','id',$context->instanceid);
716 if (!empty($coursecat->parent)) { // return parent value if it exists
717 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
bbbf2d40 718 } else { // else return site value
21c9bace 719 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
bbbf2d40 720 }
a2b6ee75 721 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 722 break;
723
724 case CONTEXT_COURSE: // 1 to 1 to course cat
caac8977 725 if (empty($switchroleactive)) {
726 // find the course cat, and return its value
5785266f 727 $course = get_record('course','id',$context->instanceid);
caac8977 728 if ($course->id == SITEID) { // In 1.8 we've separated site course and system
729 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
730 } else {
731 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $course->category);
732 }
a2b6ee75 733 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
40a2a15f 734 }
bbbf2d40 735 break;
736
737 case CONTEXT_GROUP: // 1 to 1 to course
5bf243d1 738 $courseid = get_field('groups', 'courseid', 'id', $context->instanceid);
f3f7610c 739 $parentcontext = get_context_instance(CONTEXT_COURSE, $courseid);
a2b6ee75 740 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 741 break;
742
743 case CONTEXT_MODULE: // 1 to 1 to course
744 $cm = get_record('course_modules','id',$context->instanceid);
0468976c 745 $parentcontext = get_context_instance(CONTEXT_COURSE, $cm->course);
a2b6ee75 746 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 747 break;
748
2d95f702 749 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
bbbf2d40 750 $block = get_record('block_instance','id',$context->instanceid);
2d95f702 751 if ($block->pagetype == 'course-view') {
752 $parentcontext = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
753 } else {
754 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
c331cf23 755 }
756 // ignore the $switchroleactive beause we want the real block view capability defined in system context
757 $permission = capability_search($capability, $parentcontext, $capabilities, false);
bbbf2d40 758 break;
759
760 default:
8388ade8 761 error ('This is an unknown context (' . $context->contextlevel . ') in capability_search!');
bbbf2d40 762 return false;
763 }
9425b25f 764
98882637 765 return $permission;
bbbf2d40 766}
767
40a2a15f 768/**
769 * auxillary function for load_user_capabilities()
770 * checks if context c1 is a parent (or itself) of context c2
771 * @param int $c1 - context id of context 1
772 * @param int $c2 - context id of context 2
773 * @return bool
774 */
9fccc080 775function is_parent_context($c1, $c2) {
776 static $parentsarray;
777
778 // context can be itself and this is ok
779 if ($c1 == $c2) {
780 return true;
781 }
782 // hit in cache?
783 if (isset($parentsarray[$c1][$c2])) {
784 return $parentsarray[$c1][$c2];
785 }
786
787 if (!$co2 = get_record('context', 'id', $c2)) {
788 return false;
789 }
790
791 if (!$parents = get_parent_contexts($co2)) {
792 return false;
793 }
794
795 foreach ($parents as $parent) {
796 $parentsarray[$parent][$c2] = true;
797 }
798
799 if (in_array($c1, $parents)) {
800 return true;
801 } else { // else not a parent, set the cache anyway
802 $parentsarray[$c1][$c2] = false;
803 return false;
804 }
805}
806
807
efe12f6c 808/**
9fccc080 809 * auxillary function for load_user_capabilities()
810 * handler in usort() to sort contexts according to level
40a2a15f 811 * @param object contexta
812 * @param object contextb
813 * @return int
9fccc080 814 */
815function roles_context_cmp($contexta, $contextb) {
816 if ($contexta->contextlevel == $contextb->contextlevel) {
817 return 0;
818 }
819 return ($contexta->contextlevel < $contextb->contextlevel) ? -1 : 1;
820}
821
bbbf2d40 822/**
bbbf2d40 823 * It will build an array of all the capabilities at each level
824 * i.e. site/metacourse/course_category/course/moduleinstance
825 * Note we should only load capabilities if they are explicitly assigned already,
826 * we should not load all module's capability!
21c9bace 827 *
bbbf2d40 828 * [Capabilities] => [26][forum_post] = 1
829 * [26][forum_start] = -8990
830 * [26][forum_edit] = -1
831 * [273][blah blah] = 1
832 * [273][blah blah blah] = 2
21c9bace 833 *
834 * @param $capability string - Only get a specific capability (string)
835 * @param $context object - Only get capabilities for a specific context object
836 * @param $userid integer - the id of the user whose capabilities we want to load
c3d1fbe9 837 * @param $checkenrolments boolean - Should we check enrolment plugins (potentially expensive)
21c9bace 838 * @return array of permissions (or nothing if they get assigned to $USER)
bbbf2d40 839 */
6eaa3f09 840function load_user_capability($capability='', $context=NULL, $userid=NULL, $checkenrolments=true) {
d140ad3f 841
98882637 842 global $USER, $CFG;
55526eee 843
40a2a15f 844 // this flag has not been set!
845 // (not clean install, or upgraded successfully to 1.7 and up)
2f1a4248 846 if (empty($CFG->rolesactive)) {
847 return false;
848 }
849
bbbf2d40 850 if (empty($userid)) {
dc411d1b 851 if (empty($USER->id)) { // We have no user to get capabilities for
64026e8c 852 debugging('User not logged in for load_user_capability!');
dc411d1b 853 return false;
854 }
64026e8c 855 unset($USER->capabilities); // We don't want possible older capabilites hanging around
856
6eaa3f09 857 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
858 check_enrolment_plugins($USER);
859 }
8f8ed475 860
bbbf2d40 861 $userid = $USER->id;
dc411d1b 862 $otheruserid = false;
bbbf2d40 863 } else {
64026e8c 864 if (!$user = get_record('user', 'id', $userid)) {
865 debugging('Non-existent userid in load_user_capability!');
866 return false;
867 }
868
6eaa3f09 869 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
870 check_enrolment_plugins($user);
871 }
64026e8c 872
9425b25f 873 $otheruserid = $userid;
bbbf2d40 874 }
9425b25f 875
5f70bcc3 876
877/// First we generate a list of all relevant contexts of the user
878
879 $usercontexts = array();
bbbf2d40 880
0468976c 881 if ($context) { // if context is specified
eef868d1 882 $usercontexts = get_parent_contexts($context);
9343a733 883 $usercontexts[] = $context->id; // Add the current context as well
98882637 884 } else { // else, we load everything
5f70bcc3 885 if ($userroles = get_records('role_assignments','userid',$userid)) {
886 foreach ($userroles as $userrole) {
0db6adc9 887 if (!in_array($userrole->contextid, $usercontexts)) {
888 $usercontexts[] = $userrole->contextid;
889 }
5f70bcc3 890 }
98882637 891 }
5f70bcc3 892 }
893
894/// Set up SQL fragments for searching contexts
895
896 if ($usercontexts) {
0468976c 897 $listofcontexts = '('.implode(',', $usercontexts).')';
5f70bcc3 898 $searchcontexts1 = "c1.id IN $listofcontexts AND";
5f70bcc3 899 } else {
c76e095f 900 $searchcontexts1 = '';
bbbf2d40 901 }
3ca2dea5 902
64026e8c 903 if ($capability) {
afe41398 904 // the doanything may override the requested capability
905 $capsearch = " AND (rc.capability = '$capability' OR rc.capability = 'moodle/site:doanything') ";
64026e8c 906 } else {
eef868d1 907 $capsearch ="";
64026e8c 908 }
909
5f70bcc3 910/// Then we use 1 giant SQL to bring out all relevant capabilities.
911/// The first part gets the capabilities of orginal role.
912/// The second part gets the capabilities of overriden roles.
bbbf2d40 913
21c9bace 914 $siteinstance = get_context_instance(CONTEXT_SYSTEM);
9fccc080 915 $capabilities = array(); // Reinitialize.
916
917 // SQL for normal capabilities
918 $SQL1 = "SELECT rc.capability, c1.id as id1, c1.id as id2, (c1.contextlevel * 100) AS aggrlevel,
bbbf2d40 919 SUM(rc.permission) AS sum
920 FROM
eef868d1 921 {$CFG->prefix}role_assignments ra,
42ac3ecf 922 {$CFG->prefix}role_capabilities rc,
923 {$CFG->prefix}context c1
bbbf2d40 924 WHERE
d4649c76 925 ra.contextid=c1.id AND
926 ra.roleid=rc.roleid AND
bbbf2d40 927 ra.userid=$userid AND
5f70bcc3 928 $searchcontexts1
eef868d1 929 rc.contextid=$siteinstance->id
98882637 930 $capsearch
bbbf2d40 931 GROUP BY
55526eee 932 rc.capability, c1.id, c1.contextlevel * 100
bbbf2d40 933 HAVING
9fccc080 934 SUM(rc.permission) != 0
0db6adc9 935
936 UNION ALL
937
938 SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
939 SUM(rc.permission) AS sum
940 FROM
cd54510d 941 {$CFG->prefix}role_assignments ra INNER JOIN
942 {$CFG->prefix}role_capabilities rc on ra.roleid = rc.roleid INNER JOIN
943 {$CFG->prefix}context c1 on ra.contextid = c1.id INNER JOIN
944 {$CFG->prefix}context c2 on rc.contextid = c2.id INNER JOIN
945 {$CFG->prefix}context_rel cr on cr.c1 = c2.id AND cr.c2 = c1.id
0db6adc9 946 WHERE
947 ra.userid=$userid AND
948 $searchcontexts1
949 rc.contextid != $siteinstance->id
950 $capsearch
0db6adc9 951 GROUP BY
55526eee 952 rc.capability, c1.id, c2.id, c1.contextlevel * 100 + c2.contextlevel
0db6adc9 953 HAVING
954 SUM(rc.permission) != 0
9fccc080 955 ORDER BY
956 aggrlevel ASC";
0db6adc9 957
9fccc080 958 if (!$rs = get_recordset_sql($SQL1)) {
959 error("Query failed in load_user_capability.");
960 }
bbbf2d40 961
9fccc080 962 if ($rs && $rs->RecordCount() > 0) {
bcf88cbb 963 while ($caprec = rs_fetch_next_record($rs)) {
964 $array = (array)$caprec;
9fccc080 965 $temprecord = new object;
966
967 foreach ($array as $key=>$val) {
968 if ($key == 'aggrlevel') {
969 $temprecord->contextlevel = $val;
970 } else {
971 $temprecord->{$key} = $val;
972 }
973 }
9fccc080 974 $capabilities[] = $temprecord;
9fccc080 975 }
bcf88cbb 976 rs_close($rs);
b7e40271 977 }
bcf88cbb 978
9fccc080 979 // SQL for overrides
980 // this is take out because we have no way of making sure c1 is indeed related to c2 (parent)
981 // if we do not group by sum, it is possible to have multiple records of rc.capability, c1.id, c2.id, tuple having
982 // different values, we can maually sum it when we go through the list
0db6adc9 983
984 /*
985
9fccc080 986 $SQL2 = "SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
987 rc.permission AS sum
bbbf2d40 988 FROM
42ac3ecf 989 {$CFG->prefix}role_assignments ra,
990 {$CFG->prefix}role_capabilities rc,
991 {$CFG->prefix}context c1,
992 {$CFG->prefix}context c2
bbbf2d40 993 WHERE
d4649c76 994 ra.contextid=c1.id AND
eef868d1 995 ra.roleid=rc.roleid AND
996 ra.userid=$userid AND
997 rc.contextid=c2.id AND
5f70bcc3 998 $searchcontexts1
5f70bcc3 999 rc.contextid != $siteinstance->id
bbbf2d40 1000 $capsearch
eef868d1 1001
bbbf2d40 1002 GROUP BY
21c9bace 1003 rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c1.id, c2.id, rc.permission
bbbf2d40 1004 ORDER BY
75e84883 1005 aggrlevel ASC
0db6adc9 1006 ";*/
9fccc080 1007
0db6adc9 1008/*
9fccc080 1009 if (!$rs = get_recordset_sql($SQL2)) {
75e84883 1010 error("Query failed in load_user_capability.");
1011 }
5cf38a57 1012
bbbf2d40 1013 if ($rs && $rs->RecordCount() > 0) {
bcf88cbb 1014 while ($caprec = rs_fetch_next_record($rs)) {
1015 $array = (array)$caprec;
75e84883 1016 $temprecord = new object;
eef868d1 1017
98882637 1018 foreach ($array as $key=>$val) {
75e84883 1019 if ($key == 'aggrlevel') {
aad2ba95 1020 $temprecord->contextlevel = $val;
75e84883 1021 } else {
1022 $temprecord->{$key} = $val;
1023 }
98882637 1024 }
9fccc080 1025 // for overrides, we have to make sure that context2 is a child of context1
1026 // otherwise the combination makes no sense
0db6adc9 1027 //if (is_parent_context($temprecord->id1, $temprecord->id2)) {
9fccc080 1028 $capabilities[] = $temprecord;
0db6adc9 1029 //} // only write if relevant
bbbf2d40 1030 }
bcf88cbb 1031 rs_close($rs);
bbbf2d40 1032 }
0db6adc9 1033
9fccc080 1034 // this step sorts capabilities according to the contextlevel
1035 // it is very important because the order matters when we
1036 // go through each capabilities later. (i.e. higher level contextlevel
1037 // will override lower contextlevel settings
1038 usort($capabilities, 'roles_context_cmp');
0db6adc9 1039*/
bbbf2d40 1040 /* so up to this point we should have somethign like this
aad2ba95 1041 * $capabilities[1] ->contextlevel = 1000
8ba412da 1042 ->module = 0 // changed from SITEID in 1.8 (??)
bbbf2d40 1043 ->capability = do_anything
1044 ->id = 1 (id is the context id)
1045 ->sum = 0
eef868d1 1046
aad2ba95 1047 * $capabilities[2] ->contextlevel = 1000
8ba412da 1048 ->module = 0 // changed from SITEID in 1.8 (??)
bbbf2d40 1049 ->capability = post_messages
1050 ->id = 1
1051 ->sum = -9000
1052
aad2ba95 1053 * $capabilittes[3] ->contextlevel = 3000
bbbf2d40 1054 ->module = course
1055 ->capability = view_course_activities
1056 ->id = 25
1057 ->sum = 1
1058
aad2ba95 1059 * $capabilittes[4] ->contextlevel = 3000
bbbf2d40 1060 ->module = course
1061 ->capability = view_course_activities
1062 ->id = 26
1063 ->sum = 0 (this is another course)
eef868d1 1064
aad2ba95 1065 * $capabilities[5] ->contextlevel = 3050
bbbf2d40 1066 ->module = course
1067 ->capability = view_course_activities
1068 ->id = 25 (override in course 25)
1069 ->sum = -1
1070 * ....
1071 * now we proceed to write the session array, going from top to bottom
1072 * at anypoint, we need to go up and check parent to look for prohibit
1073 */
1074 // print_object($capabilities);
1075
1076 /* This is where we write to the actualy capabilities array
1077 * what we need to do from here on is
1078 * going down the array from lowest level to highest level
1079 * 1) recursively check for prohibit,
1080 * if any, we write prohibit
1081 * else, we write the value
1082 * 2) at an override level, we overwrite current level
1083 * if it's not set to prohibit already, and if different
1084 * ........ that should be it ........
1085 */
efb58884 1086
1087 // This is the flag used for detecting the current context level. Since we are going through
1088 // the array in ascending order of context level. For normal capabilities, there should only
1089 // be 1 value per (capability, contextlevel, context), because they are already summed. But,
1090 // for overrides, since we are processing them separate, we need to sum the relevcant entries.
1091 // We set this flag when we hit a new level.
1092 // If the flag is already set, we keep adding (summing), otherwise, we just override previous
1093 // settings (from lower level contexts)
1094 $capflags = array(); // (contextid, contextlevel, capability)
98882637 1095 $usercap = array(); // for other user's capabilities
bbbf2d40 1096 foreach ($capabilities as $capability) {
1097
9fccc080 1098 if (!$context = get_context_instance_by_id($capability->id2)) {
7bfa3101 1099 continue; // incorrect stale context
1100 }
0468976c 1101
41811960 1102 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
eef868d1 1103
0468976c 1104 if (capability_prohibits($capability->capability, $context, $capability->sum, $usercap)) {
9fccc080 1105 $usercap[$capability->id2][$capability->capability] = CAP_PROHIBIT;
98882637 1106 continue;
1107 }
efb58884 1108 if (isset($usercap[$capability->id2][$capability->capability])) { // use isset because it can be sum 0
1109 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1110 $usercap[$capability->id2][$capability->capability] += $capability->sum;
1111 } else { // else we override, and update flag
1112 $usercap[$capability->id2][$capability->capability] = $capability->sum;
1113 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1114 }
9fccc080 1115 } else {
1116 $usercap[$capability->id2][$capability->capability] = $capability->sum;
efb58884 1117 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
9fccc080 1118 }
eef868d1 1119
98882637 1120 } else {
1121
0468976c 1122 if (capability_prohibits($capability->capability, $context, $capability->sum)) { // if any parent or parent's parent is set to prohibit
9fccc080 1123 $USER->capabilities[$capability->id2][$capability->capability] = CAP_PROHIBIT;
98882637 1124 continue;
1125 }
eef868d1 1126
98882637 1127 // if no parental prohibit set
1128 // just write to session, i am not sure this is correct yet
1129 // since 3050 shows up after 3000, and 3070 shows up after 3050,
1130 // it should be ok just to overwrite like this, provided that there's no
1131 // parental prohibits
98882637 1132 // we need to write even if it's 0, because it could be an inherit override
efb58884 1133 if (isset($USER->capabilities[$capability->id2][$capability->capability])) {
1134 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1135 $USER->capabilities[$capability->id2][$capability->capability] += $capability->sum;
1136 } else { // else we override, and update flag
1137 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
1138 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1139 }
9fccc080 1140 } else {
1141 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
efb58884 1142 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
9fccc080 1143 }
98882637 1144 }
bbbf2d40 1145 }
eef868d1 1146
bbbf2d40 1147 // now we don't care about the huge array anymore, we can dispose it.
1148 unset($capabilities);
efb58884 1149 unset($capflags);
eef868d1 1150
dbe7e582 1151 if (!empty($otheruserid)) {
eef868d1 1152 return $usercap; // return the array
bbbf2d40 1153 }
2f1a4248 1154}
1155
1156
eef879ec 1157/**
2f1a4248 1158 * A convenience function to completely load all the capabilities
1159 * for the current user. This is what gets called from login, for example.
1160 */
1161function load_all_capabilities() {
1162 global $USER;
1163
eef879ec 1164 //caching - helps user switching in cron
1165 static $defcaps = false;
bbbf2d40 1166
8e82745a 1167 unset($USER->mycourses); // Reset a cache used by get_my_courses
1168
eef879ec 1169 if (isguestuser()) {
2f1a4248 1170 load_guest_role(); // All non-guest users get this by default
eef879ec 1171
1172 } else if (isloggedin()) {
1173 if ($defcaps === false) {
1174 $defcaps = load_defaultuser_role(true);
1175 }
1176
3887fe4a 1177 load_user_capability();
1178
1179 // when in "course login as" - load only course caqpabilitites (it may not always work as expected)
1180 if (!empty($USER->realuser) and $USER->loginascontext->contextlevel != CONTEXT_SYSTEM) {
1181 $children = get_child_contexts($USER->loginascontext);
1182 $children[] = $USER->loginascontext->id;
1183 foreach ($USER->capabilities as $conid => $caps) {
1184 if (!in_array($conid, $children)) {
1185 unset($USER->capabilities[$conid]);
c16ec802 1186 }
f6f66b03 1187 }
1188 }
eef879ec 1189
3887fe4a 1190 // handle role switching in courses
de5e137a 1191 if (!empty($USER->switchrole)) {
de5e137a 1192 foreach ($USER->switchrole as $contextid => $roleid) {
1193 $context = get_context_instance_by_id($contextid);
1194
1195 // first prune context and any child contexts
1196 $children = get_child_contexts($context);
1197 foreach ($children as $childid) {
1198 unset($USER->capabilities[$childid]);
1199 }
1200 unset($USER->capabilities[$contextid]);
1201
1202 // now merge all switched role caps in context and bellow
1203 $swithccaps = get_role_context_caps($roleid, $context);
1204 $USER->capabilities = merge_role_caps($USER->capabilities, $swithccaps);
1205 }
eef879ec 1206 }
1207
c0aa9f09 1208 if (isset($USER->capabilities)) {
1209 $USER->capabilities = merge_role_caps($USER->capabilities, $defcaps);
1210 } else {
1211 $USER->capabilities = $defcaps;
1212 }
de5e137a 1213
2f1a4248 1214 } else {
eef879ec 1215 load_notloggedin_role();
2f1a4248 1216 }
bbbf2d40 1217}
1218
2f1a4248 1219
efe12f6c 1220/**
64026e8c 1221 * Check all the login enrolment information for the given user object
eef868d1 1222 * by querying the enrolment plugins
64026e8c 1223 */
1224function check_enrolment_plugins(&$user) {
1225 global $CFG;
1226
e4ec4e41 1227 static $inprogress; // To prevent this function being called more than once in an invocation
1228
218eb651 1229 if (!empty($inprogress[$user->id])) {
e4ec4e41 1230 return;
1231 }
1232
218eb651 1233 $inprogress[$user->id] = true; // Set the flag
e4ec4e41 1234
64026e8c 1235 require_once($CFG->dirroot .'/enrol/enrol.class.php');
eef868d1 1236
64026e8c 1237 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
1238 $plugins = array($CFG->enrol);
1239 }
1240
1241 foreach ($plugins as $plugin) {
1242 $enrol = enrolment_factory::factory($plugin);
1243 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1244 $enrol->setup_enrolments($user);
1245 } else { /// Run legacy enrolment methods
1246 if (method_exists($enrol, 'get_student_courses')) {
1247 $enrol->get_student_courses($user);
1248 }
1249 if (method_exists($enrol, 'get_teacher_courses')) {
1250 $enrol->get_teacher_courses($user);
1251 }
1252
1253 /// deal with $user->students and $user->teachers stuff
1254 unset($user->student);
1255 unset($user->teacher);
1256 }
1257 unset($enrol);
1258 }
e4ec4e41 1259
218eb651 1260 unset($inprogress[$user->id]); // Unset the flag
64026e8c 1261}
1262
bbbf2d40 1263
1264/**
1265 * This is a recursive function that checks whether the capability in this
1266 * context, or the parent capabilities are set to prohibit.
1267 *
1268 * At this point, we can probably just use the values already set in the
1269 * session variable, since we are going down the level. Any prohit set in
1270 * parents would already reflect in the session.
1271 *
1272 * @param $capability - capability name
1273 * @param $sum - sum of all capabilities values
0468976c 1274 * @param $context - the context object
bbbf2d40 1275 * @param $array - when loading another user caps, their caps are not stored in session but an array
1276 */
0468976c 1277function capability_prohibits($capability, $context, $sum='', $array='') {
bbbf2d40 1278 global $USER;
0468976c 1279
0db6adc9 1280 // caching, mainly to save unnecessary sqls
1281 static $prohibits; //[capability][contextid]
1282 if (isset($prohibits[$capability][$context->id])) {
1283 return $prohibits[$capability][$context->id];
1284 }
1285
2176adf1 1286 if (empty($context->id)) {
0db6adc9 1287 $prohibits[$capability][$context->id] = false;
2176adf1 1288 return false;
1289 }
1290
1291 if (empty($capability)) {
0db6adc9 1292 $prohibits[$capability][$context->id] = false;
2176adf1 1293 return false;
1294 }
1295
819e5a70 1296 if ($sum < (CAP_PROHIBIT/2)) {
bbbf2d40 1297 // If this capability is set to prohibit.
0db6adc9 1298 $prohibits[$capability][$context->id] = true;
bbbf2d40 1299 return true;
1300 }
eef868d1 1301
819e5a70 1302 if (!empty($array)) {
eef868d1 1303 if (isset($array[$context->id][$capability])
819e5a70 1304 && $array[$context->id][$capability] < (CAP_PROHIBIT/2)) {
0db6adc9 1305 $prohibits[$capability][$context->id] = true;
98882637 1306 return true;
eef868d1 1307 }
bbbf2d40 1308 } else {
98882637 1309 // Else if set in session.
eef868d1 1310 if (isset($USER->capabilities[$context->id][$capability])
819e5a70 1311 && $USER->capabilities[$context->id][$capability] < (CAP_PROHIBIT/2)) {
0db6adc9 1312 $prohibits[$capability][$context->id] = true;
98882637 1313 return true;
1314 }
bbbf2d40 1315 }
aad2ba95 1316 switch ($context->contextlevel) {
eef868d1 1317
bbbf2d40 1318 case CONTEXT_SYSTEM:
1319 // By now it's a definite an inherit.
1320 return 0;
1321 break;
1322
1323 case CONTEXT_PERSONAL:
2176adf1 1324 $parent = get_context_instance(CONTEXT_SYSTEM);
0db6adc9 1325 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1326 return $prohibits[$capability][$context->id];
bbbf2d40 1327 break;
1328
4b10f08b 1329 case CONTEXT_USER:
2176adf1 1330 $parent = get_context_instance(CONTEXT_SYSTEM);
0db6adc9 1331 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1332 return $prohibits[$capability][$context->id];
bbbf2d40 1333 break;
1334
1335 case CONTEXT_COURSECAT:
1336 // Coursecat -> coursecat or site.
2176adf1 1337 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
0db6adc9 1338 $prohibits[$capability][$context->id] = false;
2176adf1 1339 return false;
40a2a15f 1340 }
41811960 1341 if (!empty($coursecat->parent)) {
bbbf2d40 1342 // return parent value if exist.
1343 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1344 } else {
1345 // Return site value.
2176adf1 1346 $parent = get_context_instance(CONTEXT_SYSTEM);
bbbf2d40 1347 }
0db6adc9 1348 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1349 return $prohibits[$capability][$context->id];
bbbf2d40 1350 break;
1351
1352 case CONTEXT_COURSE:
1353 // 1 to 1 to course cat.
1354 // Find the course cat, and return its value.
2176adf1 1355 if (!$course = get_record('course','id',$context->instanceid)) {
0db6adc9 1356 $prohibits[$capability][$context->id] = false;
2176adf1 1357 return false;
1358 }
40a2a15f 1359 // Yu: Separating site and site course context
1360 if ($course->id == SITEID) {
1361 $parent = get_context_instance(CONTEXT_SYSTEM);
1362 } else {
1363 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1364 }
0db6adc9 1365 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1366 return $prohibits[$capability][$context->id];
bbbf2d40 1367 break;
1368
1369 case CONTEXT_GROUP:
1370 // 1 to 1 to course.
5bf243d1 1371 if (!$courseid = get_field('groups', 'courseid', 'id', $context->instanceid)) {
0db6adc9 1372 $prohibits[$capability][$context->id] = false;
2176adf1 1373 return false;
1374 }
f3f7610c 1375 $parent = get_context_instance(CONTEXT_COURSE, $courseid);
0db6adc9 1376 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1377 return $prohibits[$capability][$context->id];
bbbf2d40 1378 break;
1379
1380 case CONTEXT_MODULE:
1381 // 1 to 1 to course.
2176adf1 1382 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
0db6adc9 1383 $prohibits[$capability][$context->id] = false;
2176adf1 1384 return false;
1385 }
bbbf2d40 1386 $parent = get_context_instance(CONTEXT_COURSE, $cm->course);
0db6adc9 1387 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1388 return $prohibits[$capability][$context->id];
bbbf2d40 1389 break;
1390
1391 case CONTEXT_BLOCK:
c331cf23 1392 // not necessarily 1 to 1 to course.
2176adf1 1393 if (!$block = get_record('block_instance','id',$context->instanceid)) {
0db6adc9 1394 $prohibits[$capability][$context->id] = false;
2176adf1 1395 return false;
1396 }
6ceebc1f 1397 if ($block->pagetype == 'course-view') {
1398 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
1399 } else {
1400 $parent = get_context_instance(CONTEXT_SYSTEM);
1401 }
0db6adc9 1402 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1403 return $prohibits[$capability][$context->id];
bbbf2d40 1404 break;
1405
1406 default:
2176adf1 1407 print_error('unknowncontext');
1408 return false;
bbbf2d40 1409 }
1410}
1411
1412
1413/**
1414 * A print form function. This should either grab all the capabilities from
1415 * files or a central table for that particular module instance, then present
1416 * them in check boxes. Only relevant capabilities should print for known
1417 * context.
1418 * @param $mod - module id of the mod
1419 */
1420function print_capabilities($modid=0) {
1421 global $CFG;
eef868d1 1422
bbbf2d40 1423 $capabilities = array();
1424
1425 if ($modid) {
1426 // We are in a module specific context.
1427
1428 // Get the mod's name.
1429 // Call the function that grabs the file and parse.
1430 $cm = get_record('course_modules', 'id', $modid);
1431 $module = get_record('modules', 'id', $cm->module);
eef868d1 1432
bbbf2d40 1433 } else {
1434 // Print all capabilities.
1435 foreach ($capabilities as $capability) {
1436 // Prints the check box component.
1437 }
1438 }
1439}
1440
1441
1442/**
1afecc03 1443 * Installs the roles system.
1444 * This function runs on a fresh install as well as on an upgrade from the old
1445 * hard-coded student/teacher/admin etc. roles to the new roles system.
bbbf2d40 1446 */
1afecc03 1447function moodle_install_roles() {
bbbf2d40 1448
1afecc03 1449 global $CFG, $db;
eef868d1 1450
459c1ff1 1451/// Create a system wide context for assignemnt.
21c9bace 1452 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
bbbf2d40 1453
1afecc03 1454
459c1ff1 1455/// Create default/legacy roles and capabilities.
1456/// (1 legacy capability per legacy role at system level).
1457
69aaada0 1458 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1459 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1460 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1461 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1462 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1463 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1464 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1465 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1466 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1467 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1468 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1469 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
c785d40a 1470 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1471 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
2851ba9b 1472
17e5635c 1473/// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
459c1ff1 1474
98882637 1475 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
bbbf2d40 1476 error('Could not assign moodle/site:doanything to the admin role');
1477 }
250934b8 1478 if (!update_capabilities()) {
1479 error('Had trouble upgrading the core capabilities for the Roles System');
1480 }
1afecc03 1481
459c1ff1 1482/// Look inside user_admin, user_creator, user_teachers, user_students and
1483/// assign above new roles. If a user has both teacher and student role,
1484/// only teacher role is assigned. The assignment should be system level.
1485
1afecc03 1486 $dbtables = $db->MetaTables('TABLES');
eef868d1 1487
72da5046 1488/// Set up the progress bar
1489
1490 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1491
1492 $totalcount = $progresscount = 0;
1493 foreach ($usertables as $usertable) {
1494 if (in_array($CFG->prefix.$usertable, $dbtables)) {
1495 $totalcount += count_records($usertable);
1496 }
1497 }
1498
aae37b63 1499 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1500
459c1ff1 1501/// Upgrade the admins.
1502/// Sort using id ASC, first one is primary admin.
1503
1afecc03 1504 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
f1dcf000 1505 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
0f5dafff 1506 while ($admin = rs_fetch_next_record($rs)) {
1afecc03 1507 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
72da5046 1508 $progresscount++;
aae37b63 1509 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1510 }
0f5dafff 1511 rs_close($rs);
1afecc03 1512 }
1513 } else {
1514 // This is a fresh install.
bbbf2d40 1515 }
1afecc03 1516
1517
459c1ff1 1518/// Upgrade course creators.
1afecc03 1519 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
f1dcf000 1520 if ($rs = get_recordset('user_coursecreators')) {
0f5dafff 1521 while ($coursecreator = rs_fetch_next_record($rs)) {
56b4d70d 1522 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
72da5046 1523 $progresscount++;
aae37b63 1524 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1525 }
0f5dafff 1526 rs_close($rs);
1afecc03 1527 }
bbbf2d40 1528 }
1529
1afecc03 1530
459c1ff1 1531/// Upgrade editting teachers and non-editting teachers.
1afecc03 1532 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
f1dcf000 1533 if ($rs = get_recordset('user_teachers')) {
0f5dafff 1534 while ($teacher = rs_fetch_next_record($rs)) {
d5511451 1535
1536 // removed code here to ignore site level assignments
1537 // since the contexts are separated now
1538
17d6a25e 1539 // populate the user_lastaccess table
ece4945b 1540 $access = new object();
17d6a25e 1541 $access->timeaccess = $teacher->timeaccess;
1542 $access->userid = $teacher->userid;
1543 $access->courseid = $teacher->course;
1544 insert_record('user_lastaccess', $access);
f1dcf000 1545
17d6a25e 1546 // assign the default student role
1afecc03 1547 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
3fe54e51 1548 // hidden teacher
1549 if ($teacher->authority == 0) {
1550 $hiddenteacher = 1;
1551 } else {
1552 $hiddenteacher = 0;
1553 }
1554
1afecc03 1555 if ($teacher->editall) { // editting teacher
3fe54e51 1556 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1afecc03 1557 } else {
3fe54e51 1558 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1afecc03 1559 }
72da5046 1560 $progresscount++;
aae37b63 1561 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1562 }
0f5dafff 1563 rs_close($rs);
bbbf2d40 1564 }
1565 }
1afecc03 1566
1567
459c1ff1 1568/// Upgrade students.
1afecc03 1569 if (in_array($CFG->prefix.'user_students', $dbtables)) {
f1dcf000 1570 if ($rs = get_recordset('user_students')) {
0f5dafff 1571 while ($student = rs_fetch_next_record($rs)) {
f1dcf000 1572
17d6a25e 1573 // populate the user_lastaccess table
f1dcf000 1574 $access = new object;
17d6a25e 1575 $access->timeaccess = $student->timeaccess;
1576 $access->userid = $student->userid;
1577 $access->courseid = $student->course;
1578 insert_record('user_lastaccess', $access);
f1dcf000 1579
17d6a25e 1580 // assign the default student role
1afecc03 1581 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
1582 role_assign($studentrole, $student->userid, 0, $coursecontext->id);
72da5046 1583 $progresscount++;
aae37b63 1584 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1585 }
0f5dafff 1586 rs_close($rs);
1afecc03 1587 }
bbbf2d40 1588 }
1afecc03 1589
1590
459c1ff1 1591/// Upgrade guest (only 1 entry).
1afecc03 1592 if ($guestuser = get_record('user', 'username', 'guest')) {
1593 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
1594 }
aae37b63 1595 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1596
459c1ff1 1597
1598/// Insert the correct records for legacy roles
945f88ca 1599 allow_assign($adminrole, $adminrole);
1600 allow_assign($adminrole, $coursecreatorrole);
1601 allow_assign($adminrole, $noneditteacherrole);
eef868d1 1602 allow_assign($adminrole, $editteacherrole);
945f88ca 1603 allow_assign($adminrole, $studentrole);
1604 allow_assign($adminrole, $guestrole);
eef868d1 1605
945f88ca 1606 allow_assign($coursecreatorrole, $noneditteacherrole);
1607 allow_assign($coursecreatorrole, $editteacherrole);
eef868d1 1608 allow_assign($coursecreatorrole, $studentrole);
945f88ca 1609 allow_assign($coursecreatorrole, $guestrole);
eef868d1 1610
1611 allow_assign($editteacherrole, $noneditteacherrole);
1612 allow_assign($editteacherrole, $studentrole);
945f88ca 1613 allow_assign($editteacherrole, $guestrole);
eef868d1 1614
459c1ff1 1615/// Set up default permissions for overrides
945f88ca 1616 allow_override($adminrole, $adminrole);
1617 allow_override($adminrole, $coursecreatorrole);
1618 allow_override($adminrole, $noneditteacherrole);
eef868d1 1619 allow_override($adminrole, $editteacherrole);
945f88ca 1620 allow_override($adminrole, $studentrole);
eef868d1 1621 allow_override($adminrole, $guestrole);
c785d40a 1622 allow_override($adminrole, $userrole);
1afecc03 1623
746a04c5 1624
459c1ff1 1625/// Delete the old user tables when we are done
1626
83ea392e 1627 drop_table(new XMLDBTable('user_students'));
1628 drop_table(new XMLDBTable('user_teachers'));
1629 drop_table(new XMLDBTable('user_coursecreators'));
1630 drop_table(new XMLDBTable('user_admins'));
459c1ff1 1631
bbbf2d40 1632}
1633
3562486b 1634/**
1635 * Returns array of all legacy roles.
1636 */
1637function get_legacy_roles() {
1638 return array(
a83addc5 1639 'admin' => 'moodle/legacy:admin',
3562486b 1640 'coursecreator' => 'moodle/legacy:coursecreator',
a83addc5 1641 'editingteacher' => 'moodle/legacy:editingteacher',
1642 'teacher' => 'moodle/legacy:teacher',
1643 'student' => 'moodle/legacy:student',
efe12f6c 1644 'guest' => 'moodle/legacy:guest',
1645 'user' => 'moodle/legacy:user'
3562486b 1646 );
1647}
1648
b357ed13 1649function get_legacy_type($roleid) {
1650 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1651 $legacyroles = get_legacy_roles();
1652
1653 $result = '';
1654 foreach($legacyroles as $ltype=>$lcap) {
1655 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
1656 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
1657 //choose first selected legacy capability - reset the rest
1658 if (empty($result)) {
1659 $result = $ltype;
1660 } else {
66a27728 1661 unassign_capability($lcap, $roleid);
b357ed13 1662 }
1663 }
1664 }
1665
1666 return $result;
1667}
1668
bbbf2d40 1669/**
1670 * Assign the defaults found in this capabality definition to roles that have
1671 * the corresponding legacy capabilities assigned to them.
1672 * @param $legacyperms - an array in the format (example):
1673 * 'guest' => CAP_PREVENT,
1674 * 'student' => CAP_ALLOW,
1675 * 'teacher' => CAP_ALLOW,
1676 * 'editingteacher' => CAP_ALLOW,
1677 * 'coursecreator' => CAP_ALLOW,
1678 * 'admin' => CAP_ALLOW
1679 * @return boolean - success or failure.
1680 */
1681function assign_legacy_capabilities($capability, $legacyperms) {
eef868d1 1682
3562486b 1683 $legacyroles = get_legacy_roles();
1684
bbbf2d40 1685 foreach ($legacyperms as $type => $perm) {
eef868d1 1686
21c9bace 1687 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
eef868d1 1688
3562486b 1689 if (!array_key_exists($type, $legacyroles)) {
1690 error('Incorrect legacy role definition for type: '.$type);
1691 }
eef868d1 1692
3562486b 1693 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW)) {
2e85fffe 1694 foreach ($roles as $role) {
1695 // Assign a site level capability.
1696 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1697 return false;
1698 }
bbbf2d40 1699 }
1700 }
1701 }
1702 return true;
1703}
1704
1705
cee0901c 1706/**
1707 * Checks to see if a capability is a legacy capability.
1708 * @param $capabilityname
1709 * @return boolean
1710 */
bbbf2d40 1711function islegacy($capabilityname) {
d67de0ca 1712 if (strpos($capabilityname, 'moodle/legacy') === 0) {
eef868d1 1713 return true;
d67de0ca 1714 } else {
1715 return false;
98882637 1716 }
bbbf2d40 1717}
1718
cee0901c 1719
1720
1721/**********************************
bbbf2d40 1722 * Context Manipulation functions *
1723 **********************************/
1724
bbbf2d40 1725/**
9991d157 1726 * Create a new context record for use by all roles-related stuff
bbbf2d40 1727 * @param $level
1728 * @param $instanceid
3ca2dea5 1729 *
1730 * @return object newly created context (or existing one with a debug warning)
bbbf2d40 1731 */
aad2ba95 1732function create_context($contextlevel, $instanceid) {
3ca2dea5 1733 if (!$context = get_record('context','contextlevel',$contextlevel,'instanceid',$instanceid)) {
1734 if (!validate_context($contextlevel, $instanceid)) {
1735 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1736 return NULL;
1737 }
8ba412da 1738 if ($contextlevel == CONTEXT_SYSTEM) {
1739 return create_system_context();
1740
1741 }
3ca2dea5 1742 $context = new object();
aad2ba95 1743 $context->contextlevel = $contextlevel;
bbbf2d40 1744 $context->instanceid = $instanceid;
3ca2dea5 1745 if ($id = insert_record('context',$context)) {
c345bb58 1746 $c = get_record('context','id',$id);
0db6adc9 1747 return $c;
3ca2dea5 1748 } else {
1749 debugging('Error: could not insert new context level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1750 return NULL;
1751 }
1752 } else {
1753 debugging('Warning: Context id "'.s($context->id).'" not created, because it already exists.');
1754 return $context;
bbbf2d40 1755 }
1756}
1757
efe12f6c 1758/**
8ba412da 1759 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
1760 */
1761function create_system_context() {
1762 if ($context = get_record('context', 'contextlevel', CONTEXT_SYSTEM, 'instanceid', SITEID)) {
1763 // we are going to change instanceid of system context to 0 now
1764 $context->instanceid = 0;
1765 update_record('context', $context);
1766 //context rel not affected
1767 return $context;
1768
1769 } else {
1770 $context = new object();
1771 $context->contextlevel = CONTEXT_SYSTEM;
1772 $context->instanceid = 0;
1773 if ($context->id = insert_record('context',$context)) {
1774 // we need not to populate context_rel for system context
1775 return $context;
1776 } else {
1777 debugging('Can not create system context');
1778 return NULL;
1779 }
1780 }
1781}
9991d157 1782/**
1783 * Create a new context record for use by all roles-related stuff
1784 * @param $level
1785 * @param $instanceid
3ca2dea5 1786 *
1787 * @return true if properly deleted
9991d157 1788 */
1789function delete_context($contextlevel, $instanceid) {
0db6adc9 1790 if ($context = get_context_instance($contextlevel, $instanceid)) {
1791 delete_records('context_rel', 'c2', $context->id); // might not be a parent
9991d157 1792 return delete_records('context', 'id', $context->id) &&
1793 delete_records('role_assignments', 'contextid', $context->id) &&
0db6adc9 1794 delete_records('role_capabilities', 'contextid', $context->id) &&
1795 delete_records('context_rel', 'c1', $context->id);
9991d157 1796 }
1797 return true;
1798}
1799
3ca2dea5 1800/**
1801 * Validate that object with instanceid really exists in given context level.
1802 *
1803 * return if instanceid object exists
1804 */
1805function validate_context($contextlevel, $instanceid) {
1806 switch ($contextlevel) {
1807
1808 case CONTEXT_SYSTEM:
8ba412da 1809 return ($instanceid == 0);
3ca2dea5 1810
1811 case CONTEXT_PERSONAL:
1812 return (boolean)count_records('user', 'id', $instanceid);
1813
1814 case CONTEXT_USER:
1815 return (boolean)count_records('user', 'id', $instanceid);
1816
1817 case CONTEXT_COURSECAT:
1cd3eba9 1818 if ($instanceid == 0) {
1819 return true; // site course category
1820 }
3ca2dea5 1821 return (boolean)count_records('course_categories', 'id', $instanceid);
1822
1823 case CONTEXT_COURSE:
1824 return (boolean)count_records('course', 'id', $instanceid);
1825
1826 case CONTEXT_GROUP:
f3f7610c 1827 return groups_group_exists($instanceid);
3ca2dea5 1828
1829 case CONTEXT_MODULE:
1830 return (boolean)count_records('course_modules', 'id', $instanceid);
1831
1832 case CONTEXT_BLOCK:
1833 return (boolean)count_records('block_instance', 'id', $instanceid);
1834
1835 default:
1836 return false;
1837 }
1838}
bbbf2d40 1839
1840/**
1841 * Get the context instance as an object. This function will create the
1842 * context instance if it does not exist yet.
e765b5d3 1843 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
1844 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
1845 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
1846 * @return object The context object.
bbbf2d40 1847 */
8ba412da 1848function get_context_instance($contextlevel=NULL, $instance=0) {
e5605780 1849
51195e6f 1850 global $context_cache, $context_cache_id, $CONTEXT;
a36a3a3f 1851 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_PERSONAL, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_GROUP, CONTEXT_MODULE, CONTEXT_BLOCK);
d9a35e12 1852
8ba412da 1853 // Yu: Separating site and site course context - removed CONTEXT_COURSE override when SITEID
9251b26f 1854
1855 // fix for MDL-9016
1856 if ($contextlevel == 'clearcache') {
1857 // Clear ALL cache
1858 $context_cache = array();
1859 $context_cache_id = array();
1860 $CONTEXT = '';
1861 return false;
1862 }
b7cec865 1863
340ea4e8 1864/// If no level is supplied then return the current global context if there is one
aad2ba95 1865 if (empty($contextlevel)) {
340ea4e8 1866 if (empty($CONTEXT)) {
a36a3a3f 1867 //fatal error, code must be fixed
1868 error("Error: get_context_instance() called without a context");
340ea4e8 1869 } else {
1870 return $CONTEXT;
1871 }
e5605780 1872 }
1873
8ba412da 1874/// Backwards compatibility with obsoleted (CONTEXT_SYSTEM, SITEID)
1875 if ($contextlevel == CONTEXT_SYSTEM) {
1876 $instance = 0;
1877 }
1878
a36a3a3f 1879/// check allowed context levels
1880 if (!in_array($contextlevel, $allowed_contexts)) {
7bfa3101 1881 // fatal error, code must be fixed - probably typo or switched parameters
a36a3a3f 1882 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
1883 }
1884
340ea4e8 1885/// Check the cache
aad2ba95 1886 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
1887 return $context_cache[$contextlevel][$instance];
e5605780 1888 }
1889
340ea4e8 1890/// Get it from the database, or create it
aad2ba95 1891 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
1892 create_context($contextlevel, $instance);
1893 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
e5605780 1894 }
1895
ccfc5ecc 1896/// Only add to cache if context isn't empty.
1897 if (!empty($context)) {
aad2ba95 1898 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
ccfc5ecc 1899 $context_cache_id[$context->id] = $context; // Cache it for later
1900 }
0468976c 1901
bbbf2d40 1902 return $context;
1903}
1904
cee0901c 1905
340ea4e8 1906/**
e765b5d3 1907 * Get a context instance as an object, from a given context id.
1908 * @param $id a context id.
1909 * @return object The context object.
340ea4e8 1910 */
1911function get_context_instance_by_id($id) {
1912
d9a35e12 1913 global $context_cache, $context_cache_id;
1914
340ea4e8 1915 if (isset($context_cache_id[$id])) { // Already cached
75e84883 1916 return $context_cache_id[$id];
340ea4e8 1917 }
1918
1919 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
aad2ba95 1920 $context_cache[$context->contextlevel][$context->instanceid] = $context;
340ea4e8 1921 $context_cache_id[$context->id] = $context;
1922 return $context;
1923 }
1924
1925 return false;
1926}
1927
bbbf2d40 1928
8737be58 1929/**
1930 * Get the local override (if any) for a given capability in a role in a context
1931 * @param $roleid
0468976c 1932 * @param $contextid
1933 * @param $capability
8737be58 1934 */
1935function get_local_override($roleid, $contextid, $capability) {
1936 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1937}
1938
1939
bbbf2d40 1940
1941/************************************
1942 * DB TABLE RELATED FUNCTIONS *
1943 ************************************/
1944
cee0901c 1945/**
bbbf2d40 1946 * function that creates a role
1947 * @param name - role name
31f26796 1948 * @param shortname - role short name
bbbf2d40 1949 * @param description - role description
1950 * @param legacy - optional legacy capability
1951 * @return id or false
1952 */
8420bee9 1953function create_role($name, $shortname, $description, $legacy='') {
eef868d1 1954
98882637 1955 // check for duplicate role name
eef868d1 1956
98882637 1957 if ($role = get_record('role','name', $name)) {
eef868d1 1958 error('there is already a role with this name!');
98882637 1959 }
eef868d1 1960
31f26796 1961 if ($role = get_record('role','shortname', $shortname)) {
eef868d1 1962 error('there is already a role with this shortname!');
31f26796 1963 }
1964
b5959f30 1965 $role = new object();
98882637 1966 $role->name = $name;
31f26796 1967 $role->shortname = $shortname;
98882637 1968 $role->description = $description;
eef868d1 1969
8420bee9 1970 //find free sortorder number
1971 $role->sortorder = count_records('role');
1972 while (get_record('role','sortorder', $role->sortorder)) {
1973 $role->sortorder += 1;
b5959f30 1974 }
1975
21c9bace 1976 if (!$context = get_context_instance(CONTEXT_SYSTEM)) {
1977 return false;
1978 }
eef868d1 1979
98882637 1980 if ($id = insert_record('role', $role)) {
eef868d1 1981 if ($legacy) {
1982 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
98882637 1983 }
eef868d1 1984
ec7a8b79 1985 /// By default, users with role:manage at site level
1986 /// should be able to assign users to this new role, and override this new role's capabilities
eef868d1 1987
ec7a8b79 1988 // find all admin roles
e46c0987 1989 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
1990 // foreach admin role
1991 foreach ($adminroles as $arole) {
1992 // write allow_assign and allow_overrid
1993 allow_assign($arole->id, $id);
eef868d1 1994 allow_override($arole->id, $id);
e46c0987 1995 }
ec7a8b79 1996 }
eef868d1 1997
98882637 1998 return $id;
1999 } else {
eef868d1 2000 return false;
98882637 2001 }
eef868d1 2002
bbbf2d40 2003}
2004
8420bee9 2005/**
2006 * function that deletes a role and cleanups up after it
2007 * @param roleid - id of role to delete
2008 * @return success
2009 */
2010function delete_role($roleid) {
c345bb58 2011 global $CFG;
8420bee9 2012 $success = true;
2013
60ace1e1 2014// mdl 10149, check if this is the last active admin role
2015// if we make the admin role not deletable then this part can go
2016
2017 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
2018
2019 if ($role = get_record('role', 'id', $roleid)) {
2020 if (record_exists('role_capabilities', 'contextid', $systemcontext->id, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
2021 // deleting an admin role
2022 $status = false;
2023 if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext)) {
2024 foreach ($adminroles as $adminrole) {
2025 if ($adminrole->id != $roleid) {
2026 // some other admin role
2027 if (record_exists('role_assignments', 'roleid', $adminrole->id, 'contextid', $systemcontext->id)) {
2028 // found another admin role with at least 1 user assigned
2029 $status = true;
2030 break;
2031 }
2032 }
2033 }
2034 }
2035 if ($status !== true) {
2036 error ('You can not delete this role because there is no other admin roles with users assigned');
2037 }
2038 }
2039 }
2040
8420bee9 2041// first unssign all users
2042 if (!role_unassign($roleid)) {
2043 debugging("Error while unassigning all users from role with ID $roleid!");
2044 $success = false;
2045 }
2046
2047// cleanup all references to this role, ignore errors
2048 if ($success) {
c345bb58 2049
2050 // MDL-10679 find all contexts where this role has an override
2051 $contexts = get_records_sql("SELECT contextid, contextid
2052 FROM {$CFG->prefix}role_capabilities
2053 WHERE roleid = $roleid");
2054
8420bee9 2055 delete_records('role_capabilities', 'roleid', $roleid);
c345bb58 2056
2057 // MDL-10679, delete from context_rel if this role holds the last override in these contexts
2058 if ($contexts) {
2059 foreach ($contexts as $context) {
2060 if (!record_exists('role_capabilities', 'contextid', $context->contextid)) {
2061 delete_records('context_rel', 'c1', $context->contextid);
2062 }
2063 }
2064 }
2065
8420bee9 2066 delete_records('role_allow_assign', 'roleid', $roleid);
2067 delete_records('role_allow_assign', 'allowassign', $roleid);
2068 delete_records('role_allow_override', 'roleid', $roleid);
2069 delete_records('role_allow_override', 'allowoverride', $roleid);
c345bb58 2070 delete_records('role_names', 'roleid', $roleid);
8420bee9 2071 }
2072
2073// finally delete the role itself
2074 if ($success and !delete_records('role', 'id', $roleid)) {
ece4945b 2075 debugging("Could not delete role record with ID $roleid!");
8420bee9 2076 $success = false;
2077 }
2078
2079 return $success;
2080}
2081
bbbf2d40 2082/**
2083 * Function to write context specific overrides, or default capabilities.
2084 * @param module - string name
2085 * @param capability - string name
2086 * @param contextid - context id
2087 * @param roleid - role id
2088 * @param permission - int 1,-1 or -1000
96986241 2089 * should not be writing if permission is 0
bbbf2d40 2090 */
e7876c1e 2091function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
eef868d1 2092
98882637 2093 global $USER;
eef868d1 2094
96986241 2095 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
eef868d1 2096 unassign_capability($capability, $roleid, $contextid);
96986241 2097 return true;
98882637 2098 }
eef868d1 2099
2e85fffe 2100 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
e7876c1e 2101
2102 if ($existing and !$overwrite) { // We want to keep whatever is there already
2103 return true;
2104 }
2105
bbbf2d40 2106 $cap = new object;
2107 $cap->contextid = $contextid;
2108 $cap->roleid = $roleid;
2109 $cap->capability = $capability;
2110 $cap->permission = $permission;
2111 $cap->timemodified = time();
9db12da7 2112 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
e7876c1e 2113
2114 if ($existing) {
2115 $cap->id = $existing->id;
2116 return update_record('role_capabilities', $cap);
2117 } else {
c345bb58 2118 $c = get_record('context', 'id', $contextid);
2119 /// MDL-10679 insert context rel here
2120 insert_context_rel ($c);
e7876c1e 2121 return insert_record('role_capabilities', $cap);
2122 }
bbbf2d40 2123}
2124
2125
2126/**
2127 * Unassign a capability from a role.
2128 * @param $roleid - the role id
2129 * @param $capability - the name of the capability
2130 * @return boolean - success or failure
2131 */
2132function unassign_capability($capability, $roleid, $contextid=NULL) {
eef868d1 2133
98882637 2134 if (isset($contextid)) {
c345bb58 2135 // delete from context rel, if this is the last override in this context
98882637 2136 $status = delete_records('role_capabilities', 'capability', $capability,
2137 'roleid', $roleid, 'contextid', $contextid);
c345bb58 2138
2139 // MDL-10679, if this is no more overrides for this context
2140 // delete entries from context where this context is a child
2141 if (!record_exists('role_capabilities', 'contextid', $contextid)) {
2142 delete_records('context_rel', 'c1', $contextid);
2143 }
2144
98882637 2145 } else {
c345bb58 2146 // There is no need to delete from context_rel here because
2147 // this is only used for legacy, for now
98882637 2148 $status = delete_records('role_capabilities', 'capability', $capability,
2149 'roleid', $roleid);
2150 }
2151 return $status;
bbbf2d40 2152}
2153
2154
2155/**
759ac72d 2156 * Get the roles that have a given capability assigned to it. This function
2157 * does not resolve the actual permission of the capability. It just checks
2158 * for assignment only.
bbbf2d40 2159 * @param $capability - capability name (string)
2160 * @param $permission - optional, the permission defined for this capability
2161 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2162 * @return array or role objects
2163 */
ec7a8b79 2164function get_roles_with_capability($capability, $permission=NULL, $context='') {
2165
bbbf2d40 2166 global $CFG;
eef868d1 2167
ec7a8b79 2168 if ($context) {
2169 if ($contexts = get_parent_contexts($context)) {
2170 $listofcontexts = '('.implode(',', $contexts).')';
2171 } else {
21c9bace 2172 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
eef868d1 2173 $listofcontexts = '('.$sitecontext->id.')'; // must be site
2174 }
42ac3ecf 2175 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
ec7a8b79 2176 } else {
2177 $contextstr = '';
2178 }
eef868d1 2179
2180 $selectroles = "SELECT r.*
42ac3ecf 2181 FROM {$CFG->prefix}role r,
2182 {$CFG->prefix}role_capabilities rc
bbbf2d40 2183 WHERE rc.capability = '$capability'
ec7a8b79 2184 AND rc.roleid = r.id $contextstr";
bbbf2d40 2185
2186 if (isset($permission)) {
2187 $selectroles .= " AND rc.permission = '$permission'";
2188 }
2189 return get_records_sql($selectroles);
2190}
2191
2192
2193/**
a9e1c058 2194 * This function makes a role-assignment (a role for a user or group in a particular context)
bbbf2d40 2195 * @param $roleid - the role of the id
2196 * @param $userid - userid
2197 * @param $groupid - group id
2198 * @param $contextid - id of the context
2199 * @param $timestart - time this assignment becomes effective
2200 * @param $timeend - time this assignemnt ceases to be effective
2201 * @uses $USER
2202 * @return id - new id of the assigment
2203 */
69b0088c 2204function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
aa311411 2205 global $USER, $CFG;
bbbf2d40 2206
7eb0b60a 2207 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER);
bbbf2d40 2208
a9e1c058 2209/// Do some data validation
2210
bbbf2d40 2211 if (empty($roleid)) {
9d829c68 2212 debugging('Role ID not provided');
a9e1c058 2213 return false;
bbbf2d40 2214 }
2215
2216 if (empty($userid) && empty($groupid)) {
9d829c68 2217 debugging('Either userid or groupid must be provided');
a9e1c058 2218 return false;
bbbf2d40 2219 }
eef868d1 2220
7700027f 2221 if ($userid && !record_exists('user', 'id', $userid)) {
82396e5b 2222 debugging('User ID '.intval($userid).' does not exist!');
7700027f 2223 return false;
2224 }
bbbf2d40 2225
f3f7610c 2226 if ($groupid && !groups_group_exists($groupid)) {
82396e5b 2227 debugging('Group ID '.intval($groupid).' does not exist!');
dc411d1b 2228 return false;
2229 }
2230
7700027f 2231 if (!$context = get_context_instance_by_id($contextid)) {
82396e5b 2232 debugging('Context ID '.intval($contextid).' does not exist!');
a9e1c058 2233 return false;
bbbf2d40 2234 }
2235
a9e1c058 2236 if (($timestart and $timeend) and ($timestart > $timeend)) {
9d829c68 2237 debugging('The end time can not be earlier than the start time');
a9e1c058 2238 return false;
2239 }
2240
69b0088c 2241 if (!$timemodified) {
2242 $timemodified = time();
2243 }
7700027f 2244
a9e1c058 2245/// Check for existing entry
2246 if ($userid) {
7700027f 2247 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
a9e1c058 2248 } else {
7700027f 2249 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
a9e1c058 2250 }
2251
9ebcb4d2 2252
a9e1c058 2253 $newra = new object;
bbbf2d40 2254
a9e1c058 2255 if (empty($ra)) { // Create a new entry
2256 $newra->roleid = $roleid;
7700027f 2257 $newra->contextid = $context->id;
a9e1c058 2258 $newra->userid = $userid;
a9e1c058 2259 $newra->hidden = $hidden;
f44152f4 2260 $newra->enrol = $enrol;
0616d3e8 2261 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2262 /// by repeating queries with the same exact parameters in a 100 secs time window
2263 $newra->timestart = round($timestart, -2);
a9e1c058 2264 $newra->timeend = $timeend;
69b0088c 2265 $newra->timemodified = $timemodified;
115faa2f 2266 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
a9e1c058 2267
9ebcb4d2 2268 $success = insert_record('role_assignments', $newra);
a9e1c058 2269
2270 } else { // We already have one, just update it
2271
2272 $newra->id = $ra->id;
2273 $newra->hidden = $hidden;
f44152f4 2274 $newra->enrol = $enrol;
0616d3e8 2275 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2276 /// by repeating queries with the same exact parameters in a 100 secs time window
2277 $newra->timestart = round($timestart, -2);
a9e1c058 2278 $newra->timeend = $timeend;
69b0088c 2279 $newra->timemodified = $timemodified;
115faa2f 2280 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
a9e1c058 2281
9ebcb4d2 2282 $success = update_record('role_assignments', $newra);
2283 }
2284
7700027f 2285 if ($success) { /// Role was assigned, so do some other things
2286
2287 /// If the user is the current user, then reload the capabilities too.
2288 if (!empty($USER->id) && $USER->id == $userid) {
2f1a4248 2289 load_all_capabilities();
7700027f 2290 }
9b5d7a46 2291
0f161e1f 2292 /// Ask all the modules if anything needs to be done for this user
2293 if ($mods = get_list_of_plugins('mod')) {
2294 foreach ($mods as $mod) {
2295 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2296 $functionname = $mod.'_role_assign';
2297 if (function_exists($functionname)) {
a7bb9b8f 2298 $functionname($userid, $context, $roleid);
0f161e1f 2299 }
2300 }
2301 }
2302
2303 /// Make sure they have an entry in user_lastaccess for courses they can access
2304 // role_add_lastaccess_entries($userid, $context);
a9e1c058 2305 }
eef868d1 2306
4e5f3064 2307 /// now handle metacourse role assignments if in course context
aad2ba95 2308 if ($success and $context->contextlevel == CONTEXT_COURSE) {
4e5f3064 2309 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2310 foreach ($parents as $parent) {
1aad4310 2311 sync_metacourse($parent->parent_course);
4e5f3064 2312 }
2313 }
2314 }
6eb4f823 2315
2316 return $success;
bbbf2d40 2317}
2318
2319
2320/**
1dc1f037 2321 * Deletes one or more role assignments. You must specify at least one parameter.
bbbf2d40 2322 * @param $roleid
2323 * @param $userid
2324 * @param $groupid
2325 * @param $contextid
6bc1e5d5 2326 * @param $enrol unassign only if enrolment type matches, NULL means anything
bbbf2d40 2327 * @return boolean - success or failure
2328 */
6bc1e5d5 2329function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
d74067e8 2330
2331 global $USER, $CFG;
eef868d1 2332
4e5f3064 2333 $success = true;
d74067e8 2334
1dc1f037 2335 $args = array('roleid', 'userid', 'groupid', 'contextid');
2336 $select = array();
2337 foreach ($args as $arg) {
2338 if ($$arg) {
2339 $select[] = $arg.' = '.$$arg;
2340 }
2341 }
6bc1e5d5 2342 if (!empty($enrol)) {
2343 $select[] = "enrol='$enrol'";
2344 }
d74067e8 2345
1dc1f037 2346 if ($select) {
4e5f3064 2347 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2348 $mods = get_list_of_plugins('mod');
2349 foreach($ras as $ra) {
86e2c51d 2350 /// infinite loop protection when deleting recursively
2351 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
2352 continue;
2353 }
4e5f3064 2354 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
86e2c51d 2355
4e5f3064 2356 /// If the user is the current user, then reload the capabilities too.
2357 if (!empty($USER->id) && $USER->id == $ra->userid) {
2f1a4248 2358 load_all_capabilities();
4e5f3064 2359 }
2360 $context = get_record('context', 'id', $ra->contextid);
0f161e1f 2361
2362 /// Ask all the modules if anything needs to be done for this user
4e5f3064 2363 foreach ($mods as $mod) {
2364 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2365 $functionname = $mod.'_role_unassign';
2366 if (function_exists($functionname)) {
2367 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
2368 }
2369 }
2370
2371 /// now handle metacourse role unassigment and removing from goups if in course context
aad2ba95 2372 if (!empty($context) and $context->contextlevel == CONTEXT_COURSE) {
2515adf9 2373
2374 // cleanup leftover course groups/subscriptions etc when user has
2375 // no capability to view course
35274646 2376 // this may be slow, but this is the proper way of doing it
2377 if (!has_capability('moodle/course:view', $context, $ra->userid)) {
2515adf9 2378 // remove from groups
2c386f82 2379 if ($groups = groups_get_all_groups($context->instanceid)) {
4e5f3064 2380 foreach ($groups as $group) {
2381 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
2382 }
2383 }
2515adf9 2384
2515adf9 2385 // delete lastaccess records
2386 delete_records('user_lastaccess', 'userid', $ra->userid, 'courseid', $context->instanceid);
4e5f3064 2387 }
2515adf9 2388
1aad4310 2389 //unassign roles in metacourses if needed
4e5f3064 2390 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2391 foreach ($parents as $parent) {
1aad4310 2392 sync_metacourse($parent->parent_course);
0f161e1f 2393 }
2394 }
0f161e1f 2395 }
2396 }
d74067e8 2397 }
1dc1f037 2398 }
4e5f3064 2399
2400 return $success;
bbbf2d40 2401}
2402
efe12f6c 2403/**
eef868d1 2404 * A convenience function to take care of the common case where you
b963384f 2405 * just want to enrol someone using the default role into a course
2406 *
2407 * @param object $course
2408 * @param object $user
2409 * @param string $enrol - the plugin used to do this enrolment
2410 */
2411function enrol_into_course($course, $user, $enrol) {
2412
9492291c 2413 $timestart = time();
898d7119 2414 // remove time part from the timestamp and keep only the date part
2415 $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
b963384f 2416 if ($course->enrolperiod) {
898d7119 2417 $timeend = $timestart + $course->enrolperiod;
b963384f 2418 } else {
9492291c 2419 $timeend = 0;
b963384f 2420 }
2421
2422 if ($role = get_default_course_role($course)) {
c4381ef5 2423
2424 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2425
e2183037 2426 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
b963384f 2427 return false;
2428 }
eef868d1 2429
b963384f 2430 email_welcome_message_to_user($course, $user);
eef868d1 2431
b963384f 2432 add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
2433
2434 return true;
2435 }
2436
2437 return false;
2438}
2439
0f161e1f 2440/**
2441 * Add last access times to user_lastaccess as required
2442 * @param $userid
2443 * @param $context
2444 * @return boolean - success or failure
2445 */
2446function role_add_lastaccess_entries($userid, $context) {
2447
2448 global $USER, $CFG;
2449
aad2ba95 2450 if (empty($context->contextlevel)) {
0f161e1f 2451 return false;
2452 }
2453
2454 $lastaccess = new object; // Reusable object below
2455 $lastaccess->userid = $userid;
2456 $lastaccess->timeaccess = 0;
2457
aad2ba95 2458 switch ($context->contextlevel) {
0f161e1f 2459
2460 case CONTEXT_SYSTEM: // For the whole site
2461 if ($courses = get_record('course')) {
2462 foreach ($courses as $course) {
2463 $lastaccess->courseid = $course->id;
2464 role_set_lastaccess($lastaccess);
2465 }
2466 }
2467 break;
2468
2469 case CONTEXT_CATEGORY: // For a whole category
2470 if ($courses = get_record('course', 'category', $context->instanceid)) {
2471 foreach ($courses as $course) {
2472 $lastaccess->courseid = $course->id;
2473 role_set_lastaccess($lastaccess);
2474 }
2475 }
2476 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
2477 foreach ($categories as $category) {
2478 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
2479 role_add_lastaccess_entries($userid, $subcontext);
2480 }
2481 }
2482 break;
eef868d1 2483
0f161e1f 2484
2485 case CONTEXT_COURSE: // For a whole course
2486 if ($course = get_record('course', 'id', $context->instanceid)) {
2487 $lastaccess->courseid = $course->id;
2488 role_set_lastaccess($lastaccess);
2489 }
2490 break;
2491 }
2492}
2493
2494/**
2495 * Delete last access times from user_lastaccess as required
2496 * @param $userid
2497 * @param $context
2498 * @return boolean - success or failure
2499 */
2500function role_remove_lastaccess_entries($userid, $context) {
2501
2502 global $USER, $CFG;
2503
2504}
2505
bbbf2d40 2506
2507/**
2508 * Loads the capability definitions for the component (from file). If no
2509 * capabilities are defined for the component, we simply return an empty array.
2510 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2511 * @return array of capabilities
2512 */
2513function load_capability_def($component) {
2514 global $CFG;
2515
2516 if ($component == 'moodle') {
2517 $defpath = $CFG->libdir.'/db/access.php';
2518 $varprefix = 'moodle';
2519 } else {
0c4d9f49 2520 $compparts = explode('/', $component);
eef868d1 2521
0c4d9f49 2522 if ($compparts[0] == 'block') {
2523 // Blocks are an exception. Blocks directory is 'blocks', and not
2524 // 'block'. So we need to jump through hoops.
2525 $defpath = $CFG->dirroot.'/'.$compparts[0].
2526 's/'.$compparts[1].'/db/access.php';
2527 $varprefix = $compparts[0].'_'.$compparts[1];
89bd8357 2528
ae628043 2529 } else if ($compparts[0] == 'format') {
ce34ed3a 2530 // Similar to the above, course formats are 'format' while they
ae628043 2531 // are stored in 'course/format'.
2532 $defpath = $CFG->dirroot.'/course/'.$component.'/db/access.php';
2533 $varprefix = $compparts[0].'_'.$compparts[1];
89bd8357 2534
ce34ed3a 2535 } else if ($compparts[0] == 'gradeimport') {
89bd8357 2536 $defpath = $CFG->dirroot.'/grade/import/'.$compparts[1].'/db/access.php';
2537 $varprefix = $compparts[0].'_'.$compparts[1];
2538
ce34ed3a 2539 } else if ($compparts[0] == 'gradeexport') {
89bd8357 2540 $defpath = $CFG->dirroot.'/grade/export/'.$compparts[1].'/db/access.php';
2541 $varprefix = $compparts[0].'_'.$compparts[1];
2542
ce34ed3a 2543 } else if ($compparts[0] == 'gradereport') {
89bd8357 2544 $defpath = $CFG->dirroot.'/grade/report/'.$compparts[1].'/db/access.php';
2545 $varprefix = $compparts[0].'_'.$compparts[1];
2546
0c4d9f49 2547 } else {
2548 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
2549 $varprefix = str_replace('/', '_', $component);
2550 }
bbbf2d40 2551 }
2552 $capabilities = array();
eef868d1 2553
bbbf2d40 2554 if (file_exists($defpath)) {
dc268b2f 2555 require($defpath);
bbbf2d40 2556 $capabilities = ${$varprefix.'_capabilities'};
2557 }
2558 return $capabilities;
2559}
2560
2561
2562/**
2563 * Gets the capabilities that have been cached in the database for this
2564 * component.
2565 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2566 * @return array of capabilities
2567 */
2568function get_cached_capabilities($component='moodle') {
2569 if ($component == 'moodle') {
2570 $storedcaps = get_records_select('capabilities',
2571 "name LIKE 'moodle/%:%'");
2572 } else {
2573 $storedcaps = get_records_select('capabilities',
2574 "name LIKE '$component:%'");
2575 }
2576 return $storedcaps;
2577}
2578
3562486b 2579/**
2580 * Returns default capabilities for given legacy role type.
2581 *
2582 * @param string legacy role name
2583 * @return array
2584 */
2585function get_default_capabilities($legacyrole) {
2586 if (!$allcaps = get_records('capabilities')) {
2587 error('Error: no capabilitites defined!');
2588 }
2589 $alldefs = array();
2590 $defaults = array();
2591 $components = array();
2592 foreach ($allcaps as $cap) {
efe12f6c 2593 if (!in_array($cap->component, $components)) {
3562486b 2594 $components[] = $cap->component;
2595 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2596 }
2597 }
2598 foreach($alldefs as $name=>$def) {
2599 if (isset($def['legacy'][$legacyrole])) {
2600 $defaults[$name] = $def['legacy'][$legacyrole];
2601 }
2602 }
2603
2604 //some exceptions
2605 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW;
2606 if ($legacyrole == 'admin') {
2607 $defaults['moodle/site:doanything'] = CAP_ALLOW;
2608 }
2609 return $defaults;
2610}
bbbf2d40 2611
efe12f6c 2612/**
2613 * Reset role capabilitites to default according to selected legacy capability.
2614 * If several legacy caps selected, use the first from get_default_capabilities.
2615 * If no legacy selected, removes all capabilities.
2616 *
2617 * @param int @roleid
2618 */
2619function reset_role_capabilities($roleid) {
2620 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2621 $legacyroles = get_legacy_roles();
2622
2623 $defaultcaps = array();
2624 foreach($legacyroles as $ltype=>$lcap) {
2625 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
2626 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
2627 //choose first selected legacy capability
2628 $defaultcaps = get_default_capabilities($ltype);
2629 break;
2630 }
2631 }
2632
2633 delete_records('role_capabilities', 'roleid', $roleid);
2634 if (!empty($defaultcaps)) {
2635 foreach($defaultcaps as $cap=>$permission) {
2636 assign_capability($cap, $permission, $roleid, $sitecontext->id);
2637 }
2638 }
2639}
2640
bbbf2d40 2641/**
2642 * Updates the capabilities table with the component capability definitions.
2643 * If no parameters are given, the function updates the core moodle
2644 * capabilities.
2645 *
2646 * Note that the absence of the db/access.php capabilities definition file
2647 * will cause any stored capabilities for the component to be removed from
eef868d1 2648 * the database.
bbbf2d40 2649 *
2650 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2651 * @return boolean
2652 */
2653function update_capabilities($component='moodle') {
eef868d1 2654
bbbf2d40 2655 $storedcaps = array();
be4486da 2656
2657 $filecaps = load_capability_def($component);
bbbf2d40 2658 $cachedcaps = get_cached_capabilities($component);
2659 if ($cachedcaps) {
2660 foreach ($cachedcaps as $cachedcap) {
2661 array_push($storedcaps, $cachedcap->name);
5e992f56 2662 // update risk bitmasks and context levels in existing capabilities if needed
be4486da 2663 if (array_key_exists($cachedcap->name, $filecaps)) {
2664 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2b531945 2665 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
be4486da 2666 }
2667 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
5e992f56 2668 $updatecap = new object();
be4486da 2669 $updatecap->id = $cachedcap->id;
2670 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2671 if (!update_record('capabilities', $updatecap)) {
5e992f56 2672 return false;
2673 }
2674 }
2675
2676 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2677 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2678 }
2679 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2680 $updatecap = new object();
2681 $updatecap->id = $cachedcap->id;
2682 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2683 if (!update_record('capabilities', $updatecap)) {
be4486da 2684 return false;
2685 }
2686 }
2687 }
bbbf2d40 2688 }
2689 }
be4486da 2690
bbbf2d40 2691 // Are there new capabilities in the file definition?
2692 $newcaps = array();
eef868d1 2693
bbbf2d40 2694 foreach ($filecaps as $filecap => $def) {
eef868d1 2695 if (!$storedcaps ||
bbbf2d40 2696 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2b531945 2697 if (!array_key_exists('riskbitmask', $def)) {
2698 $def['riskbitmask'] = 0; // no risk if not specified
2699 }
bbbf2d40 2700 $newcaps[$filecap] = $def;
2701 }
2702 }
2703 // Add new capabilities to the stored definition.
2704 foreach ($newcaps as $capname => $capdef) {
2705 $capability = new object;
2706 $capability->name = $capname;
2707 $capability->captype = $capdef['captype'];
2708 $capability->contextlevel = $capdef['contextlevel'];
2709 $capability->component = $component;
be4486da 2710 $capability->riskbitmask = $capdef['riskbitmask'];
eef868d1 2711
bbbf2d40 2712 if (!insert_record('capabilities', $capability, false, 'id')) {
2713 return false;
2714 }
eef868d1 2715
7d8ea286 2716
2717 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
2718 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
2719 foreach ($rolecapabilities as $rolecapability){
2720 //assign_capability will update rather than insert if capability exists
2721 if (!assign_capability($capname, $rolecapability->permission,
2722 $rolecapability->roleid, $rolecapability->contextid, true)){
2723 notify('Could not clone capabilities for '.$capname);
2724 }
2725 }
2726 }
bbbf2d40 2727 // Do we need to assign the new capabilities to roles that have the
2728 // legacy capabilities moodle/legacy:* as well?
7d8ea286 2729 // we ignore legacy key if we have cloned permissions
2730 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
bbbf2d40 2731 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2e85fffe 2732 notify('Could not assign legacy capabilities for '.$capname);
bbbf2d40 2733 }
2734 }
2735 // Are there any capabilities that have been removed from the file
2736 // definition that we need to delete from the stored capabilities and
2737 // role assignments?
2738 capabilities_cleanup($component, $filecaps);
eef868d1 2739
bbbf2d40 2740 return true;
2741}
2742
2743
2744/**
2745 * Deletes cached capabilities that are no longer needed by the component.
2746 * Also unassigns these capabilities from any roles that have them.
2747 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2748 * @param $newcapdef - array of the new capability definitions that will be
2749 * compared with the cached capabilities
2750 * @return int - number of deprecated capabilities that have been removed
2751 */
2752function capabilities_cleanup($component, $newcapdef=NULL) {
eef868d1 2753
bbbf2d40 2754 $removedcount = 0;
eef868d1 2755
bbbf2d40 2756 if ($cachedcaps = get_cached_capabilities($component)) {
2757 foreach ($cachedcaps as $cachedcap) {
2758 if (empty($newcapdef) ||
2759 array_key_exists($cachedcap->name, $newcapdef) === false) {
eef868d1 2760
bbbf2d40 2761 // Remove from capabilities cache.
2762 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
2763 error('Could not delete deprecated capability '.$cachedcap->name);
2764 } else {
2765 $removedcount++;
2766 }
2767 // Delete from roles.
2768 if($roles = get_roles_with_capability($cachedcap->name)) {
2769 foreach($roles as $role) {
46943f7b 2770 if (!unassign_capability($cachedcap->name, $role->id)) {
bbbf2d40 2771 error('Could not unassign deprecated capability '.
2772 $cachedcap->name.' from role '.$role->name);
2773 }
2774 }
2775 }
2776 } // End if.
2777 }
2778 }
2779 return $removedcount;
2780}
2781
2782
2783
cee0901c 2784/****************
2785 * UI FUNCTIONS *
2786 ****************/
bbbf2d40 2787
2788
2789/**
2790 * prints human readable context identifier.
2791 */
cd26d8e0 2792function print_context_name($context, $withprefix = true, $short = false) {
340ea4e8 2793
ec0810ee 2794 $name = '';
aad2ba95 2795 switch ($context->contextlevel) {
ec0810ee 2796
bbbf2d40 2797 case CONTEXT_SYSTEM: // by now it's a definite an inherit
8cf990bc 2798 $name = get_string('coresystem');
340ea4e8 2799 break;
bbbf2d40 2800
2801 case CONTEXT_PERSONAL:
ec0810ee 2802 $name = get_string('personal');
340ea4e8 2803 break;
2804
4b10f08b 2805 case CONTEXT_USER:
ec0810ee 2806 if ($user = get_record('user', 'id', $context->instanceid)) {
cd26d8e0 2807 if ($withprefix){
2808 $name = get_string('user').': ';
2809 }
2810 $name .= fullname($user);
ec0810ee 2811 }
340ea4e8 2812 break;
2813
bbbf2d40 2814 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
ec0810ee 2815 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
cd26d8e0 2816 if ($withprefix){
2817 $name = get_string('category').': ';
2818 }
2819 $name .=format_string($category->name);
ec0810ee 2820 }
340ea4e8 2821 break;
bbbf2d40 2822
2823 case CONTEXT_COURSE: // 1 to 1 to course cat
ec0810ee 2824 if ($course = get_record('course', 'id', $context->instanceid)) {
cd26d8e0 2825 if ($withprefix){
2826 if ($context->instanceid == SITEID) {
2827 $name = get_string('site').': ';
2828 } else {
2829 $name = get_string('course').': ';
2830 }
8cf990bc 2831 }
cd26d8e0 2832 if ($short){
2833 $name .=format_string($course->shortname);
2834 } else {
2835 $name .=format_string($course->fullname);
2836 }
2837
ec0810ee 2838 }
340ea4e8 2839 break;
bbbf2d40 2840
2841 case CONTEXT_GROUP: // 1 to 1 to course
f3f7610c 2842 if ($name = groups_get_group_name($context->instanceid)) {
cd26d8e0 2843 if ($withprefix){
2844 $name = get_string('group').': '. $name;
2845 }
ec0810ee 2846 }
340ea4e8 2847 break;
bbbf2d40 2848
2849 case CONTEXT_MODULE: // 1 to 1 to course
98882637 2850 if ($cm = get_record('course_modules','id',$context->instanceid)) {
2851 if ($module = get_record('modules','id',$cm->module)) {
2852 if ($mod = get_record($module->name, 'id', $cm->instance)) {
cd26d8e0 2853 if ($withprefix){
2854 $name = get_string('activitymodule').': ';
2855 }
2856 $name .= $mod->name;
98882637 2857 }
ec0810ee 2858 }
2859 }
340ea4e8 2860 break;
bbbf2d40 2861
c331cf23 2862 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
98882637 2863 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
2864 if ($block = get_record('block','id',$blockinstance->blockid)) {
91be52d7 2865 global $CFG;
2866 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
2867 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
2868 $blockname = "block_$block->name";
2869 if ($blockobject = new $blockname()) {
cd26d8e0 2870 if ($withprefix){
2871 $name = get_string('block').': ';
2872 }
2873 $name .= $blockobject->title;
91be52d7 2874 }
ec0810ee 2875 }
2876 }
340ea4e8 2877 break;
bbbf2d40 2878
2879 default:
8388ade8 2880 error ('This is an unknown context (' . $context->contextlevel . ') in print_context_name!');
340ea4e8 2881 return false;
2882
2883 }
340ea4e8 2884 return $name;
bbbf2d40 2885}
2886
2887
2888/**
eef868d1 2889 * Extracts the relevant capabilities given a contextid.
bbbf2d40 2890 * All case based, example an instance of forum context.
2891 * Will fetch all forum related capabilities, while course contexts
2892 * Will fetch all capabilities
0468976c 2893 * @param object context
bbbf2d40 2894 * @return array();
2895 *
2896 * capabilities
2897 * `name` varchar(150) NOT NULL,
2898 * `captype` varchar(50) NOT NULL,
2899 * `contextlevel` int(10) NOT NULL,
2900 * `component` varchar(100) NOT NULL,
2901 */
0468976c 2902function fetch_context_capabilities($context) {
eef868d1 2903
98882637 2904 global $CFG;
bbbf2d40 2905
2906 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
eef868d1 2907
aad2ba95 2908 switch ($context->contextlevel) {
bbbf2d40 2909
98882637 2910 case CONTEXT_SYSTEM: // all
2911 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2912 break;
2913
2914 case CONTEXT_PERSONAL:
0a8a95c9 2915 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
bbbf2d40 2916 break;
eef868d1 2917
4b10f08b 2918 case CONTEXT_USER:
8020a016 2919 $SQL = "SELECT *
2920 FROM {$CFG->prefix}capabilities
2921 WHERE contextlevel = ".CONTEXT_USER;
bbbf2d40 2922 break;
eef868d1 2923
bbbf2d40 2924 case CONTEXT_COURSECAT: // all
98882637 2925 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2926 break;
2927
2928 case CONTEXT_COURSE: // all
98882637 2929 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2930 break;
2931
2932 case CONTEXT_GROUP: // group caps
2933 break;
2934
2935 case CONTEXT_MODULE: // mod caps
98882637 2936 $cm = get_record('course_modules', 'id', $context->instanceid);
2937 $module = get_record('modules', 'id', $cm->module);
eef868d1 2938
98882637 2939 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
2940 and component = 'mod/$module->name'";
bbbf2d40 2941 break;
2942
2943 case CONTEXT_BLOCK: // block caps
98882637 2944 $cb = get_record('block_instance', 'id', $context->instanceid);
2945 $block = get_record('block', 'id', $cb->blockid);
eef868d1 2946
98882637 2947 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
7e874772 2948 and ( component = 'block/$block->name' or component = 'moodle')";
bbbf2d40 2949 break;
2950
2951 default:
2952 return false;
2953 }
2954
16e2e2f3 2955 if (!$records = get_records_sql($SQL.' '.$sort)) {
2956 $records = array();
2957 }
ba8d8027 2958
2959/// the rest of code is a bit hacky, think twice before modifying it :-(
69eb59f2 2960
2961 // special sorting of core system capabiltites and enrollments
e9c82dca 2962 if (in_array($context->contextlevel, array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE))) {
69eb59f2 2963 $first = array();
2964 foreach ($records as $key=>$record) {
2965 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
2966 $first[$key] = $record;
2967 unset($records[$key]);
2968 } else if (count($first)){
2969 break;
2970 }
2971 }
2972 if (count($first)) {
2973 $records = $first + $records; // merge the two arrays keeping the keys
2974 }
ba8d8027 2975 } else {
2976 $contextindependentcaps = fetch_context_independent_capabilities();
2977 $records = array_merge($contextindependentcaps, $records);
69eb59f2 2978 }
ba8d8027 2979
bbbf2d40 2980 return $records;
eef868d1 2981
bbbf2d40 2982}
2983
2984
759ac72d 2985/**
2986 * Gets the context-independent capabilities that should be overrridable in
2987 * any context.
2988 * @return array of capability records from the capabilities table.
2989 */
2990function fetch_context_independent_capabilities() {
eef868d1 2991
17e5635c 2992 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
759ac72d 2993 $contextindependentcaps = array(
2994 'moodle/site:accessallgroups'
2995 );
2996
2997 $records = array();
eef868d1 2998
759ac72d 2999 foreach ($contextindependentcaps as $capname) {
3000 $record = get_record('capabilities', 'name', $capname);
3001 array_push($records, $record);
3002 }
3003 return $records;
3004}
3005
3006
bbbf2d40 3007/**
3008 * This function pulls out all the resolved capabilities (overrides and
759ac72d 3009 * defaults) of a role used in capability overrides in contexts at a given
bbbf2d40 3010 * context.
0a8a95c9 3011 * @param obj $context
bbbf2d40 3012 * @param int $roleid
dc558690 3013 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
bbbf2d40 3014 * @return array
3015 */
1648afb2 3016function role_context_capabilities($roleid, $context, $cap='') {
dc558690 3017 global $CFG;
eef868d1 3018
8521d83a 3019 $contexts = get_parent_contexts($context);
3020 $contexts[] = $context->id;
98882637 3021 $contexts = '('.implode(',', $contexts).')';
eef868d1 3022
1648afb2 3023 if ($cap) {
e4697bf7 3024 $search = " AND rc.capability = '$cap' ";
1648afb2 3025 } else {
eef868d1 3026 $search = '';
1648afb2 3027 }
eef868d1 3028
3029 $SQL = "SELECT rc.*
3030 FROM {$CFG->prefix}role_capabilities rc,
dc558690 3031 {$CFG->prefix}context c
3032 WHERE rc.contextid in $contexts
3033 AND rc.roleid = $roleid
3034 AND rc.contextid = c.id $search
aad2ba95 3035 ORDER BY c.contextlevel DESC,
eef868d1 3036 rc.capability DESC";
759ac72d 3037
98882637 3038 $capabilities = array();
eef868d1 3039
4729012f 3040 if ($records = get_records_sql($SQL)) {
3041 // We are traversing via reverse order.
3042 foreach ($records as $record) {
3043 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3044 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
3045 $capabilities[$record->capability] = $record->permission;
eef868d1 3046 }
4729012f 3047 }
98882637 3048 }
3049 return $capabilities;
bbbf2d40 3050}
3051
bbbf2d40 3052/**
eef868d1 3053 * Recursive function which, given a context, find all parent context ids,
bbbf2d40 3054 * and return the array in reverse order, i.e. parent first, then grand
3055 * parent, etc.
3056 * @param object $context
3057 * @return array()
3058 */
bbbf2d40 3059function get_parent_contexts($context) {
759ac72d 3060
1cd03601 3061 static $pcontexts; // cache
3062 if (isset($pcontexts[$context->id])) {
3063 return ($pcontexts[$context->id]);
3064 }
3065
aad2ba95 3066 switch ($context->contextlevel) {
bbbf2d40 3067
3068 case CONTEXT_SYSTEM: // no parent
957861f7 3069 return array();
bbbf2d40 3070 break;
3071
3072 case CONTEXT_PERSONAL:
21c9bace 3073 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
957861f7 3074 return array();
3075 } else {
1cd03601 3076 $res = array($parent->id);
0de75c4c 3077 $pcontexts[$context->id] = $res;
1cd03601 3078 return $res;
957861f7 3079 }
bbbf2d40 3080 break;
eef868d1 3081
4b10f08b 3082 case CONTEXT_USER:
21c9bace 3083 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
957861f7 3084 return array();
3085 } else {
1cd03601 3086 $res = array($parent->id);
0de75c4c 3087 $pcontexts[$context->id] = $res;
1cd03601 3088 return $res;
957861f7 3089 }
bbbf2d40 3090 break;
eef868d1 3091
bbbf2d40 3092 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
957861f7 3093 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
3094 return array();
3095 }
c5ddc3fd 3096 if (!empty($coursecat->parent)) { // return parent value if exist
bbbf2d40 3097 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1cd03601 3098 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3099 $pcontexts[$context->id] = $res;
3100 return $res;
bbbf2d40 3101 } else { // else return site value
21c9bace 3102 $parent = get_context_instance(CONTEXT_SYSTEM);
1cd03601 3103 $res = array($parent->id);
3104 $pcontexts[$context->id] = $res;
3105 return $res;
bbbf2d40 3106 }
3107 break;
3108
3109 case CONTEXT_COURSE: // 1 to 1 to course cat
957861f7 3110 if (!$course = get_record('course','id',$context->instanceid)) {
3111 return array();
3112 }
1936c10e 3113 if ($course->id != SITEID) {
957861f7 3114 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1cd03601 3115 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3116 return $res;
957861f7 3117 } else {
40a2a15f 3118 // Yu: Separating site and site course context
3119 $parent = get_context_instance(CONTEXT_SYSTEM);
1cd03601 3120 $res = array($parent->id);
3121 $pcontexts[$context->id] = $res;
3122 return $res;
957861f7 3123 }
bbbf2d40 3124 break;
3125
3126 case CONTEXT_GROUP: // 1 to 1 to course
f3f7610c 3127 if (! $group = groups_get_group($context->instanceid)) {
957861f7 3128 return array();
3129 }
3130 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
1cd03601 3131 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3132 $pcontexts[$context->id] = $res;
3133 return $res;
957861f7 3134 } else {
3135 return array();
3136 }
bbbf2d40 3137 break;
3138
3139 case CONTEXT_MODULE: // 1 to 1 to course
957861f7 3140 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
3141 return array();
3142 }
3143 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
1cd03601 3144 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3145 $pcontexts[$context->id] = $res;
3146 return $res;
957861f7 3147 } else {
3148 return array();
3149 }
bbbf2d40 3150 break;
3151
c331cf23 3152 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
957861f7 3153 if (!$block = get_record('block_instance','id',$context->instanceid)) {
3154 return array();
3155 }
6ceebc1f 3156 // fix for MDL-9656, block parents are not necessarily courses
3157 if ($block->pagetype == 'course-view') {
3158 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid);
3159 } else {
3160 $parent = get_context_instance(CONTEXT_SYSTEM);
3161 }
3162
3163 if ($parent) {
1cd03601 3164 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3165 $pcontexts[$context->id] = $res;
3166 return $res;
957861f7 3167 } else {
6ceebc1f 3168 return array();
957861f7 3169 }
bbbf2d40 3170 break;
3171
3172 default:
8388ade8 3173 error('This is an unknown context (' . $context->contextlevel . ') in get_parent_contexts!');
bbbf2d40 3174 return false;
3175 }
bbbf2d40 3176}
3177
759ac72d 3178
cdfa3035 3179/**
3180 * Recursive function which, given a context, find all its children context ids.
3181 * @param object $context.
3182 * @return array of children context ids.
3183 */
3184function get_child_contexts($context) {
3185
3186 global $CFG;
3187 $children = array();