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