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