merged from 1.8 - removed commented old block widths definitions
[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
dfd1ff7a 101 $searchcontexts = array(); // get_child_contexts($context); SEE MDL-8385
cdfa3035 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
6d2d91d6 397 if (debugging('',DEBUG_DEVELOPER)) {
922633bd 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
efe12f6c 776/**
9fccc080 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
5f70bcc3 872/// Then we use 1 giant SQL to bring out all relevant capabilities.
873/// The first part gets the capabilities of orginal role.
874/// The second part gets the capabilities of overriden roles.
bbbf2d40 875
21c9bace 876 $siteinstance = get_context_instance(CONTEXT_SYSTEM);
9fccc080 877 $capabilities = array(); // Reinitialize.
878
879 // SQL for normal capabilities
880 $SQL1 = "SELECT rc.capability, c1.id as id1, c1.id as id2, (c1.contextlevel * 100) AS aggrlevel,
bbbf2d40 881 SUM(rc.permission) AS sum
882 FROM
eef868d1 883 {$CFG->prefix}role_assignments ra,
42ac3ecf 884 {$CFG->prefix}role_capabilities rc,
885 {$CFG->prefix}context c1
bbbf2d40 886 WHERE
d4649c76 887 ra.contextid=c1.id AND
888 ra.roleid=rc.roleid AND
bbbf2d40 889 ra.userid=$userid AND
5f70bcc3 890 $searchcontexts1
eef868d1 891 rc.contextid=$siteinstance->id
98882637 892 $capsearch
bbbf2d40 893 GROUP BY
55526eee 894 rc.capability, c1.id, c1.contextlevel * 100
bbbf2d40 895 HAVING
9fccc080 896 SUM(rc.permission) != 0
0db6adc9 897
898 UNION ALL
899
900 SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
901 SUM(rc.permission) AS sum
902 FROM
903 {$CFG->prefix}role_assignments ra LEFT JOIN
904 {$CFG->prefix}role_capabilities rc on ra.roleid = rc.roleid LEFT JOIN
905 {$CFG->prefix}context c1 on ra.contextid = c1.id LEFT JOIN
906 {$CFG->prefix}context c2 on rc.contextid = c2.id LEFT JOIN
907 {$CFG->prefix}context_rel cr on cr.c1 = c2.id
908 WHERE
909 ra.userid=$userid AND
910 $searchcontexts1
911 rc.contextid != $siteinstance->id
912 $capsearch
0db6adc9 913 AND cr.c2 = c1.id
914 GROUP BY
55526eee 915 rc.capability, c1.id, c2.id, c1.contextlevel * 100 + c2.contextlevel
0db6adc9 916 HAVING
917 SUM(rc.permission) != 0
9fccc080 918 ORDER BY
919 aggrlevel ASC";
0db6adc9 920
9fccc080 921 if (!$rs = get_recordset_sql($SQL1)) {
922 error("Query failed in load_user_capability.");
923 }
bbbf2d40 924
9fccc080 925 if ($rs && $rs->RecordCount() > 0) {
bcf88cbb 926 while ($caprec = rs_fetch_next_record($rs)) {
927 $array = (array)$caprec;
9fccc080 928 $temprecord = new object;
929
930 foreach ($array as $key=>$val) {
931 if ($key == 'aggrlevel') {
932 $temprecord->contextlevel = $val;
933 } else {
934 $temprecord->{$key} = $val;
935 }
936 }
9fccc080 937 $capabilities[] = $temprecord;
9fccc080 938 }
bcf88cbb 939 rs_close($rs);
b7e40271 940 }
bcf88cbb 941
9fccc080 942 // SQL for overrides
943 // this is take out because we have no way of making sure c1 is indeed related to c2 (parent)
944 // if we do not group by sum, it is possible to have multiple records of rc.capability, c1.id, c2.id, tuple having
945 // different values, we can maually sum it when we go through the list
0db6adc9 946
947 /*
948
9fccc080 949 $SQL2 = "SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
950 rc.permission AS sum
bbbf2d40 951 FROM
42ac3ecf 952 {$CFG->prefix}role_assignments ra,
953 {$CFG->prefix}role_capabilities rc,
954 {$CFG->prefix}context c1,
955 {$CFG->prefix}context c2
bbbf2d40 956 WHERE
d4649c76 957 ra.contextid=c1.id AND
eef868d1 958 ra.roleid=rc.roleid AND
959 ra.userid=$userid AND
960 rc.contextid=c2.id AND
5f70bcc3 961 $searchcontexts1
5f70bcc3 962 rc.contextid != $siteinstance->id
bbbf2d40 963 $capsearch
eef868d1 964
bbbf2d40 965 GROUP BY
21c9bace 966 rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c1.id, c2.id, rc.permission
bbbf2d40 967 ORDER BY
75e84883 968 aggrlevel ASC
0db6adc9 969 ";*/
9fccc080 970
0db6adc9 971/*
9fccc080 972 if (!$rs = get_recordset_sql($SQL2)) {
75e84883 973 error("Query failed in load_user_capability.");
974 }
5cf38a57 975
bbbf2d40 976 if ($rs && $rs->RecordCount() > 0) {
bcf88cbb 977 while ($caprec = rs_fetch_next_record($rs)) {
978 $array = (array)$caprec;
75e84883 979 $temprecord = new object;
eef868d1 980
98882637 981 foreach ($array as $key=>$val) {
75e84883 982 if ($key == 'aggrlevel') {
aad2ba95 983 $temprecord->contextlevel = $val;
75e84883 984 } else {
985 $temprecord->{$key} = $val;
986 }
98882637 987 }
9fccc080 988 // for overrides, we have to make sure that context2 is a child of context1
989 // otherwise the combination makes no sense
0db6adc9 990 //if (is_parent_context($temprecord->id1, $temprecord->id2)) {
9fccc080 991 $capabilities[] = $temprecord;
0db6adc9 992 //} // only write if relevant
bbbf2d40 993 }
bcf88cbb 994 rs_close($rs);
bbbf2d40 995 }
0db6adc9 996
9fccc080 997 // this step sorts capabilities according to the contextlevel
998 // it is very important because the order matters when we
999 // go through each capabilities later. (i.e. higher level contextlevel
1000 // will override lower contextlevel settings
1001 usort($capabilities, 'roles_context_cmp');
0db6adc9 1002*/
bbbf2d40 1003 /* so up to this point we should have somethign like this
aad2ba95 1004 * $capabilities[1] ->contextlevel = 1000
8ba412da 1005 ->module = 0 // changed from SITEID in 1.8 (??)
bbbf2d40 1006 ->capability = do_anything
1007 ->id = 1 (id is the context id)
1008 ->sum = 0
eef868d1 1009
aad2ba95 1010 * $capabilities[2] ->contextlevel = 1000
8ba412da 1011 ->module = 0 // changed from SITEID in 1.8 (??)
bbbf2d40 1012 ->capability = post_messages
1013 ->id = 1
1014 ->sum = -9000
1015
aad2ba95 1016 * $capabilittes[3] ->contextlevel = 3000
bbbf2d40 1017 ->module = course
1018 ->capability = view_course_activities
1019 ->id = 25
1020 ->sum = 1
1021
aad2ba95 1022 * $capabilittes[4] ->contextlevel = 3000
bbbf2d40 1023 ->module = course
1024 ->capability = view_course_activities
1025 ->id = 26
1026 ->sum = 0 (this is another course)
eef868d1 1027
aad2ba95 1028 * $capabilities[5] ->contextlevel = 3050
bbbf2d40 1029 ->module = course
1030 ->capability = view_course_activities
1031 ->id = 25 (override in course 25)
1032 ->sum = -1
1033 * ....
1034 * now we proceed to write the session array, going from top to bottom
1035 * at anypoint, we need to go up and check parent to look for prohibit
1036 */
1037 // print_object($capabilities);
1038
1039 /* This is where we write to the actualy capabilities array
1040 * what we need to do from here on is
1041 * going down the array from lowest level to highest level
1042 * 1) recursively check for prohibit,
1043 * if any, we write prohibit
1044 * else, we write the value
1045 * 2) at an override level, we overwrite current level
1046 * if it's not set to prohibit already, and if different
1047 * ........ that should be it ........
1048 */
efb58884 1049
1050 // This is the flag used for detecting the current context level. Since we are going through
1051 // the array in ascending order of context level. For normal capabilities, there should only
1052 // be 1 value per (capability, contextlevel, context), because they are already summed. But,
1053 // for overrides, since we are processing them separate, we need to sum the relevcant entries.
1054 // We set this flag when we hit a new level.
1055 // If the flag is already set, we keep adding (summing), otherwise, we just override previous
1056 // settings (from lower level contexts)
1057 $capflags = array(); // (contextid, contextlevel, capability)
98882637 1058 $usercap = array(); // for other user's capabilities
bbbf2d40 1059 foreach ($capabilities as $capability) {
1060
9fccc080 1061 if (!$context = get_context_instance_by_id($capability->id2)) {
7bfa3101 1062 continue; // incorrect stale context
1063 }
0468976c 1064
41811960 1065 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
eef868d1 1066
0468976c 1067 if (capability_prohibits($capability->capability, $context, $capability->sum, $usercap)) {
9fccc080 1068 $usercap[$capability->id2][$capability->capability] = CAP_PROHIBIT;
98882637 1069 continue;
1070 }
efb58884 1071 if (isset($usercap[$capability->id2][$capability->capability])) { // use isset because it can be sum 0
1072 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1073 $usercap[$capability->id2][$capability->capability] += $capability->sum;
1074 } else { // else we override, and update flag
1075 $usercap[$capability->id2][$capability->capability] = $capability->sum;
1076 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1077 }
9fccc080 1078 } else {
1079 $usercap[$capability->id2][$capability->capability] = $capability->sum;
efb58884 1080 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
9fccc080 1081 }
eef868d1 1082
98882637 1083 } else {
1084
0468976c 1085 if (capability_prohibits($capability->capability, $context, $capability->sum)) { // if any parent or parent's parent is set to prohibit
9fccc080 1086 $USER->capabilities[$capability->id2][$capability->capability] = CAP_PROHIBIT;
98882637 1087 continue;
1088 }
eef868d1 1089
98882637 1090 // if no parental prohibit set
1091 // just write to session, i am not sure this is correct yet
1092 // since 3050 shows up after 3000, and 3070 shows up after 3050,
1093 // it should be ok just to overwrite like this, provided that there's no
1094 // parental prohibits
98882637 1095 // we need to write even if it's 0, because it could be an inherit override
efb58884 1096 if (isset($USER->capabilities[$capability->id2][$capability->capability])) {
1097 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1098 $USER->capabilities[$capability->id2][$capability->capability] += $capability->sum;
1099 } else { // else we override, and update flag
1100 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
1101 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1102 }
9fccc080 1103 } else {
1104 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
efb58884 1105 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
9fccc080 1106 }
98882637 1107 }
bbbf2d40 1108 }
eef868d1 1109
bbbf2d40 1110 // now we don't care about the huge array anymore, we can dispose it.
1111 unset($capabilities);
efb58884 1112 unset($capflags);
eef868d1 1113
dbe7e582 1114 if (!empty($otheruserid)) {
eef868d1 1115 return $usercap; // return the array
bbbf2d40 1116 }
2f1a4248 1117}
1118
1119
1120/*
1121 * A convenience function to completely load all the capabilities
1122 * for the current user. This is what gets called from login, for example.
1123 */
1124function load_all_capabilities() {
1125 global $USER;
1126
1127 if (empty($USER->username)) {
1128 return;
1129 }
bbbf2d40 1130
8e82745a 1131 unset($USER->mycourses); // Reset a cache used by get_my_courses
1132
2f1a4248 1133 load_user_capability(); // Load basic capabilities assigned to this user
1134
1135 if ($USER->username == 'guest') {
1136 load_guest_role(); // All non-guest users get this by default
1137 } else {
1138 load_defaultuser_role(); // All non-guest users get this by default
1139 }
bbbf2d40 1140}
1141
2f1a4248 1142
efe12f6c 1143/**
64026e8c 1144 * Check all the login enrolment information for the given user object
eef868d1 1145 * by querying the enrolment plugins
64026e8c 1146 */
1147function check_enrolment_plugins(&$user) {
1148 global $CFG;
1149
e4ec4e41 1150 static $inprogress; // To prevent this function being called more than once in an invocation
1151
218eb651 1152 if (!empty($inprogress[$user->id])) {
e4ec4e41 1153 return;
1154 }
1155
218eb651 1156 $inprogress[$user->id] = true; // Set the flag
e4ec4e41 1157
64026e8c 1158 require_once($CFG->dirroot .'/enrol/enrol.class.php');
eef868d1 1159
64026e8c 1160 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
1161 $plugins = array($CFG->enrol);
1162 }
1163
1164 foreach ($plugins as $plugin) {
1165 $enrol = enrolment_factory::factory($plugin);
1166 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1167 $enrol->setup_enrolments($user);
1168 } else { /// Run legacy enrolment methods
1169 if (method_exists($enrol, 'get_student_courses')) {
1170 $enrol->get_student_courses($user);
1171 }
1172 if (method_exists($enrol, 'get_teacher_courses')) {
1173 $enrol->get_teacher_courses($user);
1174 }
1175
1176 /// deal with $user->students and $user->teachers stuff
1177 unset($user->student);
1178 unset($user->teacher);
1179 }
1180 unset($enrol);
1181 }
e4ec4e41 1182
218eb651 1183 unset($inprogress[$user->id]); // Unset the flag
64026e8c 1184}
1185
bbbf2d40 1186
1187/**
1188 * This is a recursive function that checks whether the capability in this
1189 * context, or the parent capabilities are set to prohibit.
1190 *
1191 * At this point, we can probably just use the values already set in the
1192 * session variable, since we are going down the level. Any prohit set in
1193 * parents would already reflect in the session.
1194 *
1195 * @param $capability - capability name
1196 * @param $sum - sum of all capabilities values
0468976c 1197 * @param $context - the context object
bbbf2d40 1198 * @param $array - when loading another user caps, their caps are not stored in session but an array
1199 */
0468976c 1200function capability_prohibits($capability, $context, $sum='', $array='') {
bbbf2d40 1201 global $USER;
0468976c 1202
0db6adc9 1203 // caching, mainly to save unnecessary sqls
1204 static $prohibits; //[capability][contextid]
1205 if (isset($prohibits[$capability][$context->id])) {
1206 return $prohibits[$capability][$context->id];
1207 }
1208
2176adf1 1209 if (empty($context->id)) {
0db6adc9 1210 $prohibits[$capability][$context->id] = false;
2176adf1 1211 return false;
1212 }
1213
1214 if (empty($capability)) {
0db6adc9 1215 $prohibits[$capability][$context->id] = false;
2176adf1 1216 return false;
1217 }
1218
819e5a70 1219 if ($sum < (CAP_PROHIBIT/2)) {
bbbf2d40 1220 // If this capability is set to prohibit.
0db6adc9 1221 $prohibits[$capability][$context->id] = true;
bbbf2d40 1222 return true;
1223 }
eef868d1 1224
819e5a70 1225 if (!empty($array)) {
eef868d1 1226 if (isset($array[$context->id][$capability])
819e5a70 1227 && $array[$context->id][$capability] < (CAP_PROHIBIT/2)) {
0db6adc9 1228 $prohibits[$capability][$context->id] = true;
98882637 1229 return true;
eef868d1 1230 }
bbbf2d40 1231 } else {
98882637 1232 // Else if set in session.
eef868d1 1233 if (isset($USER->capabilities[$context->id][$capability])
819e5a70 1234 && $USER->capabilities[$context->id][$capability] < (CAP_PROHIBIT/2)) {
0db6adc9 1235 $prohibits[$capability][$context->id] = true;
98882637 1236 return true;
1237 }
bbbf2d40 1238 }
aad2ba95 1239 switch ($context->contextlevel) {
eef868d1 1240
bbbf2d40 1241 case CONTEXT_SYSTEM:
1242 // By now it's a definite an inherit.
1243 return 0;
1244 break;
1245
1246 case CONTEXT_PERSONAL:
2176adf1 1247 $parent = get_context_instance(CONTEXT_SYSTEM);
0db6adc9 1248 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1249 return $prohibits[$capability][$context->id];
bbbf2d40 1250 break;
1251
4b10f08b 1252 case CONTEXT_USER:
2176adf1 1253 $parent = get_context_instance(CONTEXT_SYSTEM);
0db6adc9 1254 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1255 return $prohibits[$capability][$context->id];
bbbf2d40 1256 break;
1257
1258 case CONTEXT_COURSECAT:
1259 // Coursecat -> coursecat or site.
2176adf1 1260 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
0db6adc9 1261 $prohibits[$capability][$context->id] = false;
2176adf1 1262 return false;
40a2a15f 1263 }
41811960 1264 if (!empty($coursecat->parent)) {
bbbf2d40 1265 // return parent value if exist.
1266 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1267 } else {
1268 // Return site value.
2176adf1 1269 $parent = get_context_instance(CONTEXT_SYSTEM);
bbbf2d40 1270 }
0db6adc9 1271 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1272 return $prohibits[$capability][$context->id];
bbbf2d40 1273 break;
1274
1275 case CONTEXT_COURSE:
1276 // 1 to 1 to course cat.
1277 // Find the course cat, and return its value.
2176adf1 1278 if (!$course = get_record('course','id',$context->instanceid)) {
0db6adc9 1279 $prohibits[$capability][$context->id] = false;
2176adf1 1280 return false;
1281 }
40a2a15f 1282 // Yu: Separating site and site course context
1283 if ($course->id == SITEID) {
1284 $parent = get_context_instance(CONTEXT_SYSTEM);
1285 } else {
1286 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1287 }
0db6adc9 1288 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1289 return $prohibits[$capability][$context->id];
bbbf2d40 1290 break;
1291
1292 case CONTEXT_GROUP:
1293 // 1 to 1 to course.
f3f7610c 1294 if (!$courseid = groups_get_course($context->instanceid)) {
0db6adc9 1295 $prohibits[$capability][$context->id] = false;
2176adf1 1296 return false;
1297 }
f3f7610c 1298 $parent = get_context_instance(CONTEXT_COURSE, $courseid);
0db6adc9 1299 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1300 return $prohibits[$capability][$context->id];
bbbf2d40 1301 break;
1302
1303 case CONTEXT_MODULE:
1304 // 1 to 1 to course.
2176adf1 1305 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
0db6adc9 1306 $prohibits[$capability][$context->id] = false;
2176adf1 1307 return false;
1308 }
bbbf2d40 1309 $parent = get_context_instance(CONTEXT_COURSE, $cm->course);
0db6adc9 1310 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1311 return $prohibits[$capability][$context->id];
bbbf2d40 1312 break;
1313
1314 case CONTEXT_BLOCK:
1315 // 1 to 1 to course.
2176adf1 1316 if (!$block = get_record('block_instance','id',$context->instanceid)) {
0db6adc9 1317 $prohibits[$capability][$context->id] = false;
2176adf1 1318 return false;
1319 }
bbbf2d40 1320 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
0db6adc9 1321 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1322 return $prohibits[$capability][$context->id];
bbbf2d40 1323 break;
1324
1325 default:
2176adf1 1326 print_error('unknowncontext');
1327 return false;
bbbf2d40 1328 }
1329}
1330
1331
1332/**
1333 * A print form function. This should either grab all the capabilities from
1334 * files or a central table for that particular module instance, then present
1335 * them in check boxes. Only relevant capabilities should print for known
1336 * context.
1337 * @param $mod - module id of the mod
1338 */
1339function print_capabilities($modid=0) {
1340 global $CFG;
eef868d1 1341
bbbf2d40 1342 $capabilities = array();
1343
1344 if ($modid) {
1345 // We are in a module specific context.
1346
1347 // Get the mod's name.
1348 // Call the function that grabs the file and parse.
1349 $cm = get_record('course_modules', 'id', $modid);
1350 $module = get_record('modules', 'id', $cm->module);
eef868d1 1351
bbbf2d40 1352 } else {
1353 // Print all capabilities.
1354 foreach ($capabilities as $capability) {
1355 // Prints the check box component.
1356 }
1357 }
1358}
1359
1360
1361/**
1afecc03 1362 * Installs the roles system.
1363 * This function runs on a fresh install as well as on an upgrade from the old
1364 * hard-coded student/teacher/admin etc. roles to the new roles system.
bbbf2d40 1365 */
1afecc03 1366function moodle_install_roles() {
bbbf2d40 1367
1afecc03 1368 global $CFG, $db;
eef868d1 1369
459c1ff1 1370/// Create a system wide context for assignemnt.
21c9bace 1371 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
bbbf2d40 1372
1afecc03 1373
459c1ff1 1374/// Create default/legacy roles and capabilities.
1375/// (1 legacy capability per legacy role at system level).
1376
69aaada0 1377 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1378 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1379 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1380 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1381 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1382 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1383 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1384 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1385 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1386 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1387 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1388 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
c785d40a 1389 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1390 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
2851ba9b 1391
17e5635c 1392/// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
459c1ff1 1393
98882637 1394 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
bbbf2d40 1395 error('Could not assign moodle/site:doanything to the admin role');
1396 }
250934b8 1397 if (!update_capabilities()) {
1398 error('Had trouble upgrading the core capabilities for the Roles System');
1399 }
1afecc03 1400
459c1ff1 1401/// Look inside user_admin, user_creator, user_teachers, user_students and
1402/// assign above new roles. If a user has both teacher and student role,
1403/// only teacher role is assigned. The assignment should be system level.
1404
1afecc03 1405 $dbtables = $db->MetaTables('TABLES');
eef868d1 1406
72da5046 1407/// Set up the progress bar
1408
1409 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1410
1411 $totalcount = $progresscount = 0;
1412 foreach ($usertables as $usertable) {
1413 if (in_array($CFG->prefix.$usertable, $dbtables)) {
1414 $totalcount += count_records($usertable);
1415 }
1416 }
1417
aae37b63 1418 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1419
459c1ff1 1420/// Upgrade the admins.
1421/// Sort using id ASC, first one is primary admin.
1422
1afecc03 1423 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
f1dcf000 1424 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
0f5dafff 1425 while ($admin = rs_fetch_next_record($rs)) {
1afecc03 1426 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
72da5046 1427 $progresscount++;
aae37b63 1428 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1429 }
0f5dafff 1430 rs_close($rs);
1afecc03 1431 }
1432 } else {
1433 // This is a fresh install.
bbbf2d40 1434 }
1afecc03 1435
1436
459c1ff1 1437/// Upgrade course creators.
1afecc03 1438 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
f1dcf000 1439 if ($rs = get_recordset('user_coursecreators')) {
0f5dafff 1440 while ($coursecreator = rs_fetch_next_record($rs)) {
56b4d70d 1441 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
72da5046 1442 $progresscount++;
aae37b63 1443 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1444 }
0f5dafff 1445 rs_close($rs);
1afecc03 1446 }
bbbf2d40 1447 }
1448
1afecc03 1449
459c1ff1 1450/// Upgrade editting teachers and non-editting teachers.
1afecc03 1451 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
f1dcf000 1452 if ($rs = get_recordset('user_teachers')) {
0f5dafff 1453 while ($teacher = rs_fetch_next_record($rs)) {
d5511451 1454
1455 // removed code here to ignore site level assignments
1456 // since the contexts are separated now
1457
17d6a25e 1458 // populate the user_lastaccess table
ece4945b 1459 $access = new object();
17d6a25e 1460 $access->timeaccess = $teacher->timeaccess;
1461 $access->userid = $teacher->userid;
1462 $access->courseid = $teacher->course;
1463 insert_record('user_lastaccess', $access);
f1dcf000 1464
17d6a25e 1465 // assign the default student role
1afecc03 1466 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
3fe54e51 1467 // hidden teacher
1468 if ($teacher->authority == 0) {
1469 $hiddenteacher = 1;
1470 } else {
1471 $hiddenteacher = 0;
1472 }
1473
1afecc03 1474 if ($teacher->editall) { // editting teacher
3fe54e51 1475 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1afecc03 1476 } else {
3fe54e51 1477 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1afecc03 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
3562486b 1553/**
1554 * Returns array of all legacy roles.
1555 */
1556function get_legacy_roles() {
1557 return array(
a83addc5 1558 'admin' => 'moodle/legacy:admin',
3562486b 1559 'coursecreator' => 'moodle/legacy:coursecreator',
a83addc5 1560 'editingteacher' => 'moodle/legacy:editingteacher',
1561 'teacher' => 'moodle/legacy:teacher',
1562 'student' => 'moodle/legacy:student',
efe12f6c 1563 'guest' => 'moodle/legacy:guest',
1564 'user' => 'moodle/legacy:user'
3562486b 1565 );
1566}
1567
b357ed13 1568function get_legacy_type($roleid) {
1569 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1570 $legacyroles = get_legacy_roles();
1571
1572 $result = '';
1573 foreach($legacyroles as $ltype=>$lcap) {
1574 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
1575 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
1576 //choose first selected legacy capability - reset the rest
1577 if (empty($result)) {
1578 $result = $ltype;
1579 } else {
66a27728 1580 unassign_capability($lcap, $roleid);
b357ed13 1581 }
1582 }
1583 }
1584
1585 return $result;
1586}
1587
bbbf2d40 1588/**
1589 * Assign the defaults found in this capabality definition to roles that have
1590 * the corresponding legacy capabilities assigned to them.
1591 * @param $legacyperms - an array in the format (example):
1592 * 'guest' => CAP_PREVENT,
1593 * 'student' => CAP_ALLOW,
1594 * 'teacher' => CAP_ALLOW,
1595 * 'editingteacher' => CAP_ALLOW,
1596 * 'coursecreator' => CAP_ALLOW,
1597 * 'admin' => CAP_ALLOW
1598 * @return boolean - success or failure.
1599 */
1600function assign_legacy_capabilities($capability, $legacyperms) {
eef868d1 1601
3562486b 1602 $legacyroles = get_legacy_roles();
1603
bbbf2d40 1604 foreach ($legacyperms as $type => $perm) {
eef868d1 1605
21c9bace 1606 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
eef868d1 1607
3562486b 1608 if (!array_key_exists($type, $legacyroles)) {
1609 error('Incorrect legacy role definition for type: '.$type);
1610 }
eef868d1 1611
3562486b 1612 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW)) {
2e85fffe 1613 foreach ($roles as $role) {
1614 // Assign a site level capability.
1615 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1616 return false;
1617 }
bbbf2d40 1618 }
1619 }
1620 }
1621 return true;
1622}
1623
1624
cee0901c 1625/**
1626 * Checks to see if a capability is a legacy capability.
1627 * @param $capabilityname
1628 * @return boolean
1629 */
bbbf2d40 1630function islegacy($capabilityname) {
d67de0ca 1631 if (strpos($capabilityname, 'moodle/legacy') === 0) {
eef868d1 1632 return true;
d67de0ca 1633 } else {
1634 return false;
98882637 1635 }
bbbf2d40 1636}
1637
cee0901c 1638
1639
1640/**********************************
bbbf2d40 1641 * Context Manipulation functions *
1642 **********************************/
1643
bbbf2d40 1644/**
9991d157 1645 * Create a new context record for use by all roles-related stuff
bbbf2d40 1646 * @param $level
1647 * @param $instanceid
3ca2dea5 1648 *
1649 * @return object newly created context (or existing one with a debug warning)
bbbf2d40 1650 */
aad2ba95 1651function create_context($contextlevel, $instanceid) {
3ca2dea5 1652 if (!$context = get_record('context','contextlevel',$contextlevel,'instanceid',$instanceid)) {
1653 if (!validate_context($contextlevel, $instanceid)) {
1654 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1655 return NULL;
1656 }
8ba412da 1657 if ($contextlevel == CONTEXT_SYSTEM) {
1658 return create_system_context();
1659
1660 }
3ca2dea5 1661 $context = new object();
aad2ba95 1662 $context->contextlevel = $contextlevel;
bbbf2d40 1663 $context->instanceid = $instanceid;
3ca2dea5 1664 if ($id = insert_record('context',$context)) {
0db6adc9 1665 // we need to populate context_rel for every new context inserted
1666 $c = get_record('context','id',$id);
1667 insert_context_rel ($c);
1668 return $c;
3ca2dea5 1669 } else {
1670 debugging('Error: could not insert new context level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1671 return NULL;
1672 }
1673 } else {
1674 debugging('Warning: Context id "'.s($context->id).'" not created, because it already exists.');
1675 return $context;
bbbf2d40 1676 }
1677}
1678
efe12f6c 1679/**
8ba412da 1680 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
1681 */
1682function create_system_context() {
1683 if ($context = get_record('context', 'contextlevel', CONTEXT_SYSTEM, 'instanceid', SITEID)) {
1684 // we are going to change instanceid of system context to 0 now
1685 $context->instanceid = 0;
1686 update_record('context', $context);
1687 //context rel not affected
1688 return $context;
1689
1690 } else {
1691 $context = new object();
1692 $context->contextlevel = CONTEXT_SYSTEM;
1693 $context->instanceid = 0;
1694 if ($context->id = insert_record('context',$context)) {
1695 // we need not to populate context_rel for system context
1696 return $context;
1697 } else {
1698 debugging('Can not create system context');
1699 return NULL;
1700 }
1701 }
1702}
9991d157 1703/**
1704 * Create a new context record for use by all roles-related stuff
1705 * @param $level
1706 * @param $instanceid
3ca2dea5 1707 *
1708 * @return true if properly deleted
9991d157 1709 */
1710function delete_context($contextlevel, $instanceid) {
0db6adc9 1711 if ($context = get_context_instance($contextlevel, $instanceid)) {
1712 delete_records('context_rel', 'c2', $context->id); // might not be a parent
9991d157 1713 return delete_records('context', 'id', $context->id) &&
1714 delete_records('role_assignments', 'contextid', $context->id) &&
0db6adc9 1715 delete_records('role_capabilities', 'contextid', $context->id) &&
1716 delete_records('context_rel', 'c1', $context->id);
9991d157 1717 }
1718 return true;
1719}
1720
3ca2dea5 1721/**
1722 * Validate that object with instanceid really exists in given context level.
1723 *
1724 * return if instanceid object exists
1725 */
1726function validate_context($contextlevel, $instanceid) {
1727 switch ($contextlevel) {
1728
1729 case CONTEXT_SYSTEM:
8ba412da 1730 return ($instanceid == 0);
3ca2dea5 1731
1732 case CONTEXT_PERSONAL:
1733 return (boolean)count_records('user', 'id', $instanceid);
1734
1735 case CONTEXT_USER:
1736 return (boolean)count_records('user', 'id', $instanceid);
1737
1738 case CONTEXT_COURSECAT:
1cd3eba9 1739 if ($instanceid == 0) {
1740 return true; // site course category
1741 }
3ca2dea5 1742 return (boolean)count_records('course_categories', 'id', $instanceid);
1743
1744 case CONTEXT_COURSE:
1745 return (boolean)count_records('course', 'id', $instanceid);
1746
1747 case CONTEXT_GROUP:
f3f7610c
ML
1748 //return (boolean)count_records('groups_groups', 'id', $instanceid); //TODO:DONOTCOMMIT:
1749 return groups_group_exists($instanceid);
3ca2dea5 1750
1751 case CONTEXT_MODULE:
1752 return (boolean)count_records('course_modules', 'id', $instanceid);
1753
1754 case CONTEXT_BLOCK:
1755 return (boolean)count_records('block_instance', 'id', $instanceid);
1756
1757 default:
1758 return false;
1759 }
1760}
bbbf2d40 1761
1762/**
1763 * Get the context instance as an object. This function will create the
1764 * context instance if it does not exist yet.
1765 * @param $level
1766 * @param $instance
1767 */
8ba412da 1768function get_context_instance($contextlevel=NULL, $instance=0) {
e5605780 1769
51195e6f 1770 global $context_cache, $context_cache_id, $CONTEXT;
a36a3a3f 1771 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_PERSONAL, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_GROUP, CONTEXT_MODULE, CONTEXT_BLOCK);
d9a35e12 1772
8ba412da 1773 // Yu: Separating site and site course context - removed CONTEXT_COURSE override when SITEID
b7cec865 1774
340ea4e8 1775/// If no level is supplied then return the current global context if there is one
aad2ba95 1776 if (empty($contextlevel)) {
340ea4e8 1777 if (empty($CONTEXT)) {
a36a3a3f 1778 //fatal error, code must be fixed
1779 error("Error: get_context_instance() called without a context");
340ea4e8 1780 } else {
1781 return $CONTEXT;
1782 }
e5605780 1783 }
1784
8ba412da 1785/// Backwards compatibility with obsoleted (CONTEXT_SYSTEM, SITEID)
1786 if ($contextlevel == CONTEXT_SYSTEM) {
1787 $instance = 0;
1788 }
1789
a36a3a3f 1790/// check allowed context levels
1791 if (!in_array($contextlevel, $allowed_contexts)) {
7bfa3101 1792 // fatal error, code must be fixed - probably typo or switched parameters
a36a3a3f 1793 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
1794 }
1795
340ea4e8 1796/// Check the cache
aad2ba95 1797 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
1798 return $context_cache[$contextlevel][$instance];
e5605780 1799 }
1800
340ea4e8 1801/// Get it from the database, or create it
aad2ba95 1802 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
1803 create_context($contextlevel, $instance);
1804 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
e5605780 1805 }
1806
ccfc5ecc 1807/// Only add to cache if context isn't empty.
1808 if (!empty($context)) {
aad2ba95 1809 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
ccfc5ecc 1810 $context_cache_id[$context->id] = $context; // Cache it for later
1811 }
0468976c 1812
bbbf2d40 1813 return $context;
1814}
1815
cee0901c 1816
340ea4e8 1817/**
1818 * Get a context instance as an object, from a given id.
1819 * @param $id
1820 */
1821function get_context_instance_by_id($id) {
1822
d9a35e12 1823 global $context_cache, $context_cache_id;
1824
340ea4e8 1825 if (isset($context_cache_id[$id])) { // Already cached
75e84883 1826 return $context_cache_id[$id];
340ea4e8 1827 }
1828
1829 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
aad2ba95 1830 $context_cache[$context->contextlevel][$context->instanceid] = $context;
340ea4e8 1831 $context_cache_id[$context->id] = $context;
1832 return $context;
1833 }
1834
1835 return false;
1836}
1837
bbbf2d40 1838
8737be58 1839/**
1840 * Get the local override (if any) for a given capability in a role in a context
1841 * @param $roleid
0468976c 1842 * @param $contextid
1843 * @param $capability
8737be58 1844 */
1845function get_local_override($roleid, $contextid, $capability) {
1846 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1847}
1848
1849
bbbf2d40 1850
1851/************************************
1852 * DB TABLE RELATED FUNCTIONS *
1853 ************************************/
1854
cee0901c 1855/**
bbbf2d40 1856 * function that creates a role
1857 * @param name - role name
31f26796 1858 * @param shortname - role short name
bbbf2d40 1859 * @param description - role description
1860 * @param legacy - optional legacy capability
1861 * @return id or false
1862 */
8420bee9 1863function create_role($name, $shortname, $description, $legacy='') {
eef868d1 1864
98882637 1865 // check for duplicate role name
eef868d1 1866
98882637 1867 if ($role = get_record('role','name', $name)) {
eef868d1 1868 error('there is already a role with this name!');
98882637 1869 }
eef868d1 1870
31f26796 1871 if ($role = get_record('role','shortname', $shortname)) {
eef868d1 1872 error('there is already a role with this shortname!');
31f26796 1873 }
1874
b5959f30 1875 $role = new object();
98882637 1876 $role->name = $name;
31f26796 1877 $role->shortname = $shortname;
98882637 1878 $role->description = $description;
eef868d1 1879
8420bee9 1880 //find free sortorder number
1881 $role->sortorder = count_records('role');
1882 while (get_record('role','sortorder', $role->sortorder)) {
1883 $role->sortorder += 1;
b5959f30 1884 }
1885
21c9bace 1886 if (!$context = get_context_instance(CONTEXT_SYSTEM)) {
1887 return false;
1888 }
eef868d1 1889
98882637 1890 if ($id = insert_record('role', $role)) {
eef868d1 1891 if ($legacy) {
1892 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
98882637 1893 }
eef868d1 1894
ec7a8b79 1895 /// By default, users with role:manage at site level
1896 /// should be able to assign users to this new role, and override this new role's capabilities
eef868d1 1897
ec7a8b79 1898 // find all admin roles
e46c0987 1899 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
1900 // foreach admin role
1901 foreach ($adminroles as $arole) {
1902 // write allow_assign and allow_overrid
1903 allow_assign($arole->id, $id);
eef868d1 1904 allow_override($arole->id, $id);
e46c0987 1905 }
ec7a8b79 1906 }
eef868d1 1907
98882637 1908 return $id;
1909 } else {
eef868d1 1910 return false;
98882637 1911 }
eef868d1 1912
bbbf2d40 1913}
1914
8420bee9 1915/**
1916 * function that deletes a role and cleanups up after it
1917 * @param roleid - id of role to delete
1918 * @return success
1919 */
1920function delete_role($roleid) {
1921 $success = true;
1922
1923// first unssign all users
1924 if (!role_unassign($roleid)) {
1925 debugging("Error while unassigning all users from role with ID $roleid!");
1926 $success = false;
1927 }
1928
1929// cleanup all references to this role, ignore errors
1930 if ($success) {
1931 delete_records('role_capabilities', 'roleid', $roleid);
1932 delete_records('role_allow_assign', 'roleid', $roleid);
1933 delete_records('role_allow_assign', 'allowassign', $roleid);
1934 delete_records('role_allow_override', 'roleid', $roleid);
1935 delete_records('role_allow_override', 'allowoverride', $roleid);
1936 delete_records('role_names', 'roleid', $roleid);
1937 }
1938
1939// finally delete the role itself
1940 if ($success and !delete_records('role', 'id', $roleid)) {
ece4945b 1941 debugging("Could not delete role record with ID $roleid!");
8420bee9 1942 $success = false;
1943 }
1944
1945 return $success;
1946}
1947
bbbf2d40 1948/**
1949 * Function to write context specific overrides, or default capabilities.
1950 * @param module - string name
1951 * @param capability - string name
1952 * @param contextid - context id
1953 * @param roleid - role id
1954 * @param permission - int 1,-1 or -1000
96986241 1955 * should not be writing if permission is 0
bbbf2d40 1956 */
e7876c1e 1957function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
eef868d1 1958
98882637 1959 global $USER;
eef868d1 1960
96986241 1961 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
eef868d1 1962 unassign_capability($capability, $roleid, $contextid);
96986241 1963 return true;
98882637 1964 }
eef868d1 1965
2e85fffe 1966 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
e7876c1e 1967
1968 if ($existing and !$overwrite) { // We want to keep whatever is there already
1969 return true;
1970 }
1971
bbbf2d40 1972 $cap = new object;
1973 $cap->contextid = $contextid;
1974 $cap->roleid = $roleid;
1975 $cap->capability = $capability;
1976 $cap->permission = $permission;
1977 $cap->timemodified = time();
9db12da7 1978 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
e7876c1e 1979
1980 if ($existing) {
1981 $cap->id = $existing->id;
1982 return update_record('role_capabilities', $cap);
1983 } else {
1984 return insert_record('role_capabilities', $cap);
1985 }
bbbf2d40 1986}
1987
1988
1989/**
1990 * Unassign a capability from a role.
1991 * @param $roleid - the role id
1992 * @param $capability - the name of the capability
1993 * @return boolean - success or failure
1994 */
1995function unassign_capability($capability, $roleid, $contextid=NULL) {
eef868d1 1996
98882637 1997 if (isset($contextid)) {
1998 $status = delete_records('role_capabilities', 'capability', $capability,
1999 'roleid', $roleid, 'contextid', $contextid);
2000 } else {
2001 $status = delete_records('role_capabilities', 'capability', $capability,
2002 'roleid', $roleid);
2003 }
2004 return $status;
bbbf2d40 2005}
2006
2007
2008/**
759ac72d 2009 * Get the roles that have a given capability assigned to it. This function
2010 * does not resolve the actual permission of the capability. It just checks
2011 * for assignment only.
bbbf2d40 2012 * @param $capability - capability name (string)
2013 * @param $permission - optional, the permission defined for this capability
2014 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2015 * @return array or role objects
2016 */
ec7a8b79 2017function get_roles_with_capability($capability, $permission=NULL, $context='') {
2018
bbbf2d40 2019 global $CFG;
eef868d1 2020
ec7a8b79 2021 if ($context) {
2022 if ($contexts = get_parent_contexts($context)) {
2023 $listofcontexts = '('.implode(',', $contexts).')';
2024 } else {
21c9bace 2025 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
eef868d1 2026 $listofcontexts = '('.$sitecontext->id.')'; // must be site
2027 }
42ac3ecf 2028 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
ec7a8b79 2029 } else {
2030 $contextstr = '';
2031 }
eef868d1 2032
2033 $selectroles = "SELECT r.*
42ac3ecf 2034 FROM {$CFG->prefix}role r,
2035 {$CFG->prefix}role_capabilities rc
bbbf2d40 2036 WHERE rc.capability = '$capability'
ec7a8b79 2037 AND rc.roleid = r.id $contextstr";
bbbf2d40 2038
2039 if (isset($permission)) {
2040 $selectroles .= " AND rc.permission = '$permission'";
2041 }
2042 return get_records_sql($selectroles);
2043}
2044
2045
2046/**
a9e1c058 2047 * This function makes a role-assignment (a role for a user or group in a particular context)
bbbf2d40 2048 * @param $roleid - the role of the id
2049 * @param $userid - userid
2050 * @param $groupid - group id
2051 * @param $contextid - id of the context
2052 * @param $timestart - time this assignment becomes effective
2053 * @param $timeend - time this assignemnt ceases to be effective
2054 * @uses $USER
2055 * @return id - new id of the assigment
2056 */
f44152f4 2057function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual') {
aa311411 2058 global $USER, $CFG;
bbbf2d40 2059
7eb0b60a 2060 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER);
bbbf2d40 2061
a9e1c058 2062/// Do some data validation
2063
bbbf2d40 2064 if (empty($roleid)) {
9d829c68 2065 debugging('Role ID not provided');
a9e1c058 2066 return false;
bbbf2d40 2067 }
2068
2069 if (empty($userid) && empty($groupid)) {
9d829c68 2070 debugging('Either userid or groupid must be provided');
a9e1c058 2071 return false;
bbbf2d40 2072 }
eef868d1 2073
7700027f 2074 if ($userid && !record_exists('user', 'id', $userid)) {
82396e5b 2075 debugging('User ID '.intval($userid).' does not exist!');
7700027f 2076 return false;
2077 }
bbbf2d40 2078
f3f7610c 2079 if ($groupid && !groups_group_exists($groupid)) {
82396e5b 2080 debugging('Group ID '.intval($groupid).' does not exist!');
dc411d1b 2081 return false;
2082 }
2083
7700027f 2084 if (!$context = get_context_instance_by_id($contextid)) {
82396e5b 2085 debugging('Context ID '.intval($contextid).' does not exist!');
a9e1c058 2086 return false;
bbbf2d40 2087 }
2088
a9e1c058 2089 if (($timestart and $timeend) and ($timestart > $timeend)) {
9d829c68 2090 debugging('The end time can not be earlier than the start time');
a9e1c058 2091 return false;
2092 }
2093
7700027f 2094
a9e1c058 2095/// Check for existing entry
2096 if ($userid) {
7700027f 2097 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
a9e1c058 2098 } else {
7700027f 2099 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
a9e1c058 2100 }
2101
9ebcb4d2 2102
a9e1c058 2103 $newra = new object;
bbbf2d40 2104
a9e1c058 2105 if (empty($ra)) { // Create a new entry
2106 $newra->roleid = $roleid;
7700027f 2107 $newra->contextid = $context->id;
a9e1c058 2108 $newra->userid = $userid;
a9e1c058 2109 $newra->hidden = $hidden;
f44152f4 2110 $newra->enrol = $enrol;
0616d3e8 2111 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2112 /// by repeating queries with the same exact parameters in a 100 secs time window
2113 $newra->timestart = round($timestart, -2);
a9e1c058 2114 $newra->timeend = $timeend;
2115 $newra->timemodified = time();
115faa2f 2116 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
a9e1c058 2117
9ebcb4d2 2118 $success = insert_record('role_assignments', $newra);
a9e1c058 2119
2120 } else { // We already have one, just update it
2121
2122 $newra->id = $ra->id;
2123 $newra->hidden = $hidden;
f44152f4 2124 $newra->enrol = $enrol;
0616d3e8 2125 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2126 /// by repeating queries with the same exact parameters in a 100 secs time window
2127 $newra->timestart = round($timestart, -2);
a9e1c058 2128 $newra->timeend = $timeend;
2129 $newra->timemodified = time();
115faa2f 2130 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
a9e1c058 2131
9ebcb4d2 2132 $success = update_record('role_assignments', $newra);
2133 }
2134
7700027f 2135 if ($success) { /// Role was assigned, so do some other things
2136
2137 /// If the user is the current user, then reload the capabilities too.
2138 if (!empty($USER->id) && $USER->id == $userid) {
2f1a4248 2139 load_all_capabilities();
7700027f 2140 }
9b5d7a46 2141
0f161e1f 2142 /// Ask all the modules if anything needs to be done for this user
2143 if ($mods = get_list_of_plugins('mod')) {
2144 foreach ($mods as $mod) {
2145 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2146 $functionname = $mod.'_role_assign';
2147 if (function_exists($functionname)) {
2148 $functionname($userid, $context);
2149 }
2150 }
2151 }
2152
2153 /// Make sure they have an entry in user_lastaccess for courses they can access
2154 // role_add_lastaccess_entries($userid, $context);
a9e1c058 2155 }
eef868d1 2156
4e5f3064 2157 /// now handle metacourse role assignments if in course context
aad2ba95 2158 if ($success and $context->contextlevel == CONTEXT_COURSE) {
4e5f3064 2159 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2160 foreach ($parents as $parent) {
1aad4310 2161 sync_metacourse($parent->parent_course);
4e5f3064 2162 }
2163 }
2164 }
6eb4f823 2165
2166 return $success;
bbbf2d40 2167}
2168
2169
2170/**
1dc1f037 2171 * Deletes one or more role assignments. You must specify at least one parameter.
bbbf2d40 2172 * @param $roleid
2173 * @param $userid
2174 * @param $groupid
2175 * @param $contextid
2176 * @return boolean - success or failure
2177 */
1dc1f037 2178function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0) {
d74067e8 2179
2180 global $USER, $CFG;
eef868d1 2181
4e5f3064 2182 $success = true;
d74067e8 2183
1dc1f037 2184 $args = array('roleid', 'userid', 'groupid', 'contextid');
2185 $select = array();
2186 foreach ($args as $arg) {
2187 if ($$arg) {
2188 $select[] = $arg.' = '.$$arg;
2189 }
2190 }
d74067e8 2191
1dc1f037 2192 if ($select) {
4e5f3064 2193 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2194 $mods = get_list_of_plugins('mod');
2195 foreach($ras as $ra) {
86e2c51d 2196 /// infinite loop protection when deleting recursively
2197 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
2198 continue;
2199 }
4e5f3064 2200 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
86e2c51d 2201
4e5f3064 2202 /// If the user is the current user, then reload the capabilities too.
2203 if (!empty($USER->id) && $USER->id == $ra->userid) {
2f1a4248 2204 load_all_capabilities();
4e5f3064 2205 }
2206 $context = get_record('context', 'id', $ra->contextid);
0f161e1f 2207
2208 /// Ask all the modules if anything needs to be done for this user
4e5f3064 2209 foreach ($mods as $mod) {
2210 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2211 $functionname = $mod.'_role_unassign';
2212 if (function_exists($functionname)) {
2213 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
2214 }
2215 }
2216
2217 /// now handle metacourse role unassigment and removing from goups if in course context
aad2ba95 2218 if (!empty($context) and $context->contextlevel == CONTEXT_COURSE) {
4e5f3064 2219 //remove from groups when user has no role
2220 $roles = get_user_roles($context, $ra->userid, true);
2221 if (empty($roles)) {
2222 if ($groups = get_groups($context->instanceid, $ra->userid)) {
2223 foreach ($groups as $group) {
2224 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
2225 }
2226 }
2227 }
1aad4310 2228 //unassign roles in metacourses if needed
4e5f3064 2229 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2230 foreach ($parents as $parent) {
1aad4310 2231 sync_metacourse($parent->parent_course);
0f161e1f 2232 }
2233 }
0f161e1f 2234 }
2235 }
d74067e8 2236 }
1dc1f037 2237 }
4e5f3064 2238
2239 return $success;
bbbf2d40 2240}
2241
efe12f6c 2242/**
eef868d1 2243 * A convenience function to take care of the common case where you
b963384f 2244 * just want to enrol someone using the default role into a course
2245 *
2246 * @param object $course
2247 * @param object $user
2248 * @param string $enrol - the plugin used to do this enrolment
2249 */
2250function enrol_into_course($course, $user, $enrol) {
2251
2252 if ($course->enrolperiod) {
2253 $timestart = time();
2254 $timeend = time() + $course->enrolperiod;
2255 } else {
2256 $timestart = $timeend = 0;
2257 }
2258
2259 if ($role = get_default_course_role($course)) {
c4381ef5 2260
2261 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2262
e2183037 2263 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
b963384f 2264 return false;
2265 }
eef868d1 2266
b963384f 2267 email_welcome_message_to_user($course, $user);
eef868d1 2268
b963384f 2269 add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
2270
2271 return true;
2272 }
2273
2274 return false;
2275}
2276
0f161e1f 2277/**
2278 * Add last access times to user_lastaccess as required
2279 * @param $userid
2280 * @param $context
2281 * @return boolean - success or failure
2282 */
2283function role_add_lastaccess_entries($userid, $context) {
2284
2285 global $USER, $CFG;
2286
aad2ba95 2287 if (empty($context->contextlevel)) {
0f161e1f 2288 return false;
2289 }
2290
2291 $lastaccess = new object; // Reusable object below
2292 $lastaccess->userid = $userid;
2293 $lastaccess->timeaccess = 0;
2294
aad2ba95 2295 switch ($context->contextlevel) {
0f161e1f 2296
2297 case CONTEXT_SYSTEM: // For the whole site
2298 if ($courses = get_record('course')) {
2299 foreach ($courses as $course) {
2300 $lastaccess->courseid = $course->id;
2301 role_set_lastaccess($lastaccess);
2302 }
2303 }
2304 break;
2305
2306 case CONTEXT_CATEGORY: // For a whole category
2307 if ($courses = get_record('course', 'category', $context->instanceid)) {
2308 foreach ($courses as $course) {
2309 $lastaccess->courseid = $course->id;
2310 role_set_lastaccess($lastaccess);
2311 }
2312 }
2313 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
2314 foreach ($categories as $category) {
2315 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
2316 role_add_lastaccess_entries($userid, $subcontext);
2317 }
2318 }
2319 break;
eef868d1 2320
0f161e1f 2321
2322 case CONTEXT_COURSE: // For a whole course
2323 if ($course = get_record('course', 'id', $context->instanceid)) {
2324 $lastaccess->courseid = $course->id;
2325 role_set_lastaccess($lastaccess);
2326 }
2327 break;
2328 }
2329}
2330
2331/**
2332 * Delete last access times from user_lastaccess as required
2333 * @param $userid
2334 * @param $context
2335 * @return boolean - success or failure
2336 */
2337function role_remove_lastaccess_entries($userid, $context) {
2338
2339 global $USER, $CFG;
2340
2341}
2342
bbbf2d40 2343
2344/**
2345 * Loads the capability definitions for the component (from file). If no
2346 * capabilities are defined for the component, we simply return an empty array.
2347 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2348 * @return array of capabilities
2349 */
2350function load_capability_def($component) {
2351 global $CFG;
2352
2353 if ($component == 'moodle') {
2354 $defpath = $CFG->libdir.'/db/access.php';
2355 $varprefix = 'moodle';
2356 } else {
0c4d9f49 2357 $compparts = explode('/', $component);
eef868d1 2358
0c4d9f49 2359 if ($compparts[0] == 'block') {
2360 // Blocks are an exception. Blocks directory is 'blocks', and not
2361 // 'block'. So we need to jump through hoops.
2362 $defpath = $CFG->dirroot.'/'.$compparts[0].
2363 's/'.$compparts[1].'/db/access.php';
2364 $varprefix = $compparts[0].'_'.$compparts[1];
ae628043 2365 } else if ($compparts[0] == 'format') {
2366 // Similar to the above, course formats are 'format' while they
2367 // are stored in 'course/format'.
2368 $defpath = $CFG->dirroot.'/course/'.$component.'/db/access.php';
2369 $varprefix = $compparts[0].'_'.$compparts[1];
0c4d9f49 2370 } else {
2371 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
2372 $varprefix = str_replace('/', '_', $component);
2373 }
bbbf2d40 2374 }
2375 $capabilities = array();
eef868d1 2376
bbbf2d40 2377 if (file_exists($defpath)) {
dc268b2f 2378 require($defpath);
bbbf2d40 2379 $capabilities = ${$varprefix.'_capabilities'};
2380 }
2381 return $capabilities;
2382}
2383
2384
2385/**
2386 * Gets the capabilities that have been cached in the database for this
2387 * component.
2388 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2389 * @return array of capabilities
2390 */
2391function get_cached_capabilities($component='moodle') {
2392 if ($component == 'moodle') {
2393 $storedcaps = get_records_select('capabilities',
2394 "name LIKE 'moodle/%:%'");
2395 } else {
2396 $storedcaps = get_records_select('capabilities',
2397 "name LIKE '$component:%'");
2398 }
2399 return $storedcaps;
2400}
2401
3562486b 2402/**
2403 * Returns default capabilities for given legacy role type.
2404 *
2405 * @param string legacy role name
2406 * @return array
2407 */
2408function get_default_capabilities($legacyrole) {
2409 if (!$allcaps = get_records('capabilities')) {
2410 error('Error: no capabilitites defined!');
2411 }
2412 $alldefs = array();
2413 $defaults = array();
2414 $components = array();
2415 foreach ($allcaps as $cap) {
efe12f6c 2416 if (!in_array($cap->component, $components)) {
3562486b 2417 $components[] = $cap->component;
2418 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2419 }
2420 }
2421 foreach($alldefs as $name=>$def) {
2422 if (isset($def['legacy'][$legacyrole])) {
2423 $defaults[$name] = $def['legacy'][$legacyrole];
2424 }
2425 }
2426
2427 //some exceptions
2428 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW;
2429 if ($legacyrole == 'admin') {
2430 $defaults['moodle/site:doanything'] = CAP_ALLOW;
2431 }
2432 return $defaults;
2433}
bbbf2d40 2434
efe12f6c 2435/**
2436 * Reset role capabilitites to default according to selected legacy capability.
2437 * If several legacy caps selected, use the first from get_default_capabilities.
2438 * If no legacy selected, removes all capabilities.
2439 *
2440 * @param int @roleid
2441 */
2442function reset_role_capabilities($roleid) {
2443 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2444 $legacyroles = get_legacy_roles();
2445
2446 $defaultcaps = array();
2447 foreach($legacyroles as $ltype=>$lcap) {
2448 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
2449 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
2450 //choose first selected legacy capability
2451 $defaultcaps = get_default_capabilities($ltype);
2452 break;
2453 }
2454 }
2455
2456 delete_records('role_capabilities', 'roleid', $roleid);
2457 if (!empty($defaultcaps)) {
2458 foreach($defaultcaps as $cap=>$permission) {
2459 assign_capability($cap, $permission, $roleid, $sitecontext->id);
2460 }
2461 }
2462}
2463
bbbf2d40 2464/**
2465 * Updates the capabilities table with the component capability definitions.
2466 * If no parameters are given, the function updates the core moodle
2467 * capabilities.
2468 *
2469 * Note that the absence of the db/access.php capabilities definition file
2470 * will cause any stored capabilities for the component to be removed from
eef868d1 2471 * the database.
bbbf2d40 2472 *
2473 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2474 * @return boolean
2475 */
2476function update_capabilities($component='moodle') {
eef868d1 2477
bbbf2d40 2478 $storedcaps = array();
be4486da 2479
2480 $filecaps = load_capability_def($component);
bbbf2d40 2481 $cachedcaps = get_cached_capabilities($component);
2482 if ($cachedcaps) {
2483 foreach ($cachedcaps as $cachedcap) {
2484 array_push($storedcaps, $cachedcap->name);
17e5635c 2485 // update risk bitmasks in existing capabilities if needed
be4486da 2486 if (array_key_exists($cachedcap->name, $filecaps)) {
2487 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2b531945 2488 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
be4486da 2489 }
2490 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2491 $updatecap = new object;
2492 $updatecap->id = $cachedcap->id;
2493 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2494 if (!update_record('capabilities', $updatecap)) {
2495 return false;
2496 }
2497 }
2498 }
bbbf2d40 2499 }
2500 }
be4486da 2501
bbbf2d40 2502 // Are there new capabilities in the file definition?
2503 $newcaps = array();
eef868d1 2504
bbbf2d40 2505 foreach ($filecaps as $filecap => $def) {
eef868d1 2506 if (!$storedcaps ||
bbbf2d40 2507 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2b531945 2508 if (!array_key_exists('riskbitmask', $def)) {
2509 $def['riskbitmask'] = 0; // no risk if not specified
2510 }
bbbf2d40 2511 $newcaps[$filecap] = $def;
2512 }
2513 }
2514 // Add new capabilities to the stored definition.
2515 foreach ($newcaps as $capname => $capdef) {
2516 $capability = new object;
2517 $capability->name = $capname;
2518 $capability->captype = $capdef['captype'];
2519 $capability->contextlevel = $capdef['contextlevel'];
2520 $capability->component = $component;
be4486da 2521 $capability->riskbitmask = $capdef['riskbitmask'];
eef868d1 2522
bbbf2d40 2523 if (!insert_record('capabilities', $capability, false, 'id')) {
2524 return false;
2525 }
eef868d1 2526
bbbf2d40 2527 // Do we need to assign the new capabilities to roles that have the
2528 // legacy capabilities moodle/legacy:* as well?
2529 if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
2530 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2e85fffe 2531 notify('Could not assign legacy capabilities for '.$capname);
bbbf2d40 2532 }
2533 }
2534 // Are there any capabilities that have been removed from the file
2535 // definition that we need to delete from the stored capabilities and
2536 // role assignments?
2537 capabilities_cleanup($component, $filecaps);
eef868d1 2538
bbbf2d40 2539 return true;
2540}
2541
2542
2543/**
2544 * Deletes cached capabilities that are no longer needed by the component.
2545 * Also unassigns these capabilities from any roles that have them.
2546 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2547 * @param $newcapdef - array of the new capability definitions that will be
2548 * compared with the cached capabilities
2549 * @return int - number of deprecated capabilities that have been removed
2550 */
2551function capabilities_cleanup($component, $newcapdef=NULL) {
eef868d1 2552
bbbf2d40 2553 $removedcount = 0;
eef868d1 2554
bbbf2d40 2555 if ($cachedcaps = get_cached_capabilities($component)) {
2556 foreach ($cachedcaps as $cachedcap) {
2557 if (empty($newcapdef) ||
2558 array_key_exists($cachedcap->name, $newcapdef) === false) {
eef868d1 2559
bbbf2d40 2560 // Remove from capabilities cache.
2561 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
2562 error('Could not delete deprecated capability '.$cachedcap->name);
2563 } else {
2564 $removedcount++;
2565 }
2566 // Delete from roles.
2567 if($roles = get_roles_with_capability($cachedcap->name)) {
2568 foreach($roles as $role) {
46943f7b 2569 if (!unassign_capability($cachedcap->name, $role->id)) {
bbbf2d40 2570 error('Could not unassign deprecated capability '.
2571 $cachedcap->name.' from role '.$role->name);
2572 }
2573 }
2574 }
2575 } // End if.
2576 }
2577 }
2578 return $removedcount;
2579}
2580
2581
2582
cee0901c 2583/****************
2584 * UI FUNCTIONS *
2585 ****************/
bbbf2d40 2586
2587
2588/**
2589 * prints human readable context identifier.
2590 */
0468976c 2591function print_context_name($context) {
340ea4e8 2592
ec0810ee 2593 $name = '';
aad2ba95 2594 switch ($context->contextlevel) {
ec0810ee 2595
bbbf2d40 2596 case CONTEXT_SYSTEM: // by now it's a definite an inherit
ec0810ee 2597 $name = get_string('site');
340ea4e8 2598 break;
bbbf2d40 2599
2600 case CONTEXT_PERSONAL:
ec0810ee 2601 $name = get_string('personal');
340ea4e8 2602 break;
2603
4b10f08b 2604 case CONTEXT_USER:
ec0810ee 2605 if ($user = get_record('user', 'id', $context->instanceid)) {
2606 $name = get_string('user').': '.fullname($user);
2607 }
340ea4e8 2608 break;
2609
bbbf2d40 2610 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
ec0810ee 2611 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
6ba65fa0 2612 $name = get_string('category').': '. format_string($category->name);
ec0810ee 2613 }
340ea4e8 2614 break;
bbbf2d40 2615
2616 case CONTEXT_COURSE: // 1 to 1 to course cat
ec0810ee 2617 if ($course = get_record('course', 'id', $context->instanceid)) {
6ba65fa0 2618 $name = get_string('course').': '. format_string($course->fullname);
ec0810ee 2619 }
340ea4e8 2620 break;
bbbf2d40 2621
2622 case CONTEXT_GROUP: // 1 to 1 to course
f3f7610c
ML
2623 if ($name = groups_get_group_name($context->instanceid)) {
2624 $name = get_string('group').': '. $name;
ec0810ee 2625 }
340ea4e8 2626 break;
bbbf2d40 2627
2628 case CONTEXT_MODULE: // 1 to 1 to course
98882637 2629 if ($cm = get_record('course_modules','id',$context->instanceid)) {
2630 if ($module = get_record('modules','id',$cm->module)) {
2631 if ($mod = get_record($module->name, 'id', $cm->instance)) {
ec0810ee 2632 $name = get_string('activitymodule').': '.$mod->name;
98882637 2633 }
ec0810ee 2634 }
2635 }
340ea4e8 2636 break;
bbbf2d40 2637
2638 case CONTEXT_BLOCK: // 1 to 1 to course
98882637 2639 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
2640 if ($block = get_record('block','id',$blockinstance->blockid)) {
91be52d7 2641 global $CFG;
2642 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
2643 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
2644 $blockname = "block_$block->name";
2645 if ($blockobject = new $blockname()) {
2646 $name = $blockobject->title.' ('.get_string('block').')';
2647 }
ec0810ee 2648 }
2649 }
340ea4e8 2650 break;
bbbf2d40 2651
2652 default:
8388ade8 2653 error ('This is an unknown context (' . $context->contextlevel . ') in print_context_name!');
340ea4e8 2654 return false;
2655
2656 }
340ea4e8 2657 return $name;
bbbf2d40 2658}
2659
2660
2661/**
eef868d1 2662 * Extracts the relevant capabilities given a contextid.
bbbf2d40 2663 * All case based, example an instance of forum context.
2664 * Will fetch all forum related capabilities, while course contexts
2665 * Will fetch all capabilities
0468976c 2666 * @param object context
bbbf2d40 2667 * @return array();
2668 *
2669 * capabilities
2670 * `name` varchar(150) NOT NULL,
2671 * `captype` varchar(50) NOT NULL,
2672 * `contextlevel` int(10) NOT NULL,
2673 * `component` varchar(100) NOT NULL,
2674 */
0468976c 2675function fetch_context_capabilities($context) {
eef868d1 2676
98882637 2677 global $CFG;
bbbf2d40 2678
2679 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
eef868d1 2680
aad2ba95 2681 switch ($context->contextlevel) {
bbbf2d40 2682
98882637 2683 case CONTEXT_SYSTEM: // all
2684 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2685 break;
2686
2687 case CONTEXT_PERSONAL:
0a8a95c9 2688 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
bbbf2d40 2689 break;
eef868d1 2690
4b10f08b 2691 case CONTEXT_USER:
8020a016 2692 $SQL = "SELECT *
2693 FROM {$CFG->prefix}capabilities
2694 WHERE contextlevel = ".CONTEXT_USER;
bbbf2d40 2695 break;
eef868d1 2696
bbbf2d40 2697 case CONTEXT_COURSECAT: // all
98882637 2698 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2699 break;
2700
2701 case CONTEXT_COURSE: // all
98882637 2702 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2703 break;
2704
2705 case CONTEXT_GROUP: // group caps
2706 break;
2707
2708 case CONTEXT_MODULE: // mod caps
98882637 2709 $cm = get_record('course_modules', 'id', $context->instanceid);
2710 $module = get_record('modules', 'id', $cm->module);
eef868d1 2711
98882637 2712 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
2713 and component = 'mod/$module->name'";
bbbf2d40 2714 break;
2715
2716 case CONTEXT_BLOCK: // block caps
98882637 2717 $cb = get_record('block_instance', 'id', $context->instanceid);
2718 $block = get_record('block', 'id', $cb->blockid);
eef868d1 2719
98882637 2720 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
2721 and component = 'block/$block->name'";
bbbf2d40 2722 break;
2723
2724 default:
2725 return false;
2726 }
2727
16e2e2f3 2728 if (!$records = get_records_sql($SQL.' '.$sort)) {
2729 $records = array();
2730 }
ba8d8027 2731
2732/// the rest of code is a bit hacky, think twice before modifying it :-(
69eb59f2 2733
2734 // special sorting of core system capabiltites and enrollments
e9c82dca 2735 if (in_array($context->contextlevel, array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE))) {
69eb59f2 2736 $first = array();
2737 foreach ($records as $key=>$record) {
2738 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
2739 $first[$key] = $record;
2740 unset($records[$key]);
2741 } else if (count($first)){
2742 break;
2743 }
2744 }
2745 if (count($first)) {
2746 $records = $first + $records; // merge the two arrays keeping the keys
2747 }
ba8d8027 2748 } else {
2749 $contextindependentcaps = fetch_context_independent_capabilities();
2750 $records = array_merge($contextindependentcaps, $records);
69eb59f2 2751 }
ba8d8027 2752
bbbf2d40 2753 return $records;
eef868d1 2754
bbbf2d40 2755}
2756
2757
759ac72d 2758/**
2759 * Gets the context-independent capabilities that should be overrridable in
2760 * any context.
2761 * @return array of capability records from the capabilities table.
2762 */
2763function fetch_context_independent_capabilities() {
eef868d1 2764
17e5635c 2765 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
759ac72d 2766 $contextindependentcaps = array(
2767 'moodle/site:accessallgroups'
2768 );
2769
2770 $records = array();
eef868d1 2771
759ac72d 2772 foreach ($contextindependentcaps as $capname) {
2773 $record = get_record('capabilities', 'name', $capname);
2774 array_push($records, $record);
2775 }
2776 return $records;
2777}
2778
2779
bbbf2d40 2780/**
2781 * This function pulls out all the resolved capabilities (overrides and
759ac72d 2782 * defaults) of a role used in capability overrides in contexts at a given
bbbf2d40 2783 * context.
0a8a95c9 2784 * @param obj $context
bbbf2d40 2785 * @param int $roleid
dc558690 2786 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
bbbf2d40 2787 * @return array
2788 */
1648afb2 2789function role_context_capabilities($roleid, $context, $cap='') {
dc558690 2790 global $CFG;
eef868d1 2791
8521d83a 2792 $contexts = get_parent_contexts($context);
2793 $contexts[] = $context->id;
98882637 2794 $contexts = '('.implode(',', $contexts).')';
eef868d1 2795
1648afb2 2796 if ($cap) {
e4697bf7 2797 $search = " AND rc.capability = '$cap' ";
1648afb2 2798 } else {
eef868d1 2799 $search = '';
1648afb2 2800 }
eef868d1 2801
2802 $SQL = "SELECT rc.*
2803 FROM {$CFG->prefix}role_capabilities rc,
dc558690 2804 {$CFG->prefix}context c
2805 WHERE rc.contextid in $contexts
2806 AND rc.roleid = $roleid
2807 AND rc.contextid = c.id $search
aad2ba95 2808 ORDER BY c.contextlevel DESC,
eef868d1 2809 rc.capability DESC";
759ac72d 2810
98882637 2811 $capabilities = array();
eef868d1 2812
4729012f 2813 if ($records = get_records_sql($SQL)) {
2814 // We are traversing via reverse order.
2815 foreach ($records as $record) {
2816 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2817 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2818 $capabilities[$record->capability] = $record->permission;
eef868d1 2819 }
4729012f 2820 }
98882637 2821 }
2822 return $capabilities;
bbbf2d40 2823}
2824
bbbf2d40 2825/**
eef868d1 2826 * Recursive function which, given a context, find all parent context ids,
bbbf2d40 2827 * and return the array in reverse order, i.e. parent first, then grand
2828 * parent, etc.
2829 * @param object $context
2830 * @return array()
2831 */
bbbf2d40 2832function get_parent_contexts($context) {
759ac72d 2833
1cd03601 2834 static $pcontexts; // cache
2835 if (isset($pcontexts[$context->id])) {
2836 return ($pcontexts[$context->id]);
2837 }
2838
aad2ba95 2839 switch ($context->contextlevel) {
bbbf2d40 2840
2841 case CONTEXT_SYSTEM: // no parent
957861f7 2842 return array();
bbbf2d40 2843 break;
2844
2845 case CONTEXT_PERSONAL:
21c9bace 2846 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
957861f7 2847 return array();
2848 } else {
1cd03601 2849 $res = array($parent->id);
0de75c4c 2850 $pcontexts[$context->id] = $res;
1cd03601 2851 return $res;
957861f7 2852 }
bbbf2d40 2853 break;
eef868d1 2854
4b10f08b 2855 case CONTEXT_USER:
21c9bace 2856 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
957861f7 2857 return array();
2858 } else {
1cd03601 2859 $res = array($parent->id);
0de75c4c 2860 $pcontexts[$context->id] = $res;
1cd03601 2861 return $res;
957861f7 2862 }
bbbf2d40 2863 break;
eef868d1 2864
bbbf2d40 2865 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
957861f7 2866 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
2867 return array();
2868 }
c5ddc3fd 2869 if (!empty($coursecat->parent)) { // return parent value if exist
bbbf2d40 2870 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1cd03601 2871 $res = array_merge(array($parent->id), get_parent_contexts($parent));
2872 $pcontexts[$context->id] = $res;
2873 return $res;
bbbf2d40 2874 } else { // else return site value
21c9bace 2875 $parent = get_context_instance(CONTEXT_SYSTEM);
1cd03601 2876 $res = array($parent->id);
2877 $pcontexts[$context->id] = $res;
2878 return $res;
bbbf2d40 2879 }
2880 break;
2881
2882 case CONTEXT_COURSE: // 1 to 1 to course cat
957861f7 2883 if (!$course = get_record('course','id',$context->instanceid)) {
2884 return array();
2885 }
1936c10e 2886 if ($course->id != SITEID) {
957861f7 2887 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1cd03601 2888 $res = array_merge(array($parent->id), get_parent_contexts($parent));
2889 return $res;
957861f7 2890 } else {
40a2a15f 2891 // Yu: Separating site and site course context
2892 $parent = get_context_instance(CONTEXT_SYSTEM);
1cd03601 2893 $res = array($parent->id);
2894 $pcontexts[$context->id] = $res;
2895 return $res;
957861f7 2896 }
bbbf2d40 2897 break;
2898
2899 case CONTEXT_GROUP: // 1 to 1 to course
f3f7610c 2900 if (! $group = groups_get_group($context->instanceid)) {
957861f7 2901 return array();
2902 }
2903 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
1cd03601 2904 $res = array_merge(array($parent->id), get_parent_contexts($parent));
2905 $pcontexts[$context->id] = $res;
2906 return $res;
957861f7 2907 } else {
2908 return array();
2909 }
bbbf2d40 2910 break;
2911
2912 case CONTEXT_MODULE: // 1 to 1 to course
957861f7 2913 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
2914 return array();
2915 }
2916 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
1cd03601 2917 $res = array_merge(array($parent->id), get_parent_contexts($parent));
2918 $pcontexts[$context->id] = $res;
2919 return $res;
957861f7 2920 } else {
2921 return array();
2922 }
bbbf2d40 2923 break;
2924
2925 case CONTEXT_BLOCK: // 1 to 1 to course
957861f7 2926 if (!$block = get_record('block_instance','id',$context->instanceid)) {
2927 return array();
2928 }
2929 if ($parent = get_context_instance(CONTEXT_COURSE, $block->pageid)) {
1cd03601 2930 $res = array_merge(array($parent->id), get_parent_contexts($parent));
2931 $pcontexts[$context->id] = $res;
2932 return $res;
957861f7 2933 } else {
2934 return array();
2935 }
bbbf2d40 2936 break;
2937
2938 default:
8388ade8 2939 error('This is an unknown context (' . $context->contextlevel . ') in get_parent_contexts!');
bbbf2d40 2940 return false;
2941 }
bbbf2d40 2942}
2943
759ac72d 2944
cdfa3035 2945/**
2946 * Recursive function which, given a context, find all its children context ids.
2947 * @param object $context.
2948 * @return array of children context ids.
2949 */
2950function get_child_contexts($context) {
2951
2952 global $CFG;
2953 $children = array();
2954
2955 switch ($context->contextlevel) {
2956
2957 case CONTEXT_BLOCK:
2958 // No children.
2959 return array();
2960 break;
2961
2962 case CONTEXT_MODULE:
2963 // No children.
2964 return array();
2965 break;
2966
2967 case CONTEXT_GROUP:
2968 // No children.
2969 return array();
2970 break;
2971
2972 case CONTEXT_COURSE:
2973 // Find all block instances for the course.
2974 $page = new page_course;
2975 $page->id = $context->instanceid;
2976 $page->type = 'course-view';
2977 if ($blocks = blocks_get_by_page_pinned($page)) {
2978 foreach ($blocks['l'] as $leftblock) {
2b91b669 2979 if ($child = get_context_instance(CONTEXT_BLOCK, $leftblock->id)) {
cdfa3035 2980 array_push($children, $child->id);
2981 }
2982 }
2983 foreach ($blocks['r'] as $rightblock) {
2b91b669 2984 if ($child = get_context_instance(CONTEXT_BLOCK, $rightblock->id)) {
cdfa3035 2985 array_push($children, $child->id);
2986 }
2987 }
2988 }
2989 // Find all module instances for the course.
2990 if ($modules = get_records('course_modules', 'course', $context->instanceid)) {
2991 foreach ($modules as $module) {
2992 if ($child = get_context_instance(CONTEXT_MODULE, $module->id)) {
2993 array_push($children, $child->id);
2994 }
2995 }
2996 }
2997 // Find all group instances for the course.
2b91b669 2998 if ($groupids = groups_get_groups($context->instanceid)) {
2999 foreach ($groupids as $groupid) {
3000 if ($child = get_context_instance(CONTEXT_GROUP, $groupid)) {
cdfa3035 3001 array_push($children, $child->id);
3002 }
3003 }
3004 }
3005 return $children;
3006 break;
3007
3008 case CONTEXT_COURSECAT:
3009 // We need to get the contexts for:
3010 // 1) The subcategories of the given category
3011 // 2) The courses in the given category and all its subcategories
3012 // 3) All the child contexts for these courses
3013
3014 $categories = get_all_subcategories($context->instanceid);
3015
3016 // Add the contexts for all the subcategories.
3017 foreach ($categories as $catid) {
3018 if ($catci = get_context_instance(CONTEXT_COURSECAT, $catid)) {
3019 array_push($children, $catci->id);
3020 }
3021 }
3022
3023 // Add the parent category as well so we can find the contexts
3024 // for its courses.
3025 array_unshift($categories, $context->instanceid);
3026
3027 foreach ($categories as $catid) {
3028 // Find all courses for the category.
3029 if ($courses = get_records('course', 'category', $catid)) {
3030 foreach ($courses as $course) {
3031 if ($courseci = get_context_instance(CONTEXT_COURSE, $course->id)) {
3032 array_push($children, $courseci->id);
3033 $children = array_merge($children, get_child_contexts($courseci));
3034 }
3035 }
3036 }
3037 }
3038 return $children;
3039 break;
3040
3041 case CONTEXT_USER:
3042 // No children.
3043 return array();
3044 break;
3045
3046 case CONTEXT_PERSONAL:
3047 // No children.
3048 return array();
3049 break;
3050
3051 case CONTEXT_SYSTEM:
3052 // Just get all the contexts except for CONTEXT_SYSTEM level.
3053 $sql = 'SELECT c.id '.
3054 'FROM '.$CFG->prefix.'context AS c '.
3055 'WHERE contextlevel != '.CONTEXT_SYSTEM;
3056
3057 $contexts = get_records_sql($sql);
3058 foreach ($contexts as $cid) {
3059 array_push($children, $cid->id);
3060 }
3061 return $children;
3062 break;
3063
3064 default:
8388ade8 3065 error('This is an unknown context (' . $context->contextlevel . ') in get_child_contexts!');
cdfa3035 3066 return false;
3067 }
3068}
3069
3070
759ac72d 3071/**
3072 * Gets a string for sql calls, searching for stuff in this context or above
ea8158c1 3073 * @param object $context
3074 * @return string
3075 */
3076function get_related_contexts_string($context) {
3077 if ($parents = get_parent_contexts($context)) {
eef868d1 3078 return (' IN ('.$context->id.','.implode(',', $parents).')');
ea8158c1 3079 } else {
3080 return (' ='.$context->id);
3081 }
3082}
759ac72d 3083
3084
bbbf2d40 3085/**
3086 * This function gets the capability of a role in a given context.
3087 * It is needed when printing override forms.
3088 * @param int $contextid
bbbf2d40 3089 * @param string $capability
3090 * @param array $capabilities - array loaded using role_context_capabilities
3091 * @return int (allow, prevent, prohibit, inherit)
3092 */
bbbf2d40 3093function get_role_context_capability($contextid, $capability, $capabilities) {
759ac72d 3094 if (isset($capabilities[$contextid][$capability])) {
3095 return $capabilities[$contextid][$capability];
3096 }
3097 else {
3098 return false;
3099 }
bbbf2d40 3100}
3101
3102
cee0901c 3103/**
3104 * Returns the human-readable, translated version of the capability.
3105 * Basically a big switch statement.
3106 * @param $capabilityname - e.g. mod/choice:readresponses
3107 */
ceb83c70 3108function get_capability_string($capabilityname) {
eef868d1 3109
cee0901c 3110 // Typical capabilityname is mod/choice:readresponses
ceb83c70 3111
3112 $names = split('/', $capabilityname);
3113 $stringname = $names[1]; // choice:readresponses
eef868d1 3114 $components = split(':', $stringname);
ceb83c70 3115 $componentname = $components[0]; // choice
98882637 3116
3117 switch ($names[0]) {
3118 case 'mod':
ceb83c70 3119 $string = get_string($stringname, $componentname);
98882637 3120 break;
eef868d1 3121
98882637 3122 case 'block':
ceb83c70 3123 $string = get_string($stringname, 'block_'.$componentname);
98882637 3124 break;
ceb83c70 3125
98882637 3126 case 'moodle':
ceb83c70 3127 $string = get_string($stringname, 'role');
98882637 3128 break;
eef868d1 3129
98882637 3130 case 'enrol':
ceb83c70 3131 $string = get_string($stringname, 'enrol_'.$componentname);
eef868d1 3132 break;
ae628043 3133
3134 case 'format':
3135 $string = get_string($stringname, 'format_'.$componentname);
3136 break;
eef868d1 3137
98882637 3138 default:
ceb83c70 3139 $string = get_string($stringname);
eef868d1 3140 break;
3141
98882637 3142 }
ceb83c70 3143 return $string;
bbbf2d40 3144}
3145
3146
cee0901c 3147/**
3148 * This gets the mod/block/course/core etc strings.
3149 * @param $component
3150 * @param $contextlevel
3151 */
bbbf2d40 3152function get_component_string($component, $contextlevel) {
3153
98882637 3154 switch ($contextlevel) {
bbbf2d40 3155
98882637 3156 case CONTEXT_SYSTEM:
be382aaf 3157 if (preg_match('|^enrol/|', $component)) {
3158 $langname = str_replace('/', '_', $component);
3159 $string = get_string('enrolname', $langname);
f3652521 3160 } else if (preg_match('|^block/|', $component)) {
3161 $langname = str_replace('/', '_', $component);
3162 $string = get_string('blockname', $langname);
69eb59f2 3163 } else {
3164 $string = get_string('coresystem');
3165 }
bbbf2d40 3166 break;
3167
3168 case CONTEXT_PERSONAL:
98882637 3169 $string = get_string('personal');
bbbf2d40 3170 break;
3171
4b10f08b 3172 case CONTEXT_USER:
98882637 3173 $string = get_string('users');
bbbf2d40 3174 break;
3175
3176 case CONTEXT_COURSECAT:
98882637 3177 $string = get_string('categories');
bbbf2d40 3178 break;
3179
3180 case CONTEXT_COURSE:
98882637 3181 $string = get_string('course');
bbbf2d40 3182 break;
3183
3184 case CONTEXT_GROUP:
98882637 3185 $string = get_string('group');
bbbf2d40 3186 break;
3187
3188 case CONTEXT_MODULE:
98882637 3189 $string = get_string('modulename', basename($component));
bbbf2d40 3190 break;
3191
3192 case CONTEXT_BLOCK:
6db71242 3193 $string = get_string('blockname', 'block_'.basename($component));
bbbf2d40 3194 break;
3195
3196 default:
8388ade8 3197 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
bbbf2d40 3198 return false;
eef868d1 3199
98882637 3200 }
98882637 3201 return $string;
bbbf2d40 3202}
cee0901c 3203
759ac72d 3204/**
3205 * Gets the list of roles assigned to this context and up (parents)
945f88ca 3206 * @param object $context
3997cb40 3207 * @param view - set to true when roles are pulled for display only
3208 * this is so that we can filter roles with no visible
3209 * assignment, for example, you might want to "hide" all
3210 * course creators when browsing the course participants
3211 * list.
945f88ca 3212 * @return array
3213 */
3997cb40 3214function get_roles_used_in_context($context, $view = false) {
e4dd3222 3215
3216 global $CFG;
3997cb40 3217
3218 // filter for roles with all hidden assignments
3219 // no need to return when only pulling roles for reviewing
3220 // e.g. participants page.
d42c64ba 3221 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
2d9965e1 3222 $contextlist = get_related_contexts_string($context);
eef868d1 3223
759ac72d 3224 $sql = "SELECT DISTINCT r.id,
3225 r.name,
3226 r.shortname,