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