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