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