lib/setup: declare SYSCONTEXTID to have the system context handy
[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
19bb8a05 92 $searchcontexts = array_keys(get_child_contexts($context));
eef879ec 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
c421ad4b 220 // course:view, which is a hack that's necessary because guest roles are
eef879ec 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;
c421ad4b 302
40a2a15f 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 }
c421ad4b 333
3bf618ce 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
c421ad4b 446 static $capcache = array(); // Cache of capabilities
922633bd 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)
c421ad4b 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
c421ad4b 548 $switchroleactive = true;
f4e2d38a 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
c421ad4b 553 $switchroleactive = true;
f4e2d38a 554 break;
555 }
556 }
557 }
558 }
559 }
560
c421ad4b 561 /// Check the site context for doanything (most common) first
f4e2d38a 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);
c421ad4b 652
2d95f702 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 }
c421ad4b 660
2d95f702 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 }
c421ad4b 708 // if already set in the array explicitly, no need to look for it in parent
40a2a15f 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 {
c421ad4b 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;
c421ad4b 794
9fccc080 795 // context can be itself and this is ok
796 if ($c1 == $c2) {
c421ad4b 797 return true;
9fccc080 798 }
799 // hit in cache?
800 if (isset($parentsarray[$c1][$c2])) {
801 return $parentsarray[$c1][$c2];
802 }
c421ad4b 803
9fccc080 804 if (!$co2 = get_record('context', 'id', $c2)) {
805 return false;
806 }
807
808 if (!$parents = get_parent_contexts($co2)) {
809 return false;
810 }
c421ad4b 811
9fccc080 812 foreach ($parents as $parent) {
813 $parentsarray[$parent][$c2] = true;
814 }
815
816 if (in_array($c1, $parents)) {
c421ad4b 817 return true;
9fccc080 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
c421ad4b 861 // this flag has not been set!
40a2a15f 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
c421ad4b 875 check_enrolment_plugins($USER);
6eaa3f09 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.
c421ad4b 933
9fccc080 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
c421ad4b 951 SUM(rc.permission) != 0
952
0db6adc9 953 UNION ALL
c421ad4b 954
955 SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
0db6adc9 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
c421ad4b 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
c421ad4b 1052 // it is very important because the order matters when we
9fccc080 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 */
c421ad4b 1103
efb58884 1104 // This is the flag used for detecting the current context level. Since we are going through
c421ad4b 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.
efb58884 1108 // We set this flag when we hit a new level.
c421ad4b 1109 // If the flag is already set, we keep adding (summing), otherwise, we just override previous
1110 // settings (from lower level contexts)
efb58884 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
a9bee37e 1173/**
1174 * It will return 2 arrays showing role assignments
1175 * all relevant role capabilities for the user at
1176 * site/metacourse/course_category/course levels
1177 *
1178 * We do _not_ delve deeper than courses because the number of
1179 * overrides at the module/block levels is HUGE.
1180 *
1181 * [ra] => [/path/] = roleid
1182 * [rdef] => [/path/:roleid][capability]=permission
1183 *
1184 * @param $userid integer - the id of the user
1185 *
1186 */
1187function get_user_sitewide_access($userid) {
1188
1189 global $CFG;
1190
1191 // this flag has not been set!
1192 // (not clean install, or upgraded successfully to 1.7 and up)
1193 if (empty($CFG->rolesactive)) {
1194 return false;
1195 }
1196
1197 /* Get in 3 cheap DB queries...
1198 * - role assignments - with role_caps
1199 * - relevant role caps
1200 * - above this user's RAs
1201 * - below this user's RAs - limited to course level
1202 */
1203
1204 $sw = array(); // named list
1205 $sw['ra'] = array();
1206 $sw['rdef'] = array();
1207
1208 $sitectx = get_field('context', 'id','contextlevel', CONTEXT_SYSTEM);
1209 $base = "/$sitectx";
1210
1211 //
1212 // Role assignments - and any rolecaps directly linked
1213 // because it's cheap to read rolecaps here over many
1214 // RAs
1215 //
1216 $sql = "SELECT ctx.path, ra.roleid, rc.capability, rc.permission
1217 FROM {$CFG->prefix}role_assignments ra
1218 JOIN {$CFG->prefix}context ctx
1219 ON ra.contextid=ctx.id
1220 LEFT OUTER JOIN {$CFG->prefix}role_capabilities rc
1221 ON (rc.roleid=ra.roleid AND rc.contextid=ra.contextid)
1222 WHERE ra.userid = $userid AND ctx.contextlevel <= ".CONTEXT_COURSE."
1223 ORDER BY ctx.depth, ctx.path";
1224 $rs = get_recordset_sql($sql);
1225 // parent paths & roles we need to walk up
1226 // this array will bulk up quite a bit with dups
1227 // which we'll later clear up
1228 $raparents = array();
1229 if ($rs->RecordCount()) {
1230 while ($ra = rs_fetch_next_record($rs)) {
1231 $sw['ra'][$ra->path] = $ra->roleid;
1232 if (!empty($ra->capability)) {
1233 $k = "{$ra->path}:{$ra->roleid}";
1234 $sw['rdef'][$k][$ra->capability] = $ra->permission;
1235 }
1236 $parentids = explode('/', $ra->path);
1237 array_pop($parentids); array_shift($parentids);
1238 if (isset($raparents[$ra->roleid])) {
1239 $raparents[$ra->roleid] = array_merge($raparents[$ra->roleid], $parentids);
1240 } else {
1241 $raparents[$ra->roleid] = $parentids;
1242 }
1243 }
1244 }
1245 rs_close($rs);
1246
1247 // Walk up the tree to grab all the roledefs
1248 // of interest to our user...
1249 // NOTE: we use a series of IN clauses here - which
1250 // might explode on huge sites with very convoluted nesting of
1251 // categories... - extremely unlikely that the number of categories
1252 // and roletypes is so large that we hit the limits of IN()
1253 $clauses = array();
1254 foreach ($raparents as $roleid=>$contexts) {
1255 $contexts = sql_intarray_to_in(array_unique($contexts));
1256 if ($contexts ==! '') {
1257 $clauses[] = "(roleid=$roleid AND contextid IN ($contexts))";
1258 }
1259 }
1260 $clauses = join(" OR ", $clauses);
1261 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1262 FROM {$CFG->prefix}role_capabilities rc
1263 JOIN {$CFG->prefix}context ctx
1264 ON rc.contextid=ctx.id
1265 WHERE $clauses
1266 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1267
1268 $rs = get_recordset_sql($sql);
1269
1270 if ($rs->RecordCount()) {
1271 while ($rd = rs_fetch_next_record($rs)) {
1272 $k = "{$rd->path}:{$rd->roleid}";
1273 $sw['rdef'][$k][$rd->capability] = $rd->permission;
1274 }
1275 }
1276 rs_close($rs);
1277
1278 //
1279 // Overrides for the role assignments IN SUBCONTEXTS
1280 // (though we still do _not_ go below the course level.
1281 //
1282 // NOTE that the JOIN w sctx is with 3-way triangulation to
1283 // catch overrides to the applicable role in any subcontext, based
1284 // on the path field of the parent.
1285 //
1286 $sql = "SELECT sctx.path, ra.roleid,
1287 ctx.path AS parentpath,
1288 rco.capability, rco.permission
1289 FROM {$CFG->prefix}role_assignments ra
1290 JOIN {$CFG->prefix}context ctx
1291 ON ra.contextid=ctx.id
1292 JOIN {$CFG->prefix}context sctx
1293 ON (sctx.path LIKE ctx.path||'/%')
1294 JOIN {$CFG->prefix}role_capabilities rco
1295 ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
1296 WHERE ra.userid = $userid
1297 AND sctx.contextlevel <= ".CONTEXT_COURSE."
1298 ORDER BY sctx.depth, sctx.path, $ra.roleid";
1299 if ($rs->RecordCount()) {
1300 while ($rd = rs_fetch_next_record($rs)) {
1301 $k = "{$rd->path}:{$rd->roleid}";
1302 $sw['rdef'][$k][$rd->capability] = $rd->permission;
1303 }
1304 }
1305 rs_close($rs);
1306
1307 // TODO: compact capsets?
1308
1309 return $sw;
1310}
1311
2f1a4248 1312
eef879ec 1313/**
c421ad4b 1314 * A convenience function to completely load all the capabilities
2f1a4248 1315 * for the current user. This is what gets called from login, for example.
1316 */
1317function load_all_capabilities() {
1318 global $USER;
1319
eef879ec 1320 //caching - helps user switching in cron
1321 static $defcaps = false;
bbbf2d40 1322
8e82745a 1323 unset($USER->mycourses); // Reset a cache used by get_my_courses
1324
eef879ec 1325 if (isguestuser()) {
2f1a4248 1326 load_guest_role(); // All non-guest users get this by default
eef879ec 1327
1328 } else if (isloggedin()) {
1329 if ($defcaps === false) {
1330 $defcaps = load_defaultuser_role(true);
1331 }
1332
3887fe4a 1333 load_user_capability();
1334
1335 // when in "course login as" - load only course caqpabilitites (it may not always work as expected)
1336 if (!empty($USER->realuser) and $USER->loginascontext->contextlevel != CONTEXT_SYSTEM) {
19bb8a05 1337 $children = array_keys(get_child_contexts($USER->loginascontext));
3887fe4a 1338 $children[] = $USER->loginascontext->id;
1339 foreach ($USER->capabilities as $conid => $caps) {
1340 if (!in_array($conid, $children)) {
1341 unset($USER->capabilities[$conid]);
c16ec802 1342 }
f6f66b03 1343 }
1344 }
eef879ec 1345
3887fe4a 1346 // handle role switching in courses
de5e137a 1347 if (!empty($USER->switchrole)) {
de5e137a 1348 foreach ($USER->switchrole as $contextid => $roleid) {
1349 $context = get_context_instance_by_id($contextid);
1350
1351 // first prune context and any child contexts
19bb8a05 1352 $children = array_keys(get_child_contexts($context));
de5e137a 1353 foreach ($children as $childid) {
1354 unset($USER->capabilities[$childid]);
1355 }
1356 unset($USER->capabilities[$contextid]);
1357
1358 // now merge all switched role caps in context and bellow
1359 $swithccaps = get_role_context_caps($roleid, $context);
1360 $USER->capabilities = merge_role_caps($USER->capabilities, $swithccaps);
1361 }
eef879ec 1362 }
1363
c0aa9f09 1364 if (isset($USER->capabilities)) {
1365 $USER->capabilities = merge_role_caps($USER->capabilities, $defcaps);
1366 } else {
1367 $USER->capabilities = $defcaps;
1368 }
de5e137a 1369
2f1a4248 1370 } else {
eef879ec 1371 load_notloggedin_role();
2f1a4248 1372 }
bbbf2d40 1373}
1374
2f1a4248 1375
efe12f6c 1376/**
64026e8c 1377 * Check all the login enrolment information for the given user object
eef868d1 1378 * by querying the enrolment plugins
64026e8c 1379 */
1380function check_enrolment_plugins(&$user) {
1381 global $CFG;
1382
e4ec4e41 1383 static $inprogress; // To prevent this function being called more than once in an invocation
1384
218eb651 1385 if (!empty($inprogress[$user->id])) {
e4ec4e41 1386 return;
1387 }
1388
218eb651 1389 $inprogress[$user->id] = true; // Set the flag
e4ec4e41 1390
64026e8c 1391 require_once($CFG->dirroot .'/enrol/enrol.class.php');
eef868d1 1392
64026e8c 1393 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
1394 $plugins = array($CFG->enrol);
1395 }
1396
1397 foreach ($plugins as $plugin) {
1398 $enrol = enrolment_factory::factory($plugin);
1399 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1400 $enrol->setup_enrolments($user);
1401 } else { /// Run legacy enrolment methods
1402 if (method_exists($enrol, 'get_student_courses')) {
1403 $enrol->get_student_courses($user);
1404 }
1405 if (method_exists($enrol, 'get_teacher_courses')) {
1406 $enrol->get_teacher_courses($user);
1407 }
1408
1409 /// deal with $user->students and $user->teachers stuff
1410 unset($user->student);
1411 unset($user->teacher);
1412 }
1413 unset($enrol);
1414 }
e4ec4e41 1415
218eb651 1416 unset($inprogress[$user->id]); // Unset the flag
64026e8c 1417}
1418
bbbf2d40 1419
1420/**
1421 * This is a recursive function that checks whether the capability in this
1422 * context, or the parent capabilities are set to prohibit.
1423 *
1424 * At this point, we can probably just use the values already set in the
1425 * session variable, since we are going down the level. Any prohit set in
1426 * parents would already reflect in the session.
1427 *
1428 * @param $capability - capability name
1429 * @param $sum - sum of all capabilities values
0468976c 1430 * @param $context - the context object
bbbf2d40 1431 * @param $array - when loading another user caps, their caps are not stored in session but an array
1432 */
0468976c 1433function capability_prohibits($capability, $context, $sum='', $array='') {
bbbf2d40 1434 global $USER;
0468976c 1435
0db6adc9 1436 // caching, mainly to save unnecessary sqls
1437 static $prohibits; //[capability][contextid]
1438 if (isset($prohibits[$capability][$context->id])) {
1439 return $prohibits[$capability][$context->id];
1440 }
c421ad4b 1441
2176adf1 1442 if (empty($context->id)) {
0db6adc9 1443 $prohibits[$capability][$context->id] = false;
2176adf1 1444 return false;
1445 }
1446
1447 if (empty($capability)) {
0db6adc9 1448 $prohibits[$capability][$context->id] = false;
2176adf1 1449 return false;
1450 }
1451
819e5a70 1452 if ($sum < (CAP_PROHIBIT/2)) {
bbbf2d40 1453 // If this capability is set to prohibit.
0db6adc9 1454 $prohibits[$capability][$context->id] = true;
bbbf2d40 1455 return true;
1456 }
eef868d1 1457
819e5a70 1458 if (!empty($array)) {
eef868d1 1459 if (isset($array[$context->id][$capability])
819e5a70 1460 && $array[$context->id][$capability] < (CAP_PROHIBIT/2)) {
0db6adc9 1461 $prohibits[$capability][$context->id] = true;
98882637 1462 return true;
eef868d1 1463 }
bbbf2d40 1464 } else {
98882637 1465 // Else if set in session.
eef868d1 1466 if (isset($USER->capabilities[$context->id][$capability])
819e5a70 1467 && $USER->capabilities[$context->id][$capability] < (CAP_PROHIBIT/2)) {
0db6adc9 1468 $prohibits[$capability][$context->id] = true;
98882637 1469 return true;
1470 }
bbbf2d40 1471 }
aad2ba95 1472 switch ($context->contextlevel) {
eef868d1 1473
bbbf2d40 1474 case CONTEXT_SYSTEM:
1475 // By now it's a definite an inherit.
1476 return 0;
1477 break;
1478
1479 case CONTEXT_PERSONAL:
2176adf1 1480 $parent = get_context_instance(CONTEXT_SYSTEM);
0db6adc9 1481 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1482 return $prohibits[$capability][$context->id];
bbbf2d40 1483 break;
1484
4b10f08b 1485 case CONTEXT_USER:
2176adf1 1486 $parent = get_context_instance(CONTEXT_SYSTEM);
0db6adc9 1487 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1488 return $prohibits[$capability][$context->id];
bbbf2d40 1489 break;
1490
1491 case CONTEXT_COURSECAT:
bbbf2d40 1492 case CONTEXT_COURSE:
3bf618ce 1493 $parents = get_parent_cats($context); // cached internally
1494 // no workaround for recursion now - it needs some more work and maybe fixing
1495
1496 if (empty($parents)) {
1497 // system context - this is either top category or frontpage course
40a2a15f 1498 $parent = get_context_instance(CONTEXT_SYSTEM);
1499 } else {
3bf618ce 1500 // parent context - recursion
1501 $parentid = array_pop($parents);
1502 $parent = get_context_instance_by_id($parentid);
40a2a15f 1503 }
0db6adc9 1504 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1505 return $prohibits[$capability][$context->id];
bbbf2d40 1506 break;
1507
1508 case CONTEXT_GROUP:
1509 // 1 to 1 to course.
5bf243d1 1510 if (!$courseid = get_field('groups', 'courseid', 'id', $context->instanceid)) {
0db6adc9 1511 $prohibits[$capability][$context->id] = false;
2176adf1 1512 return false;
1513 }
f3f7610c 1514 $parent = get_context_instance(CONTEXT_COURSE, $courseid);
0db6adc9 1515 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1516 return $prohibits[$capability][$context->id];
bbbf2d40 1517 break;
1518
1519 case CONTEXT_MODULE:
1520 // 1 to 1 to course.
2176adf1 1521 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
0db6adc9 1522 $prohibits[$capability][$context->id] = false;
2176adf1 1523 return false;
1524 }
bbbf2d40 1525 $parent = get_context_instance(CONTEXT_COURSE, $cm->course);
0db6adc9 1526 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1527 return $prohibits[$capability][$context->id];
bbbf2d40 1528 break;
1529
1530 case CONTEXT_BLOCK:
c331cf23 1531 // not necessarily 1 to 1 to course.
2176adf1 1532 if (!$block = get_record('block_instance','id',$context->instanceid)) {
0db6adc9 1533 $prohibits[$capability][$context->id] = false;
2176adf1 1534 return false;
1535 }
6ceebc1f 1536 if ($block->pagetype == 'course-view') {
1537 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
1538 } else {
c421ad4b 1539 $parent = get_context_instance(CONTEXT_SYSTEM);
1540 }
0db6adc9 1541 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1542 return $prohibits[$capability][$context->id];
bbbf2d40 1543 break;
1544
1545 default:
2176adf1 1546 print_error('unknowncontext');
1547 return false;
bbbf2d40 1548 }
1549}
1550
1551
1552/**
1553 * A print form function. This should either grab all the capabilities from
1554 * files or a central table for that particular module instance, then present
1555 * them in check boxes. Only relevant capabilities should print for known
1556 * context.
1557 * @param $mod - module id of the mod
1558 */
1559function print_capabilities($modid=0) {
1560 global $CFG;
eef868d1 1561
bbbf2d40 1562 $capabilities = array();
1563
1564 if ($modid) {
1565 // We are in a module specific context.
1566
1567 // Get the mod's name.
1568 // Call the function that grabs the file and parse.
1569 $cm = get_record('course_modules', 'id', $modid);
1570 $module = get_record('modules', 'id', $cm->module);
eef868d1 1571
bbbf2d40 1572 } else {
1573 // Print all capabilities.
1574 foreach ($capabilities as $capability) {
1575 // Prints the check box component.
1576 }
1577 }
1578}
1579
1580
1581/**
1afecc03 1582 * Installs the roles system.
1583 * This function runs on a fresh install as well as on an upgrade from the old
1584 * hard-coded student/teacher/admin etc. roles to the new roles system.
bbbf2d40 1585 */
1afecc03 1586function moodle_install_roles() {
bbbf2d40 1587
1afecc03 1588 global $CFG, $db;
eef868d1 1589
459c1ff1 1590/// Create a system wide context for assignemnt.
21c9bace 1591 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
bbbf2d40 1592
1afecc03 1593
459c1ff1 1594/// Create default/legacy roles and capabilities.
1595/// (1 legacy capability per legacy role at system level).
1596
69aaada0 1597 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1598 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1599 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1600 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1601 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1602 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1603 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1604 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1605 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1606 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1607 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1608 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
c785d40a 1609 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1610 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
c421ad4b 1611
17e5635c 1612/// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
459c1ff1 1613
98882637 1614 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
bbbf2d40 1615 error('Could not assign moodle/site:doanything to the admin role');
1616 }
250934b8 1617 if (!update_capabilities()) {
1618 error('Had trouble upgrading the core capabilities for the Roles System');
1619 }
1afecc03 1620
459c1ff1 1621/// Look inside user_admin, user_creator, user_teachers, user_students and
1622/// assign above new roles. If a user has both teacher and student role,
1623/// only teacher role is assigned. The assignment should be system level.
1624
1afecc03 1625 $dbtables = $db->MetaTables('TABLES');
eef868d1 1626
72da5046 1627/// Set up the progress bar
1628
1629 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1630
1631 $totalcount = $progresscount = 0;
1632 foreach ($usertables as $usertable) {
1633 if (in_array($CFG->prefix.$usertable, $dbtables)) {
1634 $totalcount += count_records($usertable);
1635 }
1636 }
1637
aae37b63 1638 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1639
459c1ff1 1640/// Upgrade the admins.
1641/// Sort using id ASC, first one is primary admin.
1642
1afecc03 1643 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
f1dcf000 1644 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
0f5dafff 1645 while ($admin = rs_fetch_next_record($rs)) {
1afecc03 1646 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
72da5046 1647 $progresscount++;
aae37b63 1648 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1649 }
0f5dafff 1650 rs_close($rs);
1afecc03 1651 }
1652 } else {
1653 // This is a fresh install.
bbbf2d40 1654 }
1afecc03 1655
1656
459c1ff1 1657/// Upgrade course creators.
1afecc03 1658 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
f1dcf000 1659 if ($rs = get_recordset('user_coursecreators')) {
0f5dafff 1660 while ($coursecreator = rs_fetch_next_record($rs)) {
56b4d70d 1661 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
72da5046 1662 $progresscount++;
aae37b63 1663 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1664 }
0f5dafff 1665 rs_close($rs);
1afecc03 1666 }
bbbf2d40 1667 }
1668
1afecc03 1669
459c1ff1 1670/// Upgrade editting teachers and non-editting teachers.
1afecc03 1671 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
f1dcf000 1672 if ($rs = get_recordset('user_teachers')) {
0f5dafff 1673 while ($teacher = rs_fetch_next_record($rs)) {
c421ad4b 1674
d5511451 1675 // removed code here to ignore site level assignments
1676 // since the contexts are separated now
c421ad4b 1677
17d6a25e 1678 // populate the user_lastaccess table
ece4945b 1679 $access = new object();
17d6a25e 1680 $access->timeaccess = $teacher->timeaccess;
1681 $access->userid = $teacher->userid;
1682 $access->courseid = $teacher->course;
1683 insert_record('user_lastaccess', $access);
f1dcf000 1684
17d6a25e 1685 // assign the default student role
1afecc03 1686 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
3fe54e51 1687 // hidden teacher
1688 if ($teacher->authority == 0) {
c421ad4b 1689 $hiddenteacher = 1;
3fe54e51 1690 } else {
c421ad4b 1691 $hiddenteacher = 0;
1692 }
1693
1afecc03 1694 if ($teacher->editall) { // editting teacher
3fe54e51 1695 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1afecc03 1696 } else {
3fe54e51 1697 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1afecc03 1698 }
72da5046 1699 $progresscount++;
aae37b63 1700 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1701 }
0f5dafff 1702 rs_close($rs);
bbbf2d40 1703 }
1704 }
1afecc03 1705
1706
459c1ff1 1707/// Upgrade students.
1afecc03 1708 if (in_array($CFG->prefix.'user_students', $dbtables)) {
f1dcf000 1709 if ($rs = get_recordset('user_students')) {
0f5dafff 1710 while ($student = rs_fetch_next_record($rs)) {
f1dcf000 1711
17d6a25e 1712 // populate the user_lastaccess table
f1dcf000 1713 $access = new object;
17d6a25e 1714 $access->timeaccess = $student->timeaccess;
1715 $access->userid = $student->userid;
1716 $access->courseid = $student->course;
1717 insert_record('user_lastaccess', $access);
f1dcf000 1718
17d6a25e 1719 // assign the default student role
1afecc03 1720 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
1721 role_assign($studentrole, $student->userid, 0, $coursecontext->id);
72da5046 1722 $progresscount++;
aae37b63 1723 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1724 }
0f5dafff 1725 rs_close($rs);
1afecc03 1726 }
bbbf2d40 1727 }
1afecc03 1728
1729
459c1ff1 1730/// Upgrade guest (only 1 entry).
1afecc03 1731 if ($guestuser = get_record('user', 'username', 'guest')) {
1732 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
1733 }
aae37b63 1734 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1735
459c1ff1 1736
1737/// Insert the correct records for legacy roles
945f88ca 1738 allow_assign($adminrole, $adminrole);
1739 allow_assign($adminrole, $coursecreatorrole);
1740 allow_assign($adminrole, $noneditteacherrole);
eef868d1 1741 allow_assign($adminrole, $editteacherrole);
945f88ca 1742 allow_assign($adminrole, $studentrole);
1743 allow_assign($adminrole, $guestrole);
eef868d1 1744
945f88ca 1745 allow_assign($coursecreatorrole, $noneditteacherrole);
1746 allow_assign($coursecreatorrole, $editteacherrole);
eef868d1 1747 allow_assign($coursecreatorrole, $studentrole);
945f88ca 1748 allow_assign($coursecreatorrole, $guestrole);
eef868d1 1749
1750 allow_assign($editteacherrole, $noneditteacherrole);
1751 allow_assign($editteacherrole, $studentrole);
945f88ca 1752 allow_assign($editteacherrole, $guestrole);
eef868d1 1753
459c1ff1 1754/// Set up default permissions for overrides
945f88ca 1755 allow_override($adminrole, $adminrole);
1756 allow_override($adminrole, $coursecreatorrole);
1757 allow_override($adminrole, $noneditteacherrole);
eef868d1 1758 allow_override($adminrole, $editteacherrole);
945f88ca 1759 allow_override($adminrole, $studentrole);
eef868d1 1760 allow_override($adminrole, $guestrole);
c785d40a 1761 allow_override($adminrole, $userrole);
1afecc03 1762
746a04c5 1763
459c1ff1 1764/// Delete the old user tables when we are done
1765
83ea392e 1766 drop_table(new XMLDBTable('user_students'));
1767 drop_table(new XMLDBTable('user_teachers'));
1768 drop_table(new XMLDBTable('user_coursecreators'));
1769 drop_table(new XMLDBTable('user_admins'));
459c1ff1 1770
bbbf2d40 1771}
1772
3562486b 1773/**
1774 * Returns array of all legacy roles.
1775 */
1776function get_legacy_roles() {
1777 return array(
a83addc5 1778 'admin' => 'moodle/legacy:admin',
3562486b 1779 'coursecreator' => 'moodle/legacy:coursecreator',
a83addc5 1780 'editingteacher' => 'moodle/legacy:editingteacher',
1781 'teacher' => 'moodle/legacy:teacher',
1782 'student' => 'moodle/legacy:student',
efe12f6c 1783 'guest' => 'moodle/legacy:guest',
1784 'user' => 'moodle/legacy:user'
3562486b 1785 );
1786}
1787
b357ed13 1788function get_legacy_type($roleid) {
1789 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1790 $legacyroles = get_legacy_roles();
1791
1792 $result = '';
1793 foreach($legacyroles as $ltype=>$lcap) {
1794 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
1795 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
1796 //choose first selected legacy capability - reset the rest
1797 if (empty($result)) {
1798 $result = $ltype;
1799 } else {
66a27728 1800 unassign_capability($lcap, $roleid);
c421ad4b 1801 }
b357ed13 1802 }
1803 }
1804
1805 return $result;
1806}
1807
bbbf2d40 1808/**
1809 * Assign the defaults found in this capabality definition to roles that have
1810 * the corresponding legacy capabilities assigned to them.
1811 * @param $legacyperms - an array in the format (example):
1812 * 'guest' => CAP_PREVENT,
1813 * 'student' => CAP_ALLOW,
1814 * 'teacher' => CAP_ALLOW,
1815 * 'editingteacher' => CAP_ALLOW,
1816 * 'coursecreator' => CAP_ALLOW,
1817 * 'admin' => CAP_ALLOW
1818 * @return boolean - success or failure.
1819 */
1820function assign_legacy_capabilities($capability, $legacyperms) {
eef868d1 1821
3562486b 1822 $legacyroles = get_legacy_roles();
1823
bbbf2d40 1824 foreach ($legacyperms as $type => $perm) {
eef868d1 1825
21c9bace 1826 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
eef868d1 1827
3562486b 1828 if (!array_key_exists($type, $legacyroles)) {
1829 error('Incorrect legacy role definition for type: '.$type);
1830 }
eef868d1 1831
3562486b 1832 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW)) {
2e85fffe 1833 foreach ($roles as $role) {
1834 // Assign a site level capability.
1835 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1836 return false;
1837 }
bbbf2d40 1838 }
1839 }
1840 }
1841 return true;
1842}
1843
1844
cee0901c 1845/**
1846 * Checks to see if a capability is a legacy capability.
1847 * @param $capabilityname
1848 * @return boolean
1849 */
bbbf2d40 1850function islegacy($capabilityname) {
d67de0ca 1851 if (strpos($capabilityname, 'moodle/legacy') === 0) {
eef868d1 1852 return true;
d67de0ca 1853 } else {
1854 return false;
98882637 1855 }
bbbf2d40 1856}
1857
cee0901c 1858
1859
1860/**********************************
bbbf2d40 1861 * Context Manipulation functions *
1862 **********************************/
1863
bbbf2d40 1864/**
9991d157 1865 * Create a new context record for use by all roles-related stuff
bbbf2d40 1866 * @param $level
1867 * @param $instanceid
3ca2dea5 1868 *
1869 * @return object newly created context (or existing one with a debug warning)
bbbf2d40 1870 */
aad2ba95 1871function create_context($contextlevel, $instanceid) {
3ca2dea5 1872 if (!$context = get_record('context','contextlevel',$contextlevel,'instanceid',$instanceid)) {
1873 if (!validate_context($contextlevel, $instanceid)) {
1874 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1875 return NULL;
1876 }
8ba412da 1877 if ($contextlevel == CONTEXT_SYSTEM) {
1878 return create_system_context();
c421ad4b 1879
8ba412da 1880 }
3ca2dea5 1881 $context = new object();
aad2ba95 1882 $context->contextlevel = $contextlevel;
bbbf2d40 1883 $context->instanceid = $instanceid;
3ca2dea5 1884 if ($id = insert_record('context',$context)) {
c421ad4b 1885 $c = get_record('context','id',$id);
0db6adc9 1886 return $c;
3ca2dea5 1887 } else {
1888 debugging('Error: could not insert new context level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1889 return NULL;
1890 }
1891 } else {
1892 debugging('Warning: Context id "'.s($context->id).'" not created, because it already exists.');
1893 return $context;
bbbf2d40 1894 }
1895}
1896
efe12f6c 1897/**
8ba412da 1898 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
1899 */
1900function create_system_context() {
1901 if ($context = get_record('context', 'contextlevel', CONTEXT_SYSTEM, 'instanceid', SITEID)) {
1902 // we are going to change instanceid of system context to 0 now
1903 $context->instanceid = 0;
1904 update_record('context', $context);
1905 //context rel not affected
1906 return $context;
1907
1908 } else {
1909 $context = new object();
1910 $context->contextlevel = CONTEXT_SYSTEM;
1911 $context->instanceid = 0;
1912 if ($context->id = insert_record('context',$context)) {
1913 // we need not to populate context_rel for system context
1914 return $context;
1915 } else {
1916 debugging('Can not create system context');
1917 return NULL;
1918 }
1919 }
1920}
9991d157 1921/**
17b0efae 1922 * Remove a context record and any dependent entries
9991d157 1923 * @param $level
1924 * @param $instanceid
3ca2dea5 1925 *
17b0efae 1926 * @return bool properly deleted
9991d157 1927 */
1928function delete_context($contextlevel, $instanceid) {
c421ad4b 1929 if ($context = get_context_instance($contextlevel, $instanceid)) {
0db6adc9 1930 delete_records('context_rel', 'c2', $context->id); // might not be a parent
9991d157 1931 return delete_records('context', 'id', $context->id) &&
1932 delete_records('role_assignments', 'contextid', $context->id) &&
c421ad4b 1933 delete_records('role_capabilities', 'contextid', $context->id) &&
0db6adc9 1934 delete_records('context_rel', 'c1', $context->id);
9991d157 1935 }
1936 return true;
1937}
1938
17b0efae 1939/**
1940 * Remove stale context records
1941 *
1942 * @return bool
1943 */
1944function cleanup_contexts() {
1945 global $CFG;
1946
1947 $sql = " SELECT " . CONTEXT_COURSECAT . " AS level,
1948 c.instanceid AS instanceid
1949 FROM {$CFG->prefix}context c
1950 LEFT OUTER JOIN {$CFG->prefix}course_categories AS t
1951 ON c.instanceid = t.id
1952 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSECAT . "
1953 UNION
1954 SELECT " . CONTEXT_COURSE . " AS level,
1955 c.instanceid AS instanceid
1956 FROM {$CFG->prefix}context c
1957 LEFT OUTER JOIN {$CFG->prefix}course AS t
1958 ON c.instanceid = t.id
1959 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSE . "
1960 UNION
1961 SELECT " . CONTEXT_MODULE . " AS level,
1962 c.instanceid AS instanceid
1963 FROM {$CFG->prefix}context c
1964 LEFT OUTER JOIN {$CFG->prefix}course_modules AS t
1965 ON c.instanceid = t.id
1966 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_MODULE . "
1967 UNION
1968 SELECT " . CONTEXT_USER . " AS level,
1969 c.instanceid AS instanceid
1970 FROM {$CFG->prefix}context c
1971 LEFT OUTER JOIN {$CFG->prefix}user AS t
1972 ON c.instanceid = t.id
1973 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_USER . "
1974 UNION
1975 SELECT " . CONTEXT_BLOCK . " AS level,
1976 c.instanceid AS instanceid
1977 FROM {$CFG->prefix}context c
1978 LEFT OUTER JOIN {$CFG->prefix}block_instance AS t
1979 ON c.instanceid = t.id
1980 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_BLOCK . "
1981 UNION
1982 SELECT " . CONTEXT_GROUP . " AS level,
1983 c.instanceid AS instanceid
1984 FROM {$CFG->prefix}context c
1985 LEFT OUTER JOIN {$CFG->prefix}groups AS t
1986 ON c.instanceid = t.id
1987 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_GROUP . "
1988 ";
1989 $rs = get_recordset_sql($sql);
1990 if ($rs->RecordCount()) {
1991 begin_sql();
1992 $tx = true;
1993 while ($tx && $ctx = rs_fetch_next_record($rs)) {
1994 $tx = $tx && delete_context($ctx->level, $ctx->instanceid);
1995 }
1996 rs_close($rs);
1997 if ($tx) {
1998 commit_sql();
1999 return true;
2000 }
2001 rollback_sql();
2002 return false;
2003 }
2004 return true;
2005}
2006
3ca2dea5 2007/**
2008 * Validate that object with instanceid really exists in given context level.
2009 *
2010 * return if instanceid object exists
2011 */
2012function validate_context($contextlevel, $instanceid) {
2013 switch ($contextlevel) {
2014
2015 case CONTEXT_SYSTEM:
8ba412da 2016 return ($instanceid == 0);
3ca2dea5 2017
2018 case CONTEXT_PERSONAL:
2019 return (boolean)count_records('user', 'id', $instanceid);
2020
2021 case CONTEXT_USER:
2022 return (boolean)count_records('user', 'id', $instanceid);
2023
2024 case CONTEXT_COURSECAT:
1cd3eba9 2025 if ($instanceid == 0) {
2026 return true; // site course category
2027 }
3ca2dea5 2028 return (boolean)count_records('course_categories', 'id', $instanceid);
2029
2030 case CONTEXT_COURSE:
2031 return (boolean)count_records('course', 'id', $instanceid);
2032
2033 case CONTEXT_GROUP:
f3f7610c 2034 return groups_group_exists($instanceid);
3ca2dea5 2035
2036 case CONTEXT_MODULE:
2037 return (boolean)count_records('course_modules', 'id', $instanceid);
2038
2039 case CONTEXT_BLOCK:
2040 return (boolean)count_records('block_instance', 'id', $instanceid);
2041
2042 default:
2043 return false;
2044 }
2045}
bbbf2d40 2046
2047/**
2048 * Get the context instance as an object. This function will create the
2049 * context instance if it does not exist yet.
e765b5d3 2050 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2051 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
2052 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
2053 * @return object The context object.
bbbf2d40 2054 */
8ba412da 2055function get_context_instance($contextlevel=NULL, $instance=0) {
e5605780 2056
51195e6f 2057 global $context_cache, $context_cache_id, $CONTEXT;
a36a3a3f 2058 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_PERSONAL, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_GROUP, CONTEXT_MODULE, CONTEXT_BLOCK);
d9a35e12 2059
8ba412da 2060 // Yu: Separating site and site course context - removed CONTEXT_COURSE override when SITEID
c421ad4b 2061
9251b26f 2062 // fix for MDL-9016
2063 if ($contextlevel == 'clearcache') {
2064 // Clear ALL cache
2065 $context_cache = array();
2066 $context_cache_id = array();
c421ad4b 2067 $CONTEXT = '';
9251b26f 2068 return false;
2069 }
b7cec865 2070
340ea4e8 2071/// If no level is supplied then return the current global context if there is one
aad2ba95 2072 if (empty($contextlevel)) {
340ea4e8 2073 if (empty($CONTEXT)) {
a36a3a3f 2074 //fatal error, code must be fixed
2075 error("Error: get_context_instance() called without a context");
340ea4e8 2076 } else {
2077 return $CONTEXT;
2078 }
e5605780 2079 }
2080
8ba412da 2081/// Backwards compatibility with obsoleted (CONTEXT_SYSTEM, SITEID)
2082 if ($contextlevel == CONTEXT_SYSTEM) {
2083 $instance = 0;
2084 }
2085
a36a3a3f 2086/// check allowed context levels
2087 if (!in_array($contextlevel, $allowed_contexts)) {
7bfa3101 2088 // fatal error, code must be fixed - probably typo or switched parameters
a36a3a3f 2089 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
2090 }
2091
340ea4e8 2092/// Check the cache
aad2ba95 2093 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2094 return $context_cache[$contextlevel][$instance];
e5605780 2095 }
2096
340ea4e8 2097/// Get it from the database, or create it
aad2ba95 2098 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
2099 create_context($contextlevel, $instance);
2100 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
e5605780 2101 }
2102
ccfc5ecc 2103/// Only add to cache if context isn't empty.
2104 if (!empty($context)) {
aad2ba95 2105 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
ccfc5ecc 2106 $context_cache_id[$context->id] = $context; // Cache it for later
2107 }
0468976c 2108
bbbf2d40 2109 return $context;
2110}
2111
cee0901c 2112
340ea4e8 2113/**
e765b5d3 2114 * Get a context instance as an object, from a given context id.
2115 * @param $id a context id.
2116 * @return object The context object.
340ea4e8 2117 */
2118function get_context_instance_by_id($id) {
2119
d9a35e12 2120 global $context_cache, $context_cache_id;
2121
340ea4e8 2122 if (isset($context_cache_id[$id])) { // Already cached
75e84883 2123 return $context_cache_id[$id];
340ea4e8 2124 }
2125
2126 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
aad2ba95 2127 $context_cache[$context->contextlevel][$context->instanceid] = $context;
340ea4e8 2128 $context_cache_id[$context->id] = $context;
2129 return $context;
2130 }
2131
2132 return false;
2133}
2134
bbbf2d40 2135
8737be58 2136/**
2137 * Get the local override (if any) for a given capability in a role in a context
2138 * @param $roleid
0468976c 2139 * @param $contextid
2140 * @param $capability
8737be58 2141 */
2142function get_local_override($roleid, $contextid, $capability) {
2143 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
2144}
2145
2146
bbbf2d40 2147
2148/************************************
2149 * DB TABLE RELATED FUNCTIONS *
2150 ************************************/
2151
cee0901c 2152/**
bbbf2d40 2153 * function that creates a role
2154 * @param name - role name
31f26796 2155 * @param shortname - role short name
bbbf2d40 2156 * @param description - role description
2157 * @param legacy - optional legacy capability
2158 * @return id or false
2159 */
8420bee9 2160function create_role($name, $shortname, $description, $legacy='') {
eef868d1 2161
98882637 2162 // check for duplicate role name
eef868d1 2163
98882637 2164 if ($role = get_record('role','name', $name)) {
eef868d1 2165 error('there is already a role with this name!');
98882637 2166 }
eef868d1 2167
31f26796 2168 if ($role = get_record('role','shortname', $shortname)) {
eef868d1 2169 error('there is already a role with this shortname!');
31f26796 2170 }
2171
b5959f30 2172 $role = new object();
98882637 2173 $role->name = $name;
31f26796 2174 $role->shortname = $shortname;
98882637 2175 $role->description = $description;
eef868d1 2176
8420bee9 2177 //find free sortorder number
2178 $role->sortorder = count_records('role');
2179 while (get_record('role','sortorder', $role->sortorder)) {
2180 $role->sortorder += 1;
b5959f30 2181 }
2182
21c9bace 2183 if (!$context = get_context_instance(CONTEXT_SYSTEM)) {
2184 return false;
2185 }
eef868d1 2186
98882637 2187 if ($id = insert_record('role', $role)) {
eef868d1 2188 if ($legacy) {
2189 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
98882637 2190 }
eef868d1 2191
ec7a8b79 2192 /// By default, users with role:manage at site level
2193 /// should be able to assign users to this new role, and override this new role's capabilities
eef868d1 2194
ec7a8b79 2195 // find all admin roles
e46c0987 2196 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
2197 // foreach admin role
2198 foreach ($adminroles as $arole) {
2199 // write allow_assign and allow_overrid
2200 allow_assign($arole->id, $id);
eef868d1 2201 allow_override($arole->id, $id);
e46c0987 2202 }
ec7a8b79 2203 }
eef868d1 2204
98882637 2205 return $id;
2206 } else {
eef868d1 2207 return false;
98882637 2208 }
eef868d1 2209
bbbf2d40 2210}
2211
8420bee9 2212/**
2213 * function that deletes a role and cleanups up after it
2214 * @param roleid - id of role to delete
2215 * @return success
2216 */
2217function delete_role($roleid) {
c345bb58 2218 global $CFG;
8420bee9 2219 $success = true;
2220
60ace1e1 2221// mdl 10149, check if this is the last active admin role
2222// if we make the admin role not deletable then this part can go
c421ad4b 2223
60ace1e1 2224 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
c421ad4b 2225
60ace1e1 2226 if ($role = get_record('role', 'id', $roleid)) {
2227 if (record_exists('role_capabilities', 'contextid', $systemcontext->id, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
2228 // deleting an admin role
2229 $status = false;
2230 if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext)) {
2231 foreach ($adminroles as $adminrole) {
2232 if ($adminrole->id != $roleid) {
2233 // some other admin role
2234 if (record_exists('role_assignments', 'roleid', $adminrole->id, 'contextid', $systemcontext->id)) {
c421ad4b 2235 // found another admin role with at least 1 user assigned
60ace1e1 2236 $status = true;
2237 break;
2238 }
2239 }
c421ad4b 2240 }
2241 }
60ace1e1 2242 if ($status !== true) {
c421ad4b 2243 error ('You can not delete this role because there is no other admin roles with users assigned');
60ace1e1 2244 }
c421ad4b 2245 }
60ace1e1 2246 }
2247
8420bee9 2248// first unssign all users
2249 if (!role_unassign($roleid)) {
2250 debugging("Error while unassigning all users from role with ID $roleid!");
2251 $success = false;
2252 }
2253
2254// cleanup all references to this role, ignore errors
2255 if ($success) {
c421ad4b 2256
c345bb58 2257 // MDL-10679 find all contexts where this role has an override
c421ad4b 2258 $contexts = get_records_sql("SELECT contextid, contextid
c345bb58 2259 FROM {$CFG->prefix}role_capabilities
2260 WHERE roleid = $roleid");
c421ad4b 2261
8420bee9 2262 delete_records('role_capabilities', 'roleid', $roleid);
c421ad4b 2263
c345bb58 2264 // MDL-10679, delete from context_rel if this role holds the last override in these contexts
2265 if ($contexts) {
2266 foreach ($contexts as $context) {
2267 if (!record_exists('role_capabilities', 'contextid', $context->contextid)) {
c421ad4b 2268 delete_records('context_rel', 'c1', $context->contextid);
2269 }
c345bb58 2270 }
2271 }
2272
8420bee9 2273 delete_records('role_allow_assign', 'roleid', $roleid);
2274 delete_records('role_allow_assign', 'allowassign', $roleid);
2275 delete_records('role_allow_override', 'roleid', $roleid);
2276 delete_records('role_allow_override', 'allowoverride', $roleid);
c421ad4b 2277 delete_records('role_names', 'roleid', $roleid);
8420bee9 2278 }
2279
2280// finally delete the role itself
2281 if ($success and !delete_records('role', 'id', $roleid)) {
ece4945b 2282 debugging("Could not delete role record with ID $roleid!");
8420bee9 2283 $success = false;
2284 }
2285
2286 return $success;
2287}
2288
bbbf2d40 2289/**
2290 * Function to write context specific overrides, or default capabilities.
2291 * @param module - string name
2292 * @param capability - string name
2293 * @param contextid - context id
2294 * @param roleid - role id
2295 * @param permission - int 1,-1 or -1000
96986241 2296 * should not be writing if permission is 0
bbbf2d40 2297 */
e7876c1e 2298function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
eef868d1 2299
98882637 2300 global $USER;
eef868d1 2301
96986241 2302 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
eef868d1 2303 unassign_capability($capability, $roleid, $contextid);
96986241 2304 return true;
98882637 2305 }
eef868d1 2306
2e85fffe 2307 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
e7876c1e 2308
2309 if ($existing and !$overwrite) { // We want to keep whatever is there already
2310 return true;
2311 }
2312
bbbf2d40 2313 $cap = new object;
2314 $cap->contextid = $contextid;
2315 $cap->roleid = $roleid;
2316 $cap->capability = $capability;
2317 $cap->permission = $permission;
2318 $cap->timemodified = time();
9db12da7 2319 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
e7876c1e 2320
2321 if ($existing) {
2322 $cap->id = $existing->id;
2323 return update_record('role_capabilities', $cap);
2324 } else {
c345bb58 2325 $c = get_record('context', 'id', $contextid);
2326 /// MDL-10679 insert context rel here
2327 insert_context_rel ($c);
e7876c1e 2328 return insert_record('role_capabilities', $cap);
2329 }
bbbf2d40 2330}
2331
2332
2333/**
2334 * Unassign a capability from a role.
2335 * @param $roleid - the role id
2336 * @param $capability - the name of the capability
2337 * @return boolean - success or failure
2338 */
2339function unassign_capability($capability, $roleid, $contextid=NULL) {
eef868d1 2340
98882637 2341 if (isset($contextid)) {
c345bb58 2342 // delete from context rel, if this is the last override in this context
98882637 2343 $status = delete_records('role_capabilities', 'capability', $capability,
2344 'roleid', $roleid, 'contextid', $contextid);
c421ad4b 2345
c345bb58 2346 // MDL-10679, if this is no more overrides for this context
2347 // delete entries from context where this context is a child
2348 if (!record_exists('role_capabilities', 'contextid', $contextid)) {
c421ad4b 2349 delete_records('context_rel', 'c1', $contextid);
2350 }
2351
98882637 2352 } else {
c345bb58 2353 // There is no need to delete from context_rel here because
2354 // this is only used for legacy, for now
98882637 2355 $status = delete_records('role_capabilities', 'capability', $capability,
2356 'roleid', $roleid);
2357 }
2358 return $status;
bbbf2d40 2359}
2360
2361
2362/**
759ac72d 2363 * Get the roles that have a given capability assigned to it. This function
2364 * does not resolve the actual permission of the capability. It just checks
2365 * for assignment only.
bbbf2d40 2366 * @param $capability - capability name (string)
2367 * @param $permission - optional, the permission defined for this capability
2368 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2369 * @return array or role objects
2370 */
ec7a8b79 2371function get_roles_with_capability($capability, $permission=NULL, $context='') {
2372
bbbf2d40 2373 global $CFG;
eef868d1 2374
ec7a8b79 2375 if ($context) {
2376 if ($contexts = get_parent_contexts($context)) {
2377 $listofcontexts = '('.implode(',', $contexts).')';
2378 } else {
21c9bace 2379 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
eef868d1 2380 $listofcontexts = '('.$sitecontext->id.')'; // must be site
2381 }
42ac3ecf 2382 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
ec7a8b79 2383 } else {
2384 $contextstr = '';
2385 }
eef868d1 2386
2387 $selectroles = "SELECT r.*
42ac3ecf 2388 FROM {$CFG->prefix}role r,
2389 {$CFG->prefix}role_capabilities rc
bbbf2d40 2390 WHERE rc.capability = '$capability'
ec7a8b79 2391 AND rc.roleid = r.id $contextstr";
bbbf2d40 2392
2393 if (isset($permission)) {
2394 $selectroles .= " AND rc.permission = '$permission'";
2395 }
2396 return get_records_sql($selectroles);
2397}
2398
2399
2400/**
a9e1c058 2401 * This function makes a role-assignment (a role for a user or group in a particular context)
bbbf2d40 2402 * @param $roleid - the role of the id
2403 * @param $userid - userid
2404 * @param $groupid - group id
2405 * @param $contextid - id of the context
2406 * @param $timestart - time this assignment becomes effective
2407 * @param $timeend - time this assignemnt ceases to be effective
2408 * @uses $USER
2409 * @return id - new id of the assigment
2410 */
69b0088c 2411function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
aa311411 2412 global $USER, $CFG;
bbbf2d40 2413
7eb0b60a 2414 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER);
bbbf2d40 2415
a9e1c058 2416/// Do some data validation
2417
bbbf2d40 2418 if (empty($roleid)) {
9d829c68 2419 debugging('Role ID not provided');
a9e1c058 2420 return false;
bbbf2d40 2421 }
2422
2423 if (empty($userid) && empty($groupid)) {
9d829c68 2424 debugging('Either userid or groupid must be provided');
a9e1c058 2425 return false;
bbbf2d40 2426 }
eef868d1 2427
7700027f 2428 if ($userid && !record_exists('user', 'id', $userid)) {
82396e5b 2429 debugging('User ID '.intval($userid).' does not exist!');
7700027f 2430 return false;
2431 }
bbbf2d40 2432
f3f7610c 2433 if ($groupid && !groups_group_exists($groupid)) {
82396e5b 2434 debugging('Group ID '.intval($groupid).' does not exist!');
dc411d1b 2435 return false;
2436 }
2437
7700027f 2438 if (!$context = get_context_instance_by_id($contextid)) {
82396e5b 2439 debugging('Context ID '.intval($contextid).' does not exist!');
a9e1c058 2440 return false;
bbbf2d40 2441 }
2442
a9e1c058 2443 if (($timestart and $timeend) and ($timestart > $timeend)) {
9d829c68 2444 debugging('The end time can not be earlier than the start time');
a9e1c058 2445 return false;
2446 }
2447
69b0088c 2448 if (!$timemodified) {
c421ad4b 2449 $timemodified = time();
69b0088c 2450 }
7700027f 2451
a9e1c058 2452/// Check for existing entry
2453 if ($userid) {
7700027f 2454 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
a9e1c058 2455 } else {
7700027f 2456 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
a9e1c058 2457 }
2458
9ebcb4d2 2459
a9e1c058 2460 $newra = new object;
bbbf2d40 2461
a9e1c058 2462 if (empty($ra)) { // Create a new entry
2463 $newra->roleid = $roleid;
7700027f 2464 $newra->contextid = $context->id;
a9e1c058 2465 $newra->userid = $userid;
a9e1c058 2466 $newra->hidden = $hidden;
f44152f4 2467 $newra->enrol = $enrol;
c421ad4b 2468 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
0616d3e8 2469 /// by repeating queries with the same exact parameters in a 100 secs time window
2470 $newra->timestart = round($timestart, -2);
a9e1c058 2471 $newra->timeend = $timeend;
69b0088c 2472 $newra->timemodified = $timemodified;
115faa2f 2473 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
a9e1c058 2474
9ebcb4d2 2475 $success = insert_record('role_assignments', $newra);
a9e1c058 2476
2477 } else { // We already have one, just update it
2478
2479 $newra->id = $ra->id;
2480 $newra->hidden = $hidden;
f44152f4 2481 $newra->enrol = $enrol;
c421ad4b 2482 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
0616d3e8 2483 /// by repeating queries with the same exact parameters in a 100 secs time window
2484 $newra->timestart = round($timestart, -2);
a9e1c058 2485 $newra->timeend = $timeend;
69b0088c 2486 $newra->timemodified = $timemodified;
115faa2f 2487 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
a9e1c058 2488
9ebcb4d2 2489 $success = update_record('role_assignments', $newra);
2490 }
2491
7700027f 2492 if ($success) { /// Role was assigned, so do some other things
2493
2494 /// If the user is the current user, then reload the capabilities too.
2495 if (!empty($USER->id) && $USER->id == $userid) {
2f1a4248 2496 load_all_capabilities();
7700027f 2497 }
c421ad4b 2498
0f161e1f 2499 /// Ask all the modules if anything needs to be done for this user
2500 if ($mods = get_list_of_plugins('mod')) {
2501 foreach ($mods as $mod) {
2502 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2503 $functionname = $mod.'_role_assign';
2504 if (function_exists($functionname)) {
a7bb9b8f 2505 $functionname($userid, $context, $roleid);
0f161e1f 2506 }
2507 }
2508 }
2509
2510 /// Make sure they have an entry in user_lastaccess for courses they can access
2511 // role_add_lastaccess_entries($userid, $context);
a9e1c058 2512 }
eef868d1 2513
4e5f3064 2514 /// now handle metacourse role assignments if in course context
aad2ba95 2515 if ($success and $context->contextlevel == CONTEXT_COURSE) {
4e5f3064 2516 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2517 foreach ($parents as $parent) {
1aad4310 2518 sync_metacourse($parent->parent_course);
4e5f3064 2519 }
2520 }
2521 }
6eb4f823 2522
2523 return $success;
bbbf2d40 2524}
2525
2526
2527/**
1dc1f037 2528 * Deletes one or more role assignments. You must specify at least one parameter.
bbbf2d40 2529 * @param $roleid
2530 * @param $userid
2531 * @param $groupid
2532 * @param $contextid
6bc1e5d5 2533 * @param $enrol unassign only if enrolment type matches, NULL means anything
bbbf2d40 2534 * @return boolean - success or failure
2535 */
6bc1e5d5 2536function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
d74067e8 2537
2538 global $USER, $CFG;
eef868d1 2539
4e5f3064 2540 $success = true;
d74067e8 2541
1dc1f037 2542 $args = array('roleid', 'userid', 'groupid', 'contextid');
2543 $select = array();
2544 foreach ($args as $arg) {
2545 if ($$arg) {
2546 $select[] = $arg.' = '.$$arg;
2547 }
2548 }
6bc1e5d5 2549 if (!empty($enrol)) {
2550 $select[] = "enrol='$enrol'";
2551 }
d74067e8 2552
1dc1f037 2553 if ($select) {
4e5f3064 2554 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2555 $mods = get_list_of_plugins('mod');
2556 foreach($ras as $ra) {
86e2c51d 2557 /// infinite loop protection when deleting recursively
2558 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
2559 continue;
2560 }
4e5f3064 2561 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
86e2c51d 2562
4e5f3064 2563 /// If the user is the current user, then reload the capabilities too.
2564 if (!empty($USER->id) && $USER->id == $ra->userid) {
2f1a4248 2565 load_all_capabilities();
4e5f3064 2566 }
2567 $context = get_record('context', 'id', $ra->contextid);
0f161e1f 2568
2569 /// Ask all the modules if anything needs to be done for this user
4e5f3064 2570 foreach ($mods as $mod) {
2571 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2572 $functionname = $mod.'_role_unassign';
2573 if (function_exists($functionname)) {
2574 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
2575 }
2576 }
2577
2578 /// now handle metacourse role unassigment and removing from goups if in course context
aad2ba95 2579 if (!empty($context) and $context->contextlevel == CONTEXT_COURSE) {
2515adf9 2580
c421ad4b 2581 // cleanup leftover course groups/subscriptions etc when user has
2515adf9 2582 // no capability to view course
35274646 2583 // this may be slow, but this is the proper way of doing it
2584 if (!has_capability('moodle/course:view', $context, $ra->userid)) {
2515adf9 2585 // remove from groups
2c386f82 2586 if ($groups = groups_get_all_groups($context->instanceid)) {
4e5f3064 2587 foreach ($groups as $group) {
2588 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
2589 }
2590 }
2515adf9 2591
2515adf9 2592 // delete lastaccess records
2593 delete_records('user_lastaccess', 'userid', $ra->userid, 'courseid', $context->instanceid);
4e5f3064 2594 }
2515adf9 2595
1aad4310 2596 //unassign roles in metacourses if needed
4e5f3064 2597 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2598 foreach ($parents as $parent) {
1aad4310 2599 sync_metacourse($parent->parent_course);
0f161e1f 2600 }
2601 }
0f161e1f 2602 }
2603 }
d74067e8 2604 }
1dc1f037 2605 }
4e5f3064 2606
2607 return $success;
bbbf2d40 2608}
2609
efe12f6c 2610/**
eef868d1 2611 * A convenience function to take care of the common case where you
b963384f 2612 * just want to enrol someone using the default role into a course
2613 *
2614 * @param object $course
2615 * @param object $user
2616 * @param string $enrol - the plugin used to do this enrolment
2617 */
2618function enrol_into_course($course, $user, $enrol) {
2619
9492291c 2620 $timestart = time();
898d7119 2621 // remove time part from the timestamp and keep only the date part
2622 $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
b963384f 2623 if ($course->enrolperiod) {
898d7119 2624 $timeend = $timestart + $course->enrolperiod;
b963384f 2625 } else {
9492291c 2626 $timeend = 0;
b963384f 2627 }
2628
2629 if ($role = get_default_course_role($course)) {
c4381ef5 2630
2631 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2632
e2183037 2633 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
b963384f 2634 return false;
2635 }
eef868d1 2636
b963384f 2637 email_welcome_message_to_user($course, $user);
eef868d1 2638
b963384f 2639 add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
2640
2641 return true;
2642 }
2643
2644 return false;
2645}
2646
0f161e1f 2647/**
2648 * Add last access times to user_lastaccess as required
2649 * @param $userid
2650 * @param $context
2651 * @return boolean - success or failure
2652 */
2653function role_add_lastaccess_entries($userid, $context) {
2654
2655 global $USER, $CFG;
2656
aad2ba95 2657 if (empty($context->contextlevel)) {
0f161e1f 2658 return false;
2659 }
2660
2661 $lastaccess = new object; // Reusable object below
2662 $lastaccess->userid = $userid;
2663 $lastaccess->timeaccess = 0;
2664
aad2ba95 2665 switch ($context->contextlevel) {
0f161e1f 2666
2667 case CONTEXT_SYSTEM: // For the whole site
2668 if ($courses = get_record('course')) {
2669 foreach ($courses as $course) {
2670 $lastaccess->courseid = $course->id;
2671 role_set_lastaccess($lastaccess);
2672 }
2673 }
2674 break;
2675
2676 case CONTEXT_CATEGORY: // For a whole category
2677 if ($courses = get_record('course', 'category', $context->instanceid)) {
2678 foreach ($courses as $course) {
2679 $lastaccess->courseid = $course->id;
2680 role_set_lastaccess($lastaccess);
2681 }
2682 }
2683 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
2684 foreach ($categories as $category) {
2685 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
2686 role_add_lastaccess_entries($userid, $subcontext);
2687 }
2688 }
2689 break;
eef868d1 2690
0f161e1f 2691
2692 case CONTEXT_COURSE: // For a whole course
2693 if ($course = get_record('course', 'id', $context->instanceid)) {
2694 $lastaccess->courseid = $course->id;
2695 role_set_lastaccess($lastaccess);
2696 }
2697 break;
2698 }
2699}
2700
2701/**
2702 * Delete last access times from user_lastaccess as required
2703 * @param $userid
2704 * @param $context
2705 * @return boolean - success or failure
2706 */
2707function role_remove_lastaccess_entries($userid, $context) {
2708
2709 global $USER, $CFG;
2710
2711}
2712
bbbf2d40 2713
2714/**
2715 * Loads the capability definitions for the component (from file). If no
2716 * capabilities are defined for the component, we simply return an empty array.
2717 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2718 * @return array of capabilities
2719 */
2720function load_capability_def($component) {
2721 global $CFG;
2722
2723 if ($component == 'moodle') {
2724 $defpath = $CFG->libdir.'/db/access.php';
2725 $varprefix = 'moodle';
2726 } else {
0c4d9f49 2727 $compparts = explode('/', $component);
eef868d1 2728
0c4d9f49 2729 if ($compparts[0] == 'block') {
2730 // Blocks are an exception. Blocks directory is 'blocks', and not
2731 // 'block'. So we need to jump through hoops.
2732 $defpath = $CFG->dirroot.'/'.$compparts[0].
2733 's/'.$compparts[1].'/db/access.php';
2734 $varprefix = $compparts[0].'_'.$compparts[1];
89bd8357 2735
ae628043 2736 } else if ($compparts[0] == 'format') {
ce34ed3a 2737 // Similar to the above, course formats are 'format' while they
ae628043 2738 // are stored in 'course/format'.
2739 $defpath = $CFG->dirroot.'/course/'.$component.'/db/access.php';
2740 $varprefix = $compparts[0].'_'.$compparts[1];
89bd8357 2741
ce34ed3a 2742 } else if ($compparts[0] == 'gradeimport') {
89bd8357 2743 $defpath = $CFG->dirroot.'/grade/import/'.$compparts[1].'/db/access.php';
2744 $varprefix = $compparts[0].'_'.$compparts[1];
2745
ce34ed3a 2746 } else if ($compparts[0] == 'gradeexport') {
89bd8357 2747 $defpath = $CFG->dirroot.'/grade/export/'.$compparts[1].'/db/access.php';
2748 $varprefix = $compparts[0].'_'.$compparts[1];
2749
ce34ed3a 2750 } else if ($compparts[0] == 'gradereport') {
89bd8357 2751 $defpath = $CFG->dirroot.'/grade/report/'.$compparts[1].'/db/access.php';
2752 $varprefix = $compparts[0].'_'.$compparts[1];
2753
0c4d9f49 2754 } else {
2755 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
2756 $varprefix = str_replace('/', '_', $component);
2757 }
bbbf2d40 2758 }
2759 $capabilities = array();
eef868d1 2760
bbbf2d40 2761 if (file_exists($defpath)) {
dc268b2f 2762 require($defpath);
bbbf2d40 2763 $capabilities = ${$varprefix.'_capabilities'};
2764 }
2765 return $capabilities;
2766}
2767
2768
2769/**
2770 * Gets the capabilities that have been cached in the database for this
2771 * component.
2772 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2773 * @return array of capabilities
2774 */
2775function get_cached_capabilities($component='moodle') {
2776 if ($component == 'moodle') {
2777 $storedcaps = get_records_select('capabilities',
2778 "name LIKE 'moodle/%:%'");
2779 } else {
2780 $storedcaps = get_records_select('capabilities',
2781 "name LIKE '$component:%'");
2782 }
2783 return $storedcaps;
2784}
2785
3562486b 2786/**
2787 * Returns default capabilities for given legacy role type.
2788 *
2789 * @param string legacy role name
2790 * @return array
2791 */
2792function get_default_capabilities($legacyrole) {
2793 if (!$allcaps = get_records('capabilities')) {
2794 error('Error: no capabilitites defined!');
2795 }
2796 $alldefs = array();
2797 $defaults = array();
2798 $components = array();
2799 foreach ($allcaps as $cap) {
efe12f6c 2800 if (!in_array($cap->component, $components)) {
3562486b 2801 $components[] = $cap->component;
2802 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2803 }
2804 }
2805 foreach($alldefs as $name=>$def) {
2806 if (isset($def['legacy'][$legacyrole])) {
2807 $defaults[$name] = $def['legacy'][$legacyrole];
2808 }
2809 }
2810
2811 //some exceptions
2812 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW;
2813 if ($legacyrole == 'admin') {
2814 $defaults['moodle/site:doanything'] = CAP_ALLOW;
2815 }
2816 return $defaults;
2817}
bbbf2d40 2818
efe12f6c 2819/**
2820 * Reset role capabilitites to default according to selected legacy capability.
2821 * If several legacy caps selected, use the first from get_default_capabilities.
2822 * If no legacy selected, removes all capabilities.
2823 *
2824 * @param int @roleid
2825 */
2826function reset_role_capabilities($roleid) {
2827 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2828 $legacyroles = get_legacy_roles();
2829
2830 $defaultcaps = array();
2831 foreach($legacyroles as $ltype=>$lcap) {
2832 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
2833 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
2834 //choose first selected legacy capability
2835 $defaultcaps = get_default_capabilities($ltype);
2836 break;
2837 }
2838 }
2839
2840 delete_records('role_capabilities', 'roleid', $roleid);
2841 if (!empty($defaultcaps)) {
2842 foreach($defaultcaps as $cap=>$permission) {
2843 assign_capability($cap, $permission, $roleid, $sitecontext->id);
2844 }
2845 }
2846}
2847
bbbf2d40 2848/**
2849 * Updates the capabilities table with the component capability definitions.
2850 * If no parameters are given, the function updates the core moodle
2851 * capabilities.
2852 *
2853 * Note that the absence of the db/access.php capabilities definition file
2854 * will cause any stored capabilities for the component to be removed from
eef868d1 2855 * the database.
bbbf2d40 2856 *
2857 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2858 * @return boolean
2859 */
2860function update_capabilities($component='moodle') {
eef868d1 2861
bbbf2d40 2862 $storedcaps = array();
be4486da 2863
2864 $filecaps = load_capability_def($component);
bbbf2d40 2865 $cachedcaps = get_cached_capabilities($component);
2866 if ($cachedcaps) {
2867 foreach ($cachedcaps as $cachedcap) {
2868 array_push($storedcaps, $cachedcap->name);
5e992f56 2869 // update risk bitmasks and context levels in existing capabilities if needed
be4486da 2870 if (array_key_exists($cachedcap->name, $filecaps)) {
2871 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2b531945 2872 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
be4486da 2873 }
2874 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
5e992f56 2875 $updatecap = new object();
be4486da 2876 $updatecap->id = $cachedcap->id;
2877 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2878 if (!update_record('capabilities', $updatecap)) {
5e992f56 2879 return false;
2880 }
2881 }
2882
2883 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2884 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2885 }
2886 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2887 $updatecap = new object();
2888 $updatecap->id = $cachedcap->id;
2889 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2890 if (!update_record('capabilities', $updatecap)) {
be4486da 2891 return false;
2892 }
2893 }
2894 }
bbbf2d40 2895 }
2896 }
be4486da 2897
bbbf2d40 2898 // Are there new capabilities in the file definition?
2899 $newcaps = array();
eef868d1 2900
bbbf2d40 2901 foreach ($filecaps as $filecap => $def) {
eef868d1 2902 if (!$storedcaps ||
bbbf2d40 2903 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2b531945 2904 if (!array_key_exists('riskbitmask', $def)) {
2905 $def['riskbitmask'] = 0; // no risk if not specified
2906 }
bbbf2d40 2907 $newcaps[$filecap] = $def;
2908 }
2909 }
2910 // Add new capabilities to the stored definition.
2911 foreach ($newcaps as $capname => $capdef) {
2912 $capability = new object;
2913 $capability->name = $capname;
2914 $capability->captype = $capdef['captype'];
2915 $capability->contextlevel = $capdef['contextlevel'];
2916 $capability->component = $component;
be4486da 2917 $capability->riskbitmask = $capdef['riskbitmask'];
eef868d1 2918
bbbf2d40 2919 if (!insert_record('capabilities', $capability, false, 'id')) {
2920 return false;
2921 }
eef868d1 2922
c421ad4b 2923
7d8ea286 2924 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
2925 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
2926 foreach ($rolecapabilities as $rolecapability){
2927 //assign_capability will update rather than insert if capability exists
c421ad4b 2928 if (!assign_capability($capname, $rolecapability->permission,
7d8ea286 2929 $rolecapability->roleid, $rolecapability->contextid, true)){
2930 notify('Could not clone capabilities for '.$capname);
c421ad4b 2931 }
7d8ea286 2932 }
c421ad4b 2933 }
bbbf2d40 2934 // Do we need to assign the new capabilities to roles that have the
2935 // legacy capabilities moodle/legacy:* as well?
7d8ea286 2936 // we ignore legacy key if we have cloned permissions
2937 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
bbbf2d40 2938 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2e85fffe 2939 notify('Could not assign legacy capabilities for '.$capname);
bbbf2d40 2940 }
2941 }
2942 // Are there any capabilities that have been removed from the file
2943 // definition that we need to delete from the stored capabilities and
2944 // role assignments?
2945 capabilities_cleanup($component, $filecaps);
eef868d1 2946
bbbf2d40 2947 return true;
2948}
2949
2950
2951/**
2952 * Deletes cached capabilities that are no longer needed by the component.
2953 * Also unassigns these capabilities from any roles that have them.
2954 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2955 * @param $newcapdef - array of the new capability definitions that will be
2956 * compared with the cached capabilities
2957 * @return int - number of deprecated capabilities that have been removed
2958 */
2959function capabilities_cleanup($component, $newcapdef=NULL) {
eef868d1 2960
bbbf2d40 2961 $removedcount = 0;
eef868d1 2962
bbbf2d40 2963 if ($cachedcaps = get_cached_capabilities($component)) {
2964 foreach ($cachedcaps as $cachedcap) {
2965 if (empty($newcapdef) ||
2966 array_key_exists($cachedcap->name, $newcapdef) === false) {
eef868d1 2967
bbbf2d40 2968 // Remove from capabilities cache.
2969 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
2970 error('Could not delete deprecated capability '.$cachedcap->name);
2971 } else {
2972 $removedcount++;
2973 }
2974 // Delete from roles.
2975 if($roles = get_roles_with_capability($cachedcap->name)) {
2976 foreach($roles as $role) {
46943f7b 2977 if (!unassign_capability($cachedcap->name, $role->id)) {
bbbf2d40 2978 error('Could not unassign deprecated capability '.
2979 $cachedcap->name.' from role '.$role->name);
2980 }
2981 }
2982 }
2983 } // End if.
2984 }
2985 }
2986 return $removedcount;
2987}
2988
2989
2990
cee0901c 2991/****************
2992 * UI FUNCTIONS *
2993 ****************/
bbbf2d40 2994
2995
2996/**
2997 * prints human readable context identifier.
2998 */
cd26d8e0 2999function print_context_name($context, $withprefix = true, $short = false) {
340ea4e8 3000
ec0810ee 3001 $name = '';
aad2ba95 3002 switch ($context->contextlevel) {
ec0810ee 3003
bbbf2d40 3004 case CONTEXT_SYSTEM: // by now it's a definite an inherit
8cf990bc 3005 $name = get_string('coresystem');
340ea4e8 3006 break;
bbbf2d40 3007
3008 case CONTEXT_PERSONAL:
ec0810ee 3009 $name = get_string('personal');
340ea4e8 3010 break;
3011
4b10f08b 3012 case CONTEXT_USER:
ec0810ee 3013 if ($user = get_record('user', 'id', $context->instanceid)) {
cd26d8e0 3014 if ($withprefix){
3015 $name = get_string('user').': ';
3016 }
3017 $name .= fullname($user);
ec0810ee 3018 }
340ea4e8 3019 break;
3020
bbbf2d40 3021 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
ec0810ee 3022 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
cd26d8e0 3023 if ($withprefix){
3024 $name = get_string('category').': ';
3025 }
3026 $name .=format_string($category->name);
ec0810ee 3027 }
340ea4e8 3028 break;
bbbf2d40 3029
3030 case CONTEXT_COURSE: // 1 to 1 to course cat
ec0810ee 3031 if ($course = get_record('course', 'id', $context->instanceid)) {
cd26d8e0 3032 if ($withprefix){
3033 if ($context->instanceid == SITEID) {
3034 $name = get_string('site').': ';
3035 } else {
3036 $name = get_string('course').': ';
3037 }
8cf990bc 3038 }
cd26d8e0 3039 if ($short){
3040 $name .=format_string($course->shortname);
3041 } else {
3042 $name .=format_string($course->fullname);
3043 }
3044
ec0810ee 3045 }
340ea4e8 3046 break;
bbbf2d40 3047
3048 case CONTEXT_GROUP: // 1 to 1 to course
f3f7610c 3049 if ($name = groups_get_group_name($context->instanceid)) {
cd26d8e0 3050 if ($withprefix){
3051 $name = get_string('group').': '. $name;
c421ad4b 3052 }
ec0810ee 3053 }
340ea4e8 3054 break;
bbbf2d40 3055
3056 case CONTEXT_MODULE: // 1 to 1 to course
98882637 3057 if ($cm = get_record('course_modules','id',$context->instanceid)) {
3058 if ($module = get_record('modules','id',$cm->module)) {
3059 if ($mod = get_record($module->name, 'id', $cm->instance)) {
cd26d8e0 3060 if ($withprefix){
3061 $name = get_string('activitymodule').': ';
3062 }
3063 $name .= $mod->name;
98882637 3064 }
ec0810ee 3065 }
3066 }
340ea4e8 3067 break;
bbbf2d40 3068
c331cf23 3069 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
98882637 3070 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
3071 if ($block = get_record('block','id',$blockinstance->blockid)) {
91be52d7 3072 global $CFG;
3073 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
3074 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
3075 $blockname = "block_$block->name";
3076 if ($blockobject = new $blockname()) {
cd26d8e0 3077 if ($withprefix){
3078 $name = get_string('block').': ';
3079 }
3080 $name .= $blockobject->title;
91be52d7 3081 }
ec0810ee 3082 }
3083 }
340ea4e8 3084 break;
bbbf2d40 3085
3086 default:
8388ade8 3087 error ('This is an unknown context (' . $context->contextlevel . ') in print_context_name!');
340ea4e8 3088 return false;
3089
3090 }
340ea4e8 3091 return $name;
bbbf2d40 3092}
3093
3094
3095/**
eef868d1 3096 * Extracts the relevant capabilities given a contextid.
bbbf2d40 3097 * All case based, example an instance of forum context.
3098 * Will fetch all forum related capabilities, while course contexts
3099 * Will fetch all capabilities
0468976c 3100 * @param object context
bbbf2d40 3101 * @return array();
3102 *
3103 * capabilities
3104 * `name` varchar(150) NOT NULL,
3105 * `captype` varchar(50) NOT NULL,
3106 * `contextlevel` int(10) NOT NULL,
3107 * `component` varchar(100) NOT NULL,
3108 */
0468976c 3109function fetch_context_capabilities($context) {
eef868d1 3110
98882637 3111 global $CFG;
bbbf2d40 3112
3113 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
eef868d1 3114
aad2ba95 3115 switch ($context->contextlevel) {
bbbf2d40 3116
98882637 3117 case CONTEXT_SYSTEM: // all
3118 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 3119 break;
3120
3121 case CONTEXT_PERSONAL:
0a8a95c9 3122 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
bbbf2d40 3123 break;
eef868d1 3124
4b10f08b 3125 case CONTEXT_USER:
c421ad4b 3126 $SQL = "SELECT *
3127 FROM {$CFG->prefix}capabilities
8020a016 3128 WHERE contextlevel = ".CONTEXT_USER;
bbbf2d40 3129 break;
eef868d1 3130
bbbf2d40 3131 case CONTEXT_COURSECAT: // all
98882637 3132 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 3133 break;
3134
3135 case CONTEXT_COURSE: // all
98882637 3136 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 3137 break;
3138
3139 case CONTEXT_GROUP: // group caps
3140 break;
3141
3142 case CONTEXT_MODULE: // mod caps
98882637 3143 $cm = get_record('course_modules', 'id', $context->instanceid);
3144 $module = get_record('modules', 'id', $cm->module);
eef868d1 3145
98882637 3146 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
3147 and component = 'mod/$module->name'";
bbbf2d40 3148 break;
3149
3150 case CONTEXT_BLOCK: // block caps
98882637 3151 $cb = get_record('block_instance', 'id', $context->instanceid);
3152 $block = get_record('block', 'id', $cb->blockid);
eef868d1 3153
98882637 3154 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
7e874772 3155 and ( component = 'block/$block->name' or component = 'moodle')";
bbbf2d40 3156 break;
3157
3158 default:
3159 return false;
3160 }
3161
16e2e2f3 3162 if (!$records = get_records_sql($SQL.' '.$sort)) {
3163 $records = array();
3164 }
ba8d8027 3165
3166/// the rest of code is a bit hacky, think twice before modifying it :-(
69eb59f2 3167
3168 // special sorting of core system capabiltites and enrollments
e9c82dca 3169 if (in_array($context->contextlevel, array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE))) {
69eb59f2 3170 $first = array();
3171 foreach ($records as $key=>$record) {
3172 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
3173 $first[$key] = $record;
3174 unset($records[$key]);
3175 } else if (count($first)){
3176 break;
3177 }
3178 }
3179 if (count($first)) {
3180 $records = $first + $records; // merge the two arrays keeping the keys
3181 }
ba8d8027 3182 } else {