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