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