MDL-11231 - Missing "correct" tick in Close question with answer '0'. Merged from...
[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 * @return array of contextids
271 */
3bf618ce 272function get_parent_cats($context) {
273 global $COURSE;
eef868d1 274
3bf618ce 275 switch ($context->contextlevel) {
40a2a15f 276 // a category can be the parent of another category
277 // there is no limit of depth in this case
98882637 278 case CONTEXT_COURSECAT:
3bf618ce 279 static $categoryparents = null; // cache for parent categories
280 if (!isset($categoryparents)) {
281 $categoryparents = array();
282 }
283 if (array_key_exists($context->instanceid, $categoryparents)) {
284 return $categoryparents[$context->instanceid];
c5ddc3fd 285 }
286
3bf618ce 287 if (!$cat = get_record('course_categories','id',$context->instanceid)) {
288 //error?
289 return array();
290 }
291 $parents = array();
c5ddc3fd 292 while (!empty($cat->parent)) {
3bf618ce 293 if (!$catcontext = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
294 debugging('Incorrect category parent');
c5ddc3fd 295 break;
296 }
3bf618ce 297 $parents[] = $catcontext->id;
98882637 298 $cat = get_record('course_categories','id',$cat->parent);
299 }
3bf618ce 300 return $categoryparents[$context->instanceid] = array_reverse($parents);
98882637 301 break;
40a2a15f 302
303 // a course always fall into a category, unless it's a site course
8ba412da 304 // this happens when SITEID == $course->id
40a2a15f 305 // in this case the parent of the course is site context
98882637 306 case CONTEXT_COURSE:
3bf618ce 307 static $courseparents = null; // cache course parents
308 if (!isset($courseparents)) {
309 $courseparents = array();
c5ddc3fd 310 }
3bf618ce 311 if (array_key_exists($context->instanceid, $courseparents)) {
312 return $courseparents[$context->instanceid];
c5ddc3fd 313 }
47ba005d 314
315 if (count($courseparents) > 1000) {
316 $courseparents = array(); // max cache size when looping through thousands of courses
317 }
318
3bf618ce 319 if ($context->instanceid == SITEID) {
320 return $courseparents[$context->instanceid] = array(); // frontpage course does not have parent cats
c5ddc3fd 321 }
3bf618ce 322 if ($context->instanceid == $COURSE->id) {
323 $course = $COURSE;
324 } else if (!$course = get_record('course', 'id', $context->instanceid)) {
325 //error?
326 return array();;
40a2a15f 327 }
c5ddc3fd 328
3bf618ce 329 if (empty($course->category)) {
330 // this should not happen
331 return $courseparents[$context->instanceid] = array();
332 }
333
334 if (!$catcontext = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
335 debugging('Incorect course category');
336 return array();;
98882637 337 }
3bf618ce 338
339 return $courseparents[$context->instanceid] = array_merge(get_parent_cats($catcontext), array($catcontext->id)); //recursion :-)
98882637 340 break;
eef868d1 341
98882637 342 default:
3bf618ce 343 // something is very wrong!
344 return array();
98882637 345 break;
98882637 346 }
bbbf2d40 347}
348
349
cee0901c 350
0468976c 351/**
352 * This function checks for a capability assertion being true. If it isn't
353 * then the page is terminated neatly with a standard error message
354 * @param string $capability - name of the capability
355 * @param object $context - a context object (record from context table)
356 * @param integer $userid - a userid number
d74067e8 357 * @param bool $doanything - if false, ignore do anything
0468976c 358 * @param string $errorstring - an errorstring
d74067e8 359 * @param string $stringfile - which stringfile to get it from
0468976c 360 */
eef868d1 361function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
71483894 362 $errormessage='nopermissions', $stringfile='') {
a9e1c058 363
71483894 364 global $USER, $CFG;
a9e1c058 365
71483894 366/// If the current user is not logged in, then make sure they are (if needed)
a9e1c058 367
6605128e 368 if (empty($userid) and empty($USER->capabilities)) {
aad2ba95 369 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
a9e1c058 370 require_login($context->instanceid);
11ac79ff 371 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
372 if ($cm = get_record('course_modules','id',$context->instanceid)) {
71483894 373 if (!$course = get_record('course', 'id', $cm->course)) {
374 error('Incorrect course.');
375 }
376 require_course_login($course, true, $cm);
377
11ac79ff 378 } else {
379 require_login();
380 }
71483894 381 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
382 if (!empty($CFG->forcelogin)) {
383 require_login();
384 }
385
a9e1c058 386 } else {
387 require_login();
388 }
389 }
eef868d1 390
a9e1c058 391/// OK, if they still don't have the capability then print a nice error message
392
d74067e8 393 if (!has_capability($capability, $context, $userid, $doanything)) {
0468976c 394 $capabilityname = get_capability_string($capability);
395 print_error($errormessage, $stringfile, '', $capabilityname);
396 }
397}
398
e6260a45 399/**
400 * Cheks if current user has allowed permission for any of submitted capabilities
401 * in given or child contexts.
402 * @param object $context - a context object (record from context table)
403 * @param array $capabilitynames array of strings, capability names
404 * @return boolean
405 */
406function has_capability_including_child_contexts($context, $capabilitynames) {
407 global $USER;
408
409 foreach ($capabilitynames as $capname) {
410 if (has_capability($capname, $context)) {
411 return true;
412 }
413 }
414
415 if ($children = get_child_contexts($context)) {
416 foreach ($capabilitynames as $capname) {
417 foreach ($children as $child) {
dda63707 418 if (isset($USER->capabilities[$child][$capname]) and $USER->capabilities[$child][$capname] > 0) {
e6260a45 419 // extra check for inherited prevent and prohibit
420 if (has_capability($capname, get_context_instance_by_id($child), $USER->id, false)) {
421 return true;
422 }
423 }
424 }
425 }
426 }
427
428 return false;
429}
0468976c 430
bbbf2d40 431/**
432 * This function returns whether the current user has the capability of performing a function
7d8ea286 433 * For example, we can do has_capability('mod/forum:replypost',$context) in forum
434 * This is a recursive function.
bbbf2d40 435 * @uses $USER
caac8977 436 * @param string $capability - name of the capability (or debugcache or clearcache)
0468976c 437 * @param object $context - a context object (record from context table)
438 * @param integer $userid - a userid number
20aeb4b8 439 * @param bool $doanything - if false, ignore do anything
bbbf2d40 440 * @return bool
441 */
d74067e8 442function has_capability($capability, $context=NULL, $userid=NULL, $doanything=true) {
bbbf2d40 443
20aeb4b8 444 global $USER, $CONTEXT, $CFG;
bbbf2d40 445
922633bd 446 static $capcache = array(); // Cache of capabilities
447
caac8977 448
449/// Cache management
450
451 if ($capability == 'clearcache') {
452 $capcache = array(); // Clear ALL the capability cache
453 return false;
454 }
455
922633bd 456/// Some sanity checks
6d2d91d6 457 if (debugging('',DEBUG_DEVELOPER)) {
922633bd 458 if ($capability == 'debugcache') {
459 print_object($capcache);
460 return true;
461 }
462 if (!record_exists('capabilities', 'name', $capability)) {
463 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
464 }
465 if ($doanything != true and $doanything != false) {
466 debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
467 }
468 if (!is_object($context) && $context !== NULL) {
469 debugging('Incorrect context parameter "'.$context.'" for has_capability(), object expected! This should be fixed in code.');
470 }
a8a7300a 471 }
472
922633bd 473/// Make sure we know the current context
474 if (empty($context)) { // Use default CONTEXT if none specified
475 if (empty($CONTEXT)) {
476 return false;
477 } else {
478 $context = $CONTEXT;
479 }
480 } else { // A context was given to us
481 if (empty($CONTEXT)) {
482 $CONTEXT = $context; // Store FIRST used context in this global as future default
483 }
484 }
485
486/// Check and return cache in case we've processed this one before.
8d2b18a8 487 $requsteduser = empty($userid) ? $USER->id : $userid; // find out the requested user id, $USER->id might have been changed
488 $cachekey = $capability.'_'.$context->id.'_'.intval($requsteduser).'_'.intval($doanything);
caac8977 489
922633bd 490 if (isset($capcache[$cachekey])) {
491 return $capcache[$cachekey];
492 }
493
20aeb4b8 494
922633bd 495/// Load up the capabilities list or item as necessary
8d2b18a8 496 if ($userid) {
497 if (empty($USER->id) or ($userid != $USER->id) or empty($USER->capabilities)) {
8d2b18a8 498
eef879ec 499 //caching - helps user switching in cron
500 static $guestuserid = false; // guest user id
501 static $guestcaps = false; // guest caps
502 static $defcaps = false; // default user caps - this might help cron
503
504 if ($guestuserid === false) {
8d2b18a8 505 $guestuserid = get_field('user', 'id', 'username', 'guest');
506 }
507
508 if ($userid == $guestuserid) {
eef879ec 509 if ($guestcaps === false) {
510 $guestcaps = load_guest_role(true);
511 }
512 $capabilities = $guestcaps;
8d2b18a8 513
514 } else {
6eaa3f09 515 // This big SQL is expensive! We reduce it a little by avoiding checking for changed enrolments (false)
516 $capabilities = load_user_capability($capability, $context, $userid, false);
eef879ec 517 if ($defcaps === false) {
8d2b18a8 518 $defcaps = load_defaultuser_role(true);
519 }
eef879ec 520 $capabilities = merge_role_caps($capabilities, $defcaps);
8d2b18a8 521 }
eef879ec 522
523 } else { //$USER->id == $userid and needed capabilities already present
8d2b18a8 524 $capabilities = $USER->capabilities;
9425b25f 525 }
eef879ec 526
9425b25f 527 } else { // no userid
8d2b18a8 528 if (empty($USER->capabilities)) {
eef879ec 529 load_all_capabilities(); // expensive - but we have to do it once anyway
8d2b18a8 530 }
531 $capabilities = $USER->capabilities;
922633bd 532 $userid = $USER->id;
98882637 533 }
9425b25f 534
caac8977 535/// We act a little differently when switchroles is active
536
537 $switchroleactive = false; // Assume it isn't active in this context
538
bbbf2d40 539
922633bd 540/// First deal with the "doanything" capability
5fe9a11d 541
20aeb4b8 542 if ($doanything) {
2d07587b 543
f4e2d38a 544 /// First make sure that we aren't in a "switched role"
545
f4e2d38a 546 if (!empty($USER->switchrole)) { // Switchrole is active somewhere!
547 if (!empty($USER->switchrole[$context->id])) { // Because of current context
548 $switchroleactive = true;
549 } else { // Check parent contexts
550 if ($parentcontextids = get_parent_contexts($context)) {
551 foreach ($parentcontextids as $parentcontextid) {
552 if (!empty($USER->switchrole[$parentcontextid])) { // Yep, switchroles active here
553 $switchroleactive = true;
554 break;
555 }
556 }
557 }
558 }
559 }
560
561 /// Check the site context for doanything (most common) first
562
563 if (empty($switchroleactive)) { // Ignore site setting if switchrole is active
21c9bace 564 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2d07587b 565 if (isset($capabilities[$sitecontext->id]['moodle/site:doanything'])) {
922633bd 566 $result = (0 < $capabilities[$sitecontext->id]['moodle/site:doanything']);
567 $capcache[$cachekey] = $result;
568 return $result;
2d07587b 569 }
20aeb4b8 570 }
40a2a15f 571 /// If it's not set at site level, it is possible to be set on other levels
572 /// Though this usage is not common and can cause risks
aad2ba95 573 switch ($context->contextlevel) {
eef868d1 574
20aeb4b8 575 case CONTEXT_COURSECAT:
576 // Check parent cats.
3bf618ce 577 $parentcats = get_parent_cats($context);
20aeb4b8 578 foreach ($parentcats as $parentcat) {
579 if (isset($capabilities[$parentcat]['moodle/site:doanything'])) {
922633bd 580 $result = (0 < $capabilities[$parentcat]['moodle/site:doanything']);
581 $capcache[$cachekey] = $result;
582 return $result;
20aeb4b8 583 }
cee0901c 584 }
20aeb4b8 585 break;
bbbf2d40 586
20aeb4b8 587 case CONTEXT_COURSE:
588 // Check parent cat.
3bf618ce 589 $parentcats = get_parent_cats($context);
98882637 590
20aeb4b8 591 foreach ($parentcats as $parentcat) {
592 if (isset($capabilities[$parentcat]['do_anything'])) {
922633bd 593 $result = (0 < $capabilities[$parentcat]['do_anything']);
594 $capcache[$cachekey] = $result;
595 return $result;
20aeb4b8 596 }
9425b25f 597 }
20aeb4b8 598 break;
bbbf2d40 599
20aeb4b8 600 case CONTEXT_GROUP:
601 // Find course.
5bf243d1 602 $courseid = get_field('groups', 'courseid', 'id', $context->instanceid);
f3f7610c 603 $courseinstance = get_context_instance(CONTEXT_COURSE, $courseid);
9425b25f 604
3bf618ce 605 $parentcats = get_parent_cats($courseinstance);
20aeb4b8 606 foreach ($parentcats as $parentcat) {
b4a1805a 607 if (isset($capabilities[$parentcat]['do_anything'])) {
608 $result = (0 < $capabilities[$parentcat]['do_anything']);
922633bd 609 $capcache[$cachekey] = $result;
610 return $result;
20aeb4b8 611 }
9425b25f 612 }
9425b25f 613
20aeb4b8 614 $coursecontext = '';
615 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
922633bd 616 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
617 $capcache[$cachekey] = $result;
618 return $result;
20aeb4b8 619 }
9425b25f 620
20aeb4b8 621 break;
bbbf2d40 622
20aeb4b8 623 case CONTEXT_MODULE:
624 // Find course.
625 $cm = get_record('course_modules', 'id', $context->instanceid);
626 $courseinstance = get_context_instance(CONTEXT_COURSE, $cm->course);
9425b25f 627
3bf618ce 628 if ($parentcats = get_parent_cats($courseinstance)) {
20aeb4b8 629 foreach ($parentcats as $parentcat) {
630 if (isset($capabilities[$parentcat]['do_anything'])) {
922633bd 631 $result = (0 < $capabilities[$parentcat]['do_anything']);
632 $capcache[$cachekey] = $result;
633 return $result;
20aeb4b8 634 }
cee0901c 635 }
9425b25f 636 }
98882637 637
20aeb4b8 638 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
922633bd 639 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
640 $capcache[$cachekey] = $result;
641 return $result;
20aeb4b8 642 }
bbbf2d40 643
20aeb4b8 644 break;
bbbf2d40 645
20aeb4b8 646 case CONTEXT_BLOCK:
2d95f702 647 // not necessarily 1 to 1 to course.
20aeb4b8 648 $block = get_record('block_instance','id',$context->instanceid);
2d95f702 649 if ($block->pagetype == 'course-view') {
650 $courseinstance = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
3bf618ce 651 $parentcats = get_parent_cats($courseinstance);
2d95f702 652
653 foreach ($parentcats as $parentcat) {
654 if (isset($capabilities[$parentcat]['do_anything'])) {
655 $result = (0 < $capabilities[$parentcat]['do_anything']);
656 $capcache[$cachekey] = $result;
657 return $result;
658 }
659 }
660
661 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
662 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
663 $capcache[$cachekey] = $result;
664 return $result;
665 }
20aeb4b8 666 }
c331cf23 667 // blocks that do not have course as parent do not need to do any more checks - already done above
668
20aeb4b8 669 break;
bbbf2d40 670
20aeb4b8 671 default:
4b10f08b 672 // CONTEXT_SYSTEM: CONTEXT_PERSONAL: CONTEXT_USER:
40a2a15f 673 // Do nothing, because the parents are site context
674 // which has been checked already
20aeb4b8 675 break;
676 }
bbbf2d40 677
20aeb4b8 678 // Last: check self.
679 if (isset($capabilities[$context->id]['do_anything'])) {
922633bd 680 $result = (0 < $capabilities[$context->id]['do_anything']);
681 $capcache[$cachekey] = $result;
682 return $result;
20aeb4b8 683 }
98882637 684 }
caac8977 685 // do_anything has not been set, we now look for it the normal way.
686 $result = (0 < capability_search($capability, $context, $capabilities, $switchroleactive));
922633bd 687 $capcache[$cachekey] = $result;
688 return $result;
bbbf2d40 689
9425b25f 690}
bbbf2d40 691
692
693/**
694 * In a separate function so that we won't have to deal with do_anything.
40a2a15f 695 * again. Used by function has_capability().
bbbf2d40 696 * @param $capability - capability string
0468976c 697 * @param $context - the context object
40a2a15f 698 * @param $capabilities - either $USER->capability or loaded array (for other users)
bbbf2d40 699 * @return permission (int)
700 */
caac8977 701function capability_search($capability, $context, $capabilities, $switchroleactive=false) {
759ac72d 702
3bf618ce 703 global $USER, $CFG, $COURSE;
0468976c 704
11ac79ff 705 if (!isset($context->id)) {
706 return 0;
707 }
40a2a15f 708 // if already set in the array explicitly, no need to look for it in parent
709 // context any longer
0468976c 710 if (isset($capabilities[$context->id][$capability])) {
711 return ($capabilities[$context->id][$capability]);
bbbf2d40 712 }
9425b25f 713
bbbf2d40 714 /* Then, we check the cache recursively */
9425b25f 715 $permission = 0;
716
aad2ba95 717 switch ($context->contextlevel) {
bbbf2d40 718
719 case CONTEXT_SYSTEM: // by now it's a definite an inherit
720 $permission = 0;
721 break;
722
723 case CONTEXT_PERSONAL:
21c9bace 724 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
a2b6ee75 725 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 726 break;
9425b25f 727
4b10f08b 728 case CONTEXT_USER:
21c9bace 729 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
a2b6ee75 730 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 731 break;
9425b25f 732
3bf618ce 733 case CONTEXT_COURSE:
734 if ($switchroleactive) {
735 // if switchrole active, do not check permissions above the course context, blocks are an exception
736 break;
bbbf2d40 737 }
3bf618ce 738 // break is not here intentionally - because the code is the same for category and course
739 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
740 $parents = get_parent_cats($context); // cached internally
bbbf2d40 741
3bf618ce 742 // non recursive - should be faster
743 foreach ($parents as $parentid) {
744 $parentcontext = get_context_instance_by_id($parentid);
745 if (isset($capabilities[$parentcontext->id][$capability])) {
746 return ($capabilities[$parentcontext->id][$capability]);
caac8977 747 }
40a2a15f 748 }
3bf618ce 749 // finally check system context
750 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
751 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 752 break;
753
754 case CONTEXT_GROUP: // 1 to 1 to course
5bf243d1 755 $courseid = get_field('groups', 'courseid', 'id', $context->instanceid);
f3f7610c 756 $parentcontext = get_context_instance(CONTEXT_COURSE, $courseid);
a2b6ee75 757 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 758 break;
759
760 case CONTEXT_MODULE: // 1 to 1 to course
761 $cm = get_record('course_modules','id',$context->instanceid);
0468976c 762 $parentcontext = get_context_instance(CONTEXT_COURSE, $cm->course);
a2b6ee75 763 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 764 break;
765
2d95f702 766 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
bbbf2d40 767 $block = get_record('block_instance','id',$context->instanceid);
2d95f702 768 if ($block->pagetype == 'course-view') {
769 $parentcontext = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
770 } else {
771 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
c331cf23 772 }
773 // ignore the $switchroleactive beause we want the real block view capability defined in system context
774 $permission = capability_search($capability, $parentcontext, $capabilities, false);
bbbf2d40 775 break;
776
777 default:
8388ade8 778 error ('This is an unknown context (' . $context->contextlevel . ') in capability_search!');
bbbf2d40 779 return false;
780 }
9425b25f 781
98882637 782 return $permission;
bbbf2d40 783}
784
40a2a15f 785/**
786 * auxillary function for load_user_capabilities()
787 * checks if context c1 is a parent (or itself) of context c2
788 * @param int $c1 - context id of context 1
789 * @param int $c2 - context id of context 2
790 * @return bool
791 */
9fccc080 792function is_parent_context($c1, $c2) {
793 static $parentsarray;
794
795 // context can be itself and this is ok
796 if ($c1 == $c2) {
797 return true;
798 }
799 // hit in cache?
800 if (isset($parentsarray[$c1][$c2])) {
801 return $parentsarray[$c1][$c2];
802 }
803
804 if (!$co2 = get_record('context', 'id', $c2)) {
805 return false;
806 }
807
808 if (!$parents = get_parent_contexts($co2)) {
809 return false;
810 }
811
812 foreach ($parents as $parent) {
813 $parentsarray[$parent][$c2] = true;
814 }
815
816 if (in_array($c1, $parents)) {
817 return true;
818 } else { // else not a parent, set the cache anyway
819 $parentsarray[$c1][$c2] = false;
820 return false;
821 }
822}
823
824
efe12f6c 825/**
9fccc080 826 * auxillary function for load_user_capabilities()
827 * handler in usort() to sort contexts according to level
40a2a15f 828 * @param object contexta
829 * @param object contextb
830 * @return int
9fccc080 831 */
832function roles_context_cmp($contexta, $contextb) {
833 if ($contexta->contextlevel == $contextb->contextlevel) {
834 return 0;
835 }
836 return ($contexta->contextlevel < $contextb->contextlevel) ? -1 : 1;
837}
838
bbbf2d40 839/**
bbbf2d40 840 * It will build an array of all the capabilities at each level
841 * i.e. site/metacourse/course_category/course/moduleinstance
842 * Note we should only load capabilities if they are explicitly assigned already,
843 * we should not load all module's capability!
21c9bace 844 *
bbbf2d40 845 * [Capabilities] => [26][forum_post] = 1
846 * [26][forum_start] = -8990
847 * [26][forum_edit] = -1
848 * [273][blah blah] = 1
849 * [273][blah blah blah] = 2
21c9bace 850 *
851 * @param $capability string - Only get a specific capability (string)
852 * @param $context object - Only get capabilities for a specific context object
853 * @param $userid integer - the id of the user whose capabilities we want to load
c3d1fbe9 854 * @param $checkenrolments boolean - Should we check enrolment plugins (potentially expensive)
21c9bace 855 * @return array of permissions (or nothing if they get assigned to $USER)
bbbf2d40 856 */
6eaa3f09 857function load_user_capability($capability='', $context=NULL, $userid=NULL, $checkenrolments=true) {
d140ad3f 858
98882637 859 global $USER, $CFG;
55526eee 860
40a2a15f 861 // this flag has not been set!
862 // (not clean install, or upgraded successfully to 1.7 and up)
2f1a4248 863 if (empty($CFG->rolesactive)) {
864 return false;
865 }
866
bbbf2d40 867 if (empty($userid)) {
dc411d1b 868 if (empty($USER->id)) { // We have no user to get capabilities for
64026e8c 869 debugging('User not logged in for load_user_capability!');
dc411d1b 870 return false;
871 }
64026e8c 872 unset($USER->capabilities); // We don't want possible older capabilites hanging around
873
6eaa3f09 874 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
875 check_enrolment_plugins($USER);
876 }
8f8ed475 877
bbbf2d40 878 $userid = $USER->id;
dc411d1b 879 $otheruserid = false;
bbbf2d40 880 } else {
64026e8c 881 if (!$user = get_record('user', 'id', $userid)) {
882 debugging('Non-existent userid in load_user_capability!');
883 return false;
884 }
885
6eaa3f09 886 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
887 check_enrolment_plugins($user);
888 }
64026e8c 889
9425b25f 890 $otheruserid = $userid;
bbbf2d40 891 }
9425b25f 892
5f70bcc3 893
894/// First we generate a list of all relevant contexts of the user
895
896 $usercontexts = array();
bbbf2d40 897
0468976c 898 if ($context) { // if context is specified
eef868d1 899 $usercontexts = get_parent_contexts($context);
9343a733 900 $usercontexts[] = $context->id; // Add the current context as well
98882637 901 } else { // else, we load everything
5f70bcc3 902 if ($userroles = get_records('role_assignments','userid',$userid)) {
903 foreach ($userroles as $userrole) {
0db6adc9 904 if (!in_array($userrole->contextid, $usercontexts)) {
905 $usercontexts[] = $userrole->contextid;
906 }
5f70bcc3 907 }
98882637 908 }
5f70bcc3 909 }
910
911/// Set up SQL fragments for searching contexts
912
913 if ($usercontexts) {
0468976c 914 $listofcontexts = '('.implode(',', $usercontexts).')';
5f70bcc3 915 $searchcontexts1 = "c1.id IN $listofcontexts AND";
5f70bcc3 916 } else {
c76e095f 917 $searchcontexts1 = '';
bbbf2d40 918 }
3ca2dea5 919
64026e8c 920 if ($capability) {
afe41398 921 // the doanything may override the requested capability
922 $capsearch = " AND (rc.capability = '$capability' OR rc.capability = 'moodle/site:doanything') ";
64026e8c 923 } else {
eef868d1 924 $capsearch ="";
64026e8c 925 }
926
5f70bcc3 927/// Then we use 1 giant SQL to bring out all relevant capabilities.
928/// The first part gets the capabilities of orginal role.
929/// The second part gets the capabilities of overriden roles.
bbbf2d40 930
21c9bace 931 $siteinstance = get_context_instance(CONTEXT_SYSTEM);
9fccc080 932 $capabilities = array(); // Reinitialize.
933
934 // SQL for normal capabilities
935 $SQL1 = "SELECT rc.capability, c1.id as id1, c1.id as id2, (c1.contextlevel * 100) AS aggrlevel,
bbbf2d40 936 SUM(rc.permission) AS sum
937 FROM
eef868d1 938 {$CFG->prefix}role_assignments ra,
42ac3ecf 939 {$CFG->prefix}role_capabilities rc,
940 {$CFG->prefix}context c1
bbbf2d40 941 WHERE
d4649c76 942 ra.contextid=c1.id AND
943 ra.roleid=rc.roleid AND
bbbf2d40 944 ra.userid=$userid AND
5f70bcc3 945 $searchcontexts1
eef868d1 946 rc.contextid=$siteinstance->id
98882637 947 $capsearch
bbbf2d40 948 GROUP BY
55526eee 949 rc.capability, c1.id, c1.contextlevel * 100
bbbf2d40 950 HAVING
9fccc080 951 SUM(rc.permission) != 0
0db6adc9 952
953 UNION ALL
954
955 SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
956 SUM(rc.permission) AS sum
957 FROM
cd54510d 958 {$CFG->prefix}role_assignments ra INNER JOIN
959 {$CFG->prefix}role_capabilities rc on ra.roleid = rc.roleid INNER JOIN
960 {$CFG->prefix}context c1 on ra.contextid = c1.id INNER JOIN
961 {$CFG->prefix}context c2 on rc.contextid = c2.id INNER JOIN
962 {$CFG->prefix}context_rel cr on cr.c1 = c2.id AND cr.c2 = c1.id
0db6adc9 963 WHERE
964 ra.userid=$userid AND
965 $searchcontexts1
966 rc.contextid != $siteinstance->id
967 $capsearch
0db6adc9 968 GROUP BY
55526eee 969 rc.capability, c1.id, c2.id, c1.contextlevel * 100 + c2.contextlevel
0db6adc9 970 HAVING
971 SUM(rc.permission) != 0
9fccc080 972 ORDER BY
973 aggrlevel ASC";
0db6adc9 974
9fccc080 975 if (!$rs = get_recordset_sql($SQL1)) {
976 error("Query failed in load_user_capability.");
977 }
bbbf2d40 978
9fccc080 979 if ($rs && $rs->RecordCount() > 0) {
bcf88cbb 980 while ($caprec = rs_fetch_next_record($rs)) {
981 $array = (array)$caprec;
9fccc080 982 $temprecord = new object;
983
984 foreach ($array as $key=>$val) {
985 if ($key == 'aggrlevel') {
986 $temprecord->contextlevel = $val;
987 } else {
988 $temprecord->{$key} = $val;
989 }
990 }
9fccc080 991 $capabilities[] = $temprecord;
9fccc080 992 }
bcf88cbb 993 rs_close($rs);
b7e40271 994 }
bcf88cbb 995
9fccc080 996 // SQL for overrides
997 // this is take out because we have no way of making sure c1 is indeed related to c2 (parent)
998 // if we do not group by sum, it is possible to have multiple records of rc.capability, c1.id, c2.id, tuple having
999 // different values, we can maually sum it when we go through the list
0db6adc9 1000
1001 /*
1002
9fccc080 1003 $SQL2 = "SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
1004 rc.permission AS sum
bbbf2d40 1005 FROM
42ac3ecf 1006 {$CFG->prefix}role_assignments ra,
1007 {$CFG->prefix}role_capabilities rc,
1008 {$CFG->prefix}context c1,
1009 {$CFG->prefix}context c2
bbbf2d40 1010 WHERE
d4649c76 1011 ra.contextid=c1.id AND
eef868d1 1012 ra.roleid=rc.roleid AND
1013 ra.userid=$userid AND
1014 rc.contextid=c2.id AND
5f70bcc3 1015 $searchcontexts1
5f70bcc3 1016 rc.contextid != $siteinstance->id
bbbf2d40 1017 $capsearch
eef868d1 1018
bbbf2d40 1019 GROUP BY
21c9bace 1020 rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c1.id, c2.id, rc.permission
bbbf2d40 1021 ORDER BY
75e84883 1022 aggrlevel ASC
0db6adc9 1023 ";*/
9fccc080 1024
0db6adc9 1025/*
9fccc080 1026 if (!$rs = get_recordset_sql($SQL2)) {
75e84883 1027 error("Query failed in load_user_capability.");
1028 }
5cf38a57 1029
bbbf2d40 1030 if ($rs && $rs->RecordCount() > 0) {
bcf88cbb 1031 while ($caprec = rs_fetch_next_record($rs)) {
1032 $array = (array)$caprec;
75e84883 1033 $temprecord = new object;
eef868d1 1034
98882637 1035 foreach ($array as $key=>$val) {
75e84883 1036 if ($key == 'aggrlevel') {
aad2ba95 1037 $temprecord->contextlevel = $val;
75e84883 1038 } else {
1039 $temprecord->{$key} = $val;
1040 }
98882637 1041 }
9fccc080 1042 // for overrides, we have to make sure that context2 is a child of context1
1043 // otherwise the combination makes no sense
0db6adc9 1044 //if (is_parent_context($temprecord->id1, $temprecord->id2)) {
9fccc080 1045 $capabilities[] = $temprecord;
0db6adc9 1046 //} // only write if relevant
bbbf2d40 1047 }
bcf88cbb 1048 rs_close($rs);
bbbf2d40 1049 }
0db6adc9 1050
9fccc080 1051 // this step sorts capabilities according to the contextlevel
1052 // it is very important because the order matters when we
1053 // go through each capabilities later. (i.e. higher level contextlevel
1054 // will override lower contextlevel settings
1055 usort($capabilities, 'roles_context_cmp');
0db6adc9 1056*/
bbbf2d40 1057 /* so up to this point we should have somethign like this
aad2ba95 1058 * $capabilities[1] ->contextlevel = 1000
8ba412da 1059 ->module = 0 // changed from SITEID in 1.8 (??)
bbbf2d40 1060 ->capability = do_anything
1061 ->id = 1 (id is the context id)
1062 ->sum = 0
eef868d1 1063
aad2ba95 1064 * $capabilities[2] ->contextlevel = 1000
8ba412da 1065 ->module = 0 // changed from SITEID in 1.8 (??)
bbbf2d40 1066 ->capability = post_messages
1067 ->id = 1
1068 ->sum = -9000
1069
aad2ba95 1070 * $capabilittes[3] ->contextlevel = 3000
bbbf2d40 1071 ->module = course
1072 ->capability = view_course_activities
1073 ->id = 25
1074 ->sum = 1
1075
aad2ba95 1076 * $capabilittes[4] ->contextlevel = 3000
bbbf2d40 1077 ->module = course
1078 ->capability = view_course_activities
1079 ->id = 26
1080 ->sum = 0 (this is another course)
eef868d1 1081
aad2ba95 1082 * $capabilities[5] ->contextlevel = 3050
bbbf2d40 1083 ->module = course
1084 ->capability = view_course_activities
1085 ->id = 25 (override in course 25)
1086 ->sum = -1
1087 * ....
1088 * now we proceed to write the session array, going from top to bottom
1089 * at anypoint, we need to go up and check parent to look for prohibit
1090 */
1091 // print_object($capabilities);
1092
1093 /* This is where we write to the actualy capabilities array
1094 * what we need to do from here on is
1095 * going down the array from lowest level to highest level
1096 * 1) recursively check for prohibit,
1097 * if any, we write prohibit
1098 * else, we write the value
1099 * 2) at an override level, we overwrite current level
1100 * if it's not set to prohibit already, and if different
1101 * ........ that should be it ........
1102 */
efb58884 1103
1104 // This is the flag used for detecting the current context level. Since we are going through
1105 // the array in ascending order of context level. For normal capabilities, there should only
1106 // be 1 value per (capability, contextlevel, context), because they are already summed. But,
1107 // for overrides, since we are processing them separate, we need to sum the relevcant entries.
1108 // We set this flag when we hit a new level.
1109 // If the flag is already set, we keep adding (summing), otherwise, we just override previous
1110 // settings (from lower level contexts)
1111 $capflags = array(); // (contextid, contextlevel, capability)
98882637 1112 $usercap = array(); // for other user's capabilities
bbbf2d40 1113 foreach ($capabilities as $capability) {
1114
9fccc080 1115 if (!$context = get_context_instance_by_id($capability->id2)) {
7bfa3101 1116 continue; // incorrect stale context
1117 }
0468976c 1118
41811960 1119 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
eef868d1 1120
0468976c 1121 if (capability_prohibits($capability->capability, $context, $capability->sum, $usercap)) {
9fccc080 1122 $usercap[$capability->id2][$capability->capability] = CAP_PROHIBIT;
98882637 1123 continue;
1124 }
efb58884 1125 if (isset($usercap[$capability->id2][$capability->capability])) { // use isset because it can be sum 0
1126 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1127 $usercap[$capability->id2][$capability->capability] += $capability->sum;
1128 } else { // else we override, and update flag
1129 $usercap[$capability->id2][$capability->capability] = $capability->sum;
1130 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1131 }
9fccc080 1132 } else {
1133 $usercap[$capability->id2][$capability->capability] = $capability->sum;
efb58884 1134 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
9fccc080 1135 }
eef868d1 1136
98882637 1137 } else {
1138
0468976c 1139 if (capability_prohibits($capability->capability, $context, $capability->sum)) { // if any parent or parent's parent is set to prohibit
9fccc080 1140 $USER->capabilities[$capability->id2][$capability->capability] = CAP_PROHIBIT;
98882637 1141 continue;
1142 }
eef868d1 1143
98882637 1144 // if no parental prohibit set
1145 // just write to session, i am not sure this is correct yet
1146 // since 3050 shows up after 3000, and 3070 shows up after 3050,
1147 // it should be ok just to overwrite like this, provided that there's no
1148 // parental prohibits
98882637 1149 // we need to write even if it's 0, because it could be an inherit override
efb58884 1150 if (isset($USER->capabilities[$capability->id2][$capability->capability])) {
1151 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1152 $USER->capabilities[$capability->id2][$capability->capability] += $capability->sum;
1153 } else { // else we override, and update flag
1154 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
1155 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1156 }
9fccc080 1157 } else {
1158 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
efb58884 1159 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
9fccc080 1160 }
98882637 1161 }
bbbf2d40 1162 }
eef868d1 1163
bbbf2d40 1164 // now we don't care about the huge array anymore, we can dispose it.
1165 unset($capabilities);
efb58884 1166 unset($capflags);
eef868d1 1167
dbe7e582 1168 if (!empty($otheruserid)) {
eef868d1 1169 return $usercap; // return the array
bbbf2d40 1170 }
2f1a4248 1171}
1172
1173
eef879ec 1174/**
2f1a4248 1175 * A convenience function to completely load all the capabilities
1176 * for the current user. This is what gets called from login, for example.
1177 */
1178function load_all_capabilities() {
1179 global $USER;
1180
eef879ec 1181 //caching - helps user switching in cron
1182 static $defcaps = false;
bbbf2d40 1183
8e82745a 1184 unset($USER->mycourses); // Reset a cache used by get_my_courses
1185
eef879ec 1186 if (isguestuser()) {
2f1a4248 1187 load_guest_role(); // All non-guest users get this by default
eef879ec 1188
1189 } else if (isloggedin()) {
1190 if ($defcaps === false) {
1191 $defcaps = load_defaultuser_role(true);
1192 }
1193
3887fe4a 1194 load_user_capability();
1195
1196 // when in "course login as" - load only course caqpabilitites (it may not always work as expected)
1197 if (!empty($USER->realuser) and $USER->loginascontext->contextlevel != CONTEXT_SYSTEM) {
1198 $children = get_child_contexts($USER->loginascontext);
1199 $children[] = $USER->loginascontext->id;
1200 foreach ($USER->capabilities as $conid => $caps) {
1201 if (!in_array($conid, $children)) {
1202 unset($USER->capabilities[$conid]);
c16ec802 1203 }
f6f66b03 1204 }
1205 }
eef879ec 1206
3887fe4a 1207 // handle role switching in courses
de5e137a 1208 if (!empty($USER->switchrole)) {
de5e137a 1209 foreach ($USER->switchrole as $contextid => $roleid) {
1210 $context = get_context_instance_by_id($contextid);
1211
1212 // first prune context and any child contexts
1213 $children = get_child_contexts($context);
1214 foreach ($children as $childid) {
1215 unset($USER->capabilities[$childid]);
1216 }
1217 unset($USER->capabilities[$contextid]);
1218
1219 // now merge all switched role caps in context and bellow
1220 $swithccaps = get_role_context_caps($roleid, $context);
1221 $USER->capabilities = merge_role_caps($USER->capabilities, $swithccaps);
1222 }
eef879ec 1223 }
1224
c0aa9f09 1225 if (isset($USER->capabilities)) {
1226 $USER->capabilities = merge_role_caps($USER->capabilities, $defcaps);
1227 } else {
1228 $USER->capabilities = $defcaps;
1229 }
de5e137a 1230
2f1a4248 1231 } else {
eef879ec 1232 load_notloggedin_role();
2f1a4248 1233 }
bbbf2d40 1234}
1235
2f1a4248 1236
efe12f6c 1237/**
64026e8c 1238 * Check all the login enrolment information for the given user object
eef868d1 1239 * by querying the enrolment plugins
64026e8c 1240 */
1241function check_enrolment_plugins(&$user) {
1242 global $CFG;
1243
e4ec4e41 1244 static $inprogress; // To prevent this function being called more than once in an invocation
1245
218eb651 1246 if (!empty($inprogress[$user->id])) {
e4ec4e41 1247 return;
1248 }
1249
218eb651 1250 $inprogress[$user->id] = true; // Set the flag
e4ec4e41 1251
64026e8c 1252 require_once($CFG->dirroot .'/enrol/enrol.class.php');
eef868d1 1253
64026e8c 1254 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
1255 $plugins = array($CFG->enrol);
1256 }
1257
1258 foreach ($plugins as $plugin) {
1259 $enrol = enrolment_factory::factory($plugin);
1260 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1261 $enrol->setup_enrolments($user);
1262 } else { /// Run legacy enrolment methods
1263 if (method_exists($enrol, 'get_student_courses')) {
1264 $enrol->get_student_courses($user);
1265 }
1266 if (method_exists($enrol, 'get_teacher_courses')) {
1267 $enrol->get_teacher_courses($user);
1268 }
1269
1270 /// deal with $user->students and $user->teachers stuff
1271 unset($user->student);
1272 unset($user->teacher);
1273 }
1274 unset($enrol);
1275 }
e4ec4e41 1276
218eb651 1277 unset($inprogress[$user->id]); // Unset the flag
64026e8c 1278}
1279
bbbf2d40 1280
1281/**
1282 * This is a recursive function that checks whether the capability in this
1283 * context, or the parent capabilities are set to prohibit.
1284 *
1285 * At this point, we can probably just use the values already set in the
1286 * session variable, since we are going down the level. Any prohit set in
1287 * parents would already reflect in the session.
1288 *
1289 * @param $capability - capability name
1290 * @param $sum - sum of all capabilities values
0468976c 1291 * @param $context - the context object
bbbf2d40 1292 * @param $array - when loading another user caps, their caps are not stored in session but an array
1293 */
0468976c 1294function capability_prohibits($capability, $context, $sum='', $array='') {
bbbf2d40 1295 global $USER;
0468976c 1296
0db6adc9 1297 // caching, mainly to save unnecessary sqls
1298 static $prohibits; //[capability][contextid]
1299 if (isset($prohibits[$capability][$context->id])) {
1300 return $prohibits[$capability][$context->id];
1301 }
1302
2176adf1 1303 if (empty($context->id)) {
0db6adc9 1304 $prohibits[$capability][$context->id] = false;
2176adf1 1305 return false;
1306 }
1307
1308 if (empty($capability)) {
0db6adc9 1309 $prohibits[$capability][$context->id] = false;
2176adf1 1310 return false;
1311 }
1312
819e5a70 1313 if ($sum < (CAP_PROHIBIT/2)) {
bbbf2d40 1314 // If this capability is set to prohibit.
0db6adc9 1315 $prohibits[$capability][$context->id] = true;
bbbf2d40 1316 return true;
1317 }
eef868d1 1318
819e5a70 1319 if (!empty($array)) {
eef868d1 1320 if (isset($array[$context->id][$capability])
819e5a70 1321 && $array[$context->id][$capability] < (CAP_PROHIBIT/2)) {
0db6adc9 1322 $prohibits[$capability][$context->id] = true;
98882637 1323 return true;
eef868d1 1324 }
bbbf2d40 1325 } else {
98882637 1326 // Else if set in session.
eef868d1 1327 if (isset($USER->capabilities[$context->id][$capability])
819e5a70 1328 && $USER->capabilities[$context->id][$capability] < (CAP_PROHIBIT/2)) {
0db6adc9 1329 $prohibits[$capability][$context->id] = true;
98882637 1330 return true;
1331 }
bbbf2d40 1332 }
aad2ba95 1333 switch ($context->contextlevel) {
eef868d1 1334
bbbf2d40 1335 case CONTEXT_SYSTEM:
1336 // By now it's a definite an inherit.
1337 return 0;
1338 break;
1339
1340 case CONTEXT_PERSONAL:
2176adf1 1341 $parent = get_context_instance(CONTEXT_SYSTEM);
0db6adc9 1342 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1343 return $prohibits[$capability][$context->id];
bbbf2d40 1344 break;
1345
4b10f08b 1346 case CONTEXT_USER:
2176adf1 1347 $parent = get_context_instance(CONTEXT_SYSTEM);
0db6adc9 1348 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1349 return $prohibits[$capability][$context->id];
bbbf2d40 1350 break;
1351
1352 case CONTEXT_COURSECAT:
bbbf2d40 1353 case CONTEXT_COURSE:
3bf618ce 1354 $parents = get_parent_cats($context); // cached internally
1355 // no workaround for recursion now - it needs some more work and maybe fixing
1356
1357 if (empty($parents)) {
1358 // system context - this is either top category or frontpage course
40a2a15f 1359 $parent = get_context_instance(CONTEXT_SYSTEM);
1360 } else {
3bf618ce 1361 // parent context - recursion
1362 $parentid = array_pop($parents);
1363 $parent = get_context_instance_by_id($parentid);
40a2a15f 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
bbbf2d40 3093 case CONTEXT_COURSE: // 1 to 1 to course cat
3bf618ce 3094 $parents = get_parent_cats($context);
3095 $parents = array_reverse($parents);
3096 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
3097 return $pcontexts[$context->id] = array_merge($parents, array($systemcontext->id));
bbbf2d40 3098 break;
3099
3100 case CONTEXT_GROUP: // 1 to 1 to course
f3f7610c 3101 if (! $group = groups_get_group($context->instanceid)) {
957861f7 3102 return array();
3103 }
3104 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
1cd03601 3105 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3106 $pcontexts[$context->id] = $res;
3107 return $res;
957861f7 3108 } else {
3109 return array();
3110 }
bbbf2d40 3111 break;
3112
3113 case CONTEXT_MODULE: // 1 to 1 to course
957861f7 3114 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
3115 return array();
3116 }
3117 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
1cd03601 3118 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3119 $pcontexts[$context->id] = $res;
3120 return $res;
957861f7 3121 } else {
3122 return array();
3123 }
bbbf2d40 3124 break;
3125
c331cf23 3126 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
957861f7 3127 if (!$block = get_record('block_instance','id',$context->instanceid)) {
3128 return array();
3129 }
6ceebc1f 3130 // fix for MDL-9656, block parents are not necessarily courses
3131 if ($block->pagetype == 'course-view') {
3132 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid);
3133 } else {
3134 $parent = get_context_instance(CONTEXT_SYSTEM);
3135 }
3136
3137 if ($parent) {
1cd03601 3138 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3139 $pcontexts[$context->id] = $res;
3140 return $res;
957861f7 3141 } else {
6ceebc1f 3142 return array();
957861f7 3143 }
bbbf2d40 3144 break;
3145
3146 default:
8388ade8 3147 error('This is an unknown context (' . $context->contextlevel . ') in get_parent_contexts!');
bbbf2d40 3148 return false;
3149 }
bbbf2d40 3150}
3151
759ac72d 3152
cdfa3035 3153/**
3154 * Recursive function which, given a context, find all its children context ids.
3155 * @param object $context.
3156 * @return array of children context ids.
3157 */
3158function get_child_contexts($context) {
3159
3160 global $CFG;
3161 $children = array();
3162
3163 switch ($context->contextlevel) {
3164
3165 case CONTEXT_BLOCK:
3166 // No children.
3167 return array();
3168 break;
3169
3170 case CONTEXT_MODULE:
3171 // No children.
3172 return array();
3173 break;
3174
3175 case CONTEXT_GROUP:
3176 // No children.
3177 return array();
3178 break;
3179
3180 case CONTEXT_COURSE:
3181 // Find all block instances for the course.
3182 $page = new page_course;
3183 $page->id = $context->instanceid;
3184 $page->type = 'course-view';
3185 if ($blocks = blocks_get_by_page_pinned($page)) {
3186 foreach ($blocks['l'] as $leftblock) {
2b91b669 3187 if ($child = get_context_instance(CONTEXT_BLOCK, $leftblock->id)) {
cdfa3035 3188 array_push($children, $child->id);
3189 }
3190 }
3191 foreach ($blocks['r'] as $rightblock) {