Help file: Uploading Authorize.net CSV file; Merged from MOODLE_17_STABLE.
[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
ba8d8027 1215 $adminrole = create_role(get_string('administrator'), 'admin',
459c1ff1 1216 get_string('administratordescription'), 'moodle/legacy:admin');
ba8d8027 1217 $coursecreatorrole = create_role(get_string('coursecreators'), 'coursecreator',
459c1ff1 1218 get_string('coursecreatorsdescription'), 'moodle/legacy:coursecreator');
ba8d8027 1219 $editteacherrole = create_role(get_string('defaultcourseteacher'), 'editingteacher',
459c1ff1 1220 get_string('defaultcourseteacherdescription'), 'moodle/legacy:editingteacher');
ba8d8027 1221 $noneditteacherrole = create_role(get_string('noneditingteacher'), 'teacher',
459c1ff1 1222 get_string('noneditingteacherdescription'), 'moodle/legacy:teacher');
ba8d8027 1223 $studentrole = create_role(get_string('defaultcoursestudent'), 'student',
459c1ff1 1224 get_string('defaultcoursestudentdescription'), 'moodle/legacy:student');
ba8d8027 1225 $guestrole = create_role(get_string('guest'), 'guest',
459c1ff1 1226 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;
1876 $newra->groupid = $groupid;
1877
1878 $newra->hidden = $hidden;
f44152f4 1879 $newra->enrol = $enrol;
a9e1c058 1880 $newra->timestart = $timestart;
1881 $newra->timeend = $timeend;
1882 $newra->timemodified = time();
1883 $newra->modifier = empty($USER->id) ? 0 : $USER->id;
1884
9ebcb4d2 1885 $success = insert_record('role_assignments', $newra);
a9e1c058 1886
1887 } else { // We already have one, just update it
1888
1889 $newra->id = $ra->id;
1890 $newra->hidden = $hidden;
f44152f4 1891 $newra->enrol = $enrol;
a9e1c058 1892 $newra->timestart = $timestart;
1893 $newra->timeend = $timeend;
1894 $newra->timemodified = time();
1895 $newra->modifier = empty($USER->id) ? 0 : $USER->id;
1896
9ebcb4d2 1897 $success = update_record('role_assignments', $newra);
1898 }
1899
7700027f 1900 if ($success) { /// Role was assigned, so do some other things
1901
1902 /// If the user is the current user, then reload the capabilities too.
1903 if (!empty($USER->id) && $USER->id == $userid) {
2f1a4248 1904 load_all_capabilities();
7700027f 1905 }
9b5d7a46 1906
0f161e1f 1907 /// Ask all the modules if anything needs to be done for this user
1908 if ($mods = get_list_of_plugins('mod')) {
1909 foreach ($mods as $mod) {
1910 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
1911 $functionname = $mod.'_role_assign';
1912 if (function_exists($functionname)) {
1913 $functionname($userid, $context);
1914 }
1915 }
1916 }
1917
1918 /// Make sure they have an entry in user_lastaccess for courses they can access
1919 // role_add_lastaccess_entries($userid, $context);
a9e1c058 1920 }
eef868d1 1921
4e5f3064 1922 /// now handle metacourse role assignments if in course context
aad2ba95 1923 if ($success and $context->contextlevel == CONTEXT_COURSE) {
4e5f3064 1924 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
1925 foreach ($parents as $parent) {
1aad4310 1926 sync_metacourse($parent->parent_course);
4e5f3064 1927 }
1928 }
1929 }
6eb4f823 1930
1931 return $success;
bbbf2d40 1932}
1933
1934
1935/**
1dc1f037 1936 * Deletes one or more role assignments. You must specify at least one parameter.
bbbf2d40 1937 * @param $roleid
1938 * @param $userid
1939 * @param $groupid
1940 * @param $contextid
1941 * @return boolean - success or failure
1942 */
1dc1f037 1943function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0) {
d74067e8 1944
1945 global $USER, $CFG;
eef868d1 1946
4e5f3064 1947 $success = true;
d74067e8 1948
1dc1f037 1949 $args = array('roleid', 'userid', 'groupid', 'contextid');
1950 $select = array();
1951 foreach ($args as $arg) {
1952 if ($$arg) {
1953 $select[] = $arg.' = '.$$arg;
1954 }
1955 }
d74067e8 1956
1dc1f037 1957 if ($select) {
4e5f3064 1958 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
1959 $mods = get_list_of_plugins('mod');
1960 foreach($ras as $ra) {
86e2c51d 1961 /// infinite loop protection when deleting recursively
1962 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
1963 continue;
1964 }
4e5f3064 1965 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
86e2c51d 1966
4e5f3064 1967 /// If the user is the current user, then reload the capabilities too.
1968 if (!empty($USER->id) && $USER->id == $ra->userid) {
2f1a4248 1969 load_all_capabilities();
4e5f3064 1970 }
1971 $context = get_record('context', 'id', $ra->contextid);
0f161e1f 1972
1973 /// Ask all the modules if anything needs to be done for this user
4e5f3064 1974 foreach ($mods as $mod) {
1975 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
1976 $functionname = $mod.'_role_unassign';
1977 if (function_exists($functionname)) {
1978 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
1979 }
1980 }
1981
1982 /// now handle metacourse role unassigment and removing from goups if in course context
aad2ba95 1983 if (!empty($context) and $context->contextlevel == CONTEXT_COURSE) {
4e5f3064 1984 //remove from groups when user has no role
1985 $roles = get_user_roles($context, $ra->userid, true);
1986 if (empty($roles)) {
1987 if ($groups = get_groups($context->instanceid, $ra->userid)) {
1988 foreach ($groups as $group) {
1989 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
1990 }
1991 }
1992 }
1aad4310 1993 //unassign roles in metacourses if needed
4e5f3064 1994 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
1995 foreach ($parents as $parent) {
1aad4310 1996 sync_metacourse($parent->parent_course);
0f161e1f 1997 }
1998 }
0f161e1f 1999 }
2000 }
d74067e8 2001 }
1dc1f037 2002 }
4e5f3064 2003
2004 return $success;
bbbf2d40 2005}
2006
eef868d1 2007/*
2008 * A convenience function to take care of the common case where you
b963384f 2009 * just want to enrol someone using the default role into a course
2010 *
2011 * @param object $course
2012 * @param object $user
2013 * @param string $enrol - the plugin used to do this enrolment
2014 */
2015function enrol_into_course($course, $user, $enrol) {
2016
2017 if ($course->enrolperiod) {
2018 $timestart = time();
2019 $timeend = time() + $course->enrolperiod;
2020 } else {
2021 $timestart = $timeend = 0;
2022 }
2023
2024 if ($role = get_default_course_role($course)) {
c4381ef5 2025
2026 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2027
e2183037 2028 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
b963384f 2029 return false;
2030 }
eef868d1 2031
b963384f 2032 email_welcome_message_to_user($course, $user);
eef868d1 2033
b963384f 2034 add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
2035
2036 return true;
2037 }
2038
2039 return false;
2040}
2041
0f161e1f 2042/**
2043 * Add last access times to user_lastaccess as required
2044 * @param $userid
2045 * @param $context
2046 * @return boolean - success or failure
2047 */
2048function role_add_lastaccess_entries($userid, $context) {
2049
2050 global $USER, $CFG;
2051
aad2ba95 2052 if (empty($context->contextlevel)) {
0f161e1f 2053 return false;
2054 }
2055
2056 $lastaccess = new object; // Reusable object below
2057 $lastaccess->userid = $userid;
2058 $lastaccess->timeaccess = 0;
2059
aad2ba95 2060 switch ($context->contextlevel) {
0f161e1f 2061
2062 case CONTEXT_SYSTEM: // For the whole site
2063 if ($courses = get_record('course')) {
2064 foreach ($courses as $course) {
2065 $lastaccess->courseid = $course->id;
2066 role_set_lastaccess($lastaccess);
2067 }
2068 }
2069 break;
2070
2071 case CONTEXT_CATEGORY: // For a whole category
2072 if ($courses = get_record('course', 'category', $context->instanceid)) {
2073 foreach ($courses as $course) {
2074 $lastaccess->courseid = $course->id;
2075 role_set_lastaccess($lastaccess);
2076 }
2077 }
2078 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
2079 foreach ($categories as $category) {
2080 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
2081 role_add_lastaccess_entries($userid, $subcontext);
2082 }
2083 }
2084 break;
eef868d1 2085
0f161e1f 2086
2087 case CONTEXT_COURSE: // For a whole course
2088 if ($course = get_record('course', 'id', $context->instanceid)) {
2089 $lastaccess->courseid = $course->id;
2090 role_set_lastaccess($lastaccess);
2091 }
2092 break;
2093 }
2094}
2095
2096/**
2097 * Delete last access times from user_lastaccess as required
2098 * @param $userid
2099 * @param $context
2100 * @return boolean - success or failure
2101 */
2102function role_remove_lastaccess_entries($userid, $context) {
2103
2104 global $USER, $CFG;
2105
2106}
2107
bbbf2d40 2108
2109/**
2110 * Loads the capability definitions for the component (from file). If no
2111 * capabilities are defined for the component, we simply return an empty array.
2112 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2113 * @return array of capabilities
2114 */
2115function load_capability_def($component) {
2116 global $CFG;
2117
2118 if ($component == 'moodle') {
2119 $defpath = $CFG->libdir.'/db/access.php';
2120 $varprefix = 'moodle';
2121 } else {
0c4d9f49 2122 $compparts = explode('/', $component);
eef868d1 2123
0c4d9f49 2124 if ($compparts[0] == 'block') {
2125 // Blocks are an exception. Blocks directory is 'blocks', and not
2126 // 'block'. So we need to jump through hoops.
2127 $defpath = $CFG->dirroot.'/'.$compparts[0].
2128 's/'.$compparts[1].'/db/access.php';
2129 $varprefix = $compparts[0].'_'.$compparts[1];
2130 } else {
2131 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
2132 $varprefix = str_replace('/', '_', $component);
2133 }
bbbf2d40 2134 }
2135 $capabilities = array();
eef868d1 2136
bbbf2d40 2137 if (file_exists($defpath)) {
2138 require_once($defpath);
2139 $capabilities = ${$varprefix.'_capabilities'};
2140 }
2141 return $capabilities;
2142}
2143
2144
2145/**
2146 * Gets the capabilities that have been cached in the database for this
2147 * component.
2148 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2149 * @return array of capabilities
2150 */
2151function get_cached_capabilities($component='moodle') {
2152 if ($component == 'moodle') {
2153 $storedcaps = get_records_select('capabilities',
2154 "name LIKE 'moodle/%:%'");
2155 } else {
2156 $storedcaps = get_records_select('capabilities',
2157 "name LIKE '$component:%'");
2158 }
2159 return $storedcaps;
2160}
2161
2162
2163/**
2164 * Updates the capabilities table with the component capability definitions.
2165 * If no parameters are given, the function updates the core moodle
2166 * capabilities.
2167 *
2168 * Note that the absence of the db/access.php capabilities definition file
2169 * will cause any stored capabilities for the component to be removed from
eef868d1 2170 * the database.
bbbf2d40 2171 *
2172 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2173 * @return boolean
2174 */
2175function update_capabilities($component='moodle') {
eef868d1 2176
bbbf2d40 2177 $storedcaps = array();
be4486da 2178
2179 $filecaps = load_capability_def($component);
bbbf2d40 2180 $cachedcaps = get_cached_capabilities($component);
2181 if ($cachedcaps) {
2182 foreach ($cachedcaps as $cachedcap) {
2183 array_push($storedcaps, $cachedcap->name);
17e5635c 2184 // update risk bitmasks in existing capabilities if needed
be4486da 2185 if (array_key_exists($cachedcap->name, $filecaps)) {
2186 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2b531945 2187 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
be4486da 2188 }
2189 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2190 $updatecap = new object;
2191 $updatecap->id = $cachedcap->id;
2192 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2193 if (!update_record('capabilities', $updatecap)) {
2194 return false;
2195 }
2196 }
2197 }
bbbf2d40 2198 }
2199 }
be4486da 2200
bbbf2d40 2201 // Are there new capabilities in the file definition?
2202 $newcaps = array();
eef868d1 2203
bbbf2d40 2204 foreach ($filecaps as $filecap => $def) {
eef868d1 2205 if (!$storedcaps ||
bbbf2d40 2206 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2b531945 2207 if (!array_key_exists('riskbitmask', $def)) {
2208 $def['riskbitmask'] = 0; // no risk if not specified
2209 }
bbbf2d40 2210 $newcaps[$filecap] = $def;
2211 }
2212 }
2213 // Add new capabilities to the stored definition.
2214 foreach ($newcaps as $capname => $capdef) {
2215 $capability = new object;
2216 $capability->name = $capname;
2217 $capability->captype = $capdef['captype'];
2218 $capability->contextlevel = $capdef['contextlevel'];
2219 $capability->component = $component;
be4486da 2220 $capability->riskbitmask = $capdef['riskbitmask'];
eef868d1 2221
bbbf2d40 2222 if (!insert_record('capabilities', $capability, false, 'id')) {
2223 return false;
2224 }
eef868d1 2225
bbbf2d40 2226 // Do we need to assign the new capabilities to roles that have the
2227 // legacy capabilities moodle/legacy:* as well?
2228 if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
2229 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2e85fffe 2230 notify('Could not assign legacy capabilities for '.$capname);
bbbf2d40 2231 }
2232 }
2233 // Are there any capabilities that have been removed from the file
2234 // definition that we need to delete from the stored capabilities and
2235 // role assignments?
2236 capabilities_cleanup($component, $filecaps);
eef868d1 2237
bbbf2d40 2238 return true;
2239}
2240
2241
2242/**
2243 * Deletes cached capabilities that are no longer needed by the component.
2244 * Also unassigns these capabilities from any roles that have them.
2245 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2246 * @param $newcapdef - array of the new capability definitions that will be
2247 * compared with the cached capabilities
2248 * @return int - number of deprecated capabilities that have been removed
2249 */
2250function capabilities_cleanup($component, $newcapdef=NULL) {
eef868d1 2251
bbbf2d40 2252 $removedcount = 0;
eef868d1 2253
bbbf2d40 2254 if ($cachedcaps = get_cached_capabilities($component)) {
2255 foreach ($cachedcaps as $cachedcap) {
2256 if (empty($newcapdef) ||
2257 array_key_exists($cachedcap->name, $newcapdef) === false) {
eef868d1 2258
bbbf2d40 2259 // Remove from capabilities cache.
2260 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
2261 error('Could not delete deprecated capability '.$cachedcap->name);
2262 } else {
2263 $removedcount++;
2264 }
2265 // Delete from roles.
2266 if($roles = get_roles_with_capability($cachedcap->name)) {
2267 foreach($roles as $role) {
46943f7b 2268 if (!unassign_capability($cachedcap->name, $role->id)) {
bbbf2d40 2269 error('Could not unassign deprecated capability '.
2270 $cachedcap->name.' from role '.$role->name);
2271 }
2272 }
2273 }
2274 } // End if.
2275 }
2276 }
2277 return $removedcount;
2278}
2279
2280
2281
cee0901c 2282/****************
2283 * UI FUNCTIONS *
2284 ****************/
bbbf2d40 2285
2286
2287/**
2288 * prints human readable context identifier.
2289 */
0468976c 2290function print_context_name($context) {
340ea4e8 2291
ec0810ee 2292 $name = '';
aad2ba95 2293 switch ($context->contextlevel) {
ec0810ee 2294
bbbf2d40 2295 case CONTEXT_SYSTEM: // by now it's a definite an inherit
ec0810ee 2296 $name = get_string('site');
340ea4e8 2297 break;
bbbf2d40 2298
2299 case CONTEXT_PERSONAL:
ec0810ee 2300 $name = get_string('personal');
340ea4e8 2301 break;
2302
4b10f08b 2303 case CONTEXT_USER:
ec0810ee 2304 if ($user = get_record('user', 'id', $context->instanceid)) {
2305 $name = get_string('user').': '.fullname($user);
2306 }
340ea4e8 2307 break;
2308
bbbf2d40 2309 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
ec0810ee 2310 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
2311 $name = get_string('category').': '.$category->name;
2312 }
340ea4e8 2313 break;
bbbf2d40 2314
2315 case CONTEXT_COURSE: // 1 to 1 to course cat
ec0810ee 2316 if ($course = get_record('course', 'id', $context->instanceid)) {
2317 $name = get_string('course').': '.$course->fullname;
2318 }
340ea4e8 2319 break;
bbbf2d40 2320
2321 case CONTEXT_GROUP: // 1 to 1 to course
ec0810ee 2322 if ($group = get_record('groups', 'id', $context->instanceid)) {
2323 $name = get_string('group').': '.$group->name;
2324 }
340ea4e8 2325 break;
bbbf2d40 2326
2327 case CONTEXT_MODULE: // 1 to 1 to course
98882637 2328 if ($cm = get_record('course_modules','id',$context->instanceid)) {
2329 if ($module = get_record('modules','id',$cm->module)) {
2330 if ($mod = get_record($module->name, 'id', $cm->instance)) {
ec0810ee 2331 $name = get_string('activitymodule').': '.$mod->name;
98882637 2332 }
ec0810ee 2333 }
2334 }
340ea4e8 2335 break;
bbbf2d40 2336
2337 case CONTEXT_BLOCK: // 1 to 1 to course
98882637 2338 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
2339 if ($block = get_record('block','id',$blockinstance->blockid)) {
91be52d7 2340 global $CFG;
2341 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
2342 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
2343 $blockname = "block_$block->name";
2344 if ($blockobject = new $blockname()) {
2345 $name = $blockobject->title.' ('.get_string('block').')';
2346 }
ec0810ee 2347 }
2348 }
340ea4e8 2349 break;
bbbf2d40 2350
2351 default:
2352 error ('This is an unknown context!');
340ea4e8 2353 return false;
2354
2355 }
340ea4e8 2356 return $name;
bbbf2d40 2357}
2358
2359
2360/**
eef868d1 2361 * Extracts the relevant capabilities given a contextid.
bbbf2d40 2362 * All case based, example an instance of forum context.
2363 * Will fetch all forum related capabilities, while course contexts
2364 * Will fetch all capabilities
0468976c 2365 * @param object context
bbbf2d40 2366 * @return array();
2367 *
2368 * capabilities
2369 * `name` varchar(150) NOT NULL,
2370 * `captype` varchar(50) NOT NULL,
2371 * `contextlevel` int(10) NOT NULL,
2372 * `component` varchar(100) NOT NULL,
2373 */
0468976c 2374function fetch_context_capabilities($context) {
eef868d1 2375
98882637 2376 global $CFG;
bbbf2d40 2377
2378 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
eef868d1 2379
aad2ba95 2380 switch ($context->contextlevel) {
bbbf2d40 2381
98882637 2382 case CONTEXT_SYSTEM: // all
2383 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2384 break;
2385
2386 case CONTEXT_PERSONAL:
0a8a95c9 2387 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
bbbf2d40 2388 break;
eef868d1 2389
4b10f08b 2390 case CONTEXT_USER:
8020a016 2391 $SQL = "SELECT *
2392 FROM {$CFG->prefix}capabilities
2393 WHERE contextlevel = ".CONTEXT_USER;
bbbf2d40 2394 break;
eef868d1 2395
bbbf2d40 2396 case CONTEXT_COURSECAT: // all
98882637 2397 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2398 break;
2399
2400 case CONTEXT_COURSE: // all
98882637 2401 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2402 break;
2403
2404 case CONTEXT_GROUP: // group caps
2405 break;
2406
2407 case CONTEXT_MODULE: // mod caps
98882637 2408 $cm = get_record('course_modules', 'id', $context->instanceid);
2409 $module = get_record('modules', 'id', $cm->module);
eef868d1 2410
98882637 2411 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
2412 and component = 'mod/$module->name'";
bbbf2d40 2413 break;
2414
2415 case CONTEXT_BLOCK: // block caps
98882637 2416 $cb = get_record('block_instance', 'id', $context->instanceid);
2417 $block = get_record('block', 'id', $cb->blockid);
eef868d1 2418
98882637 2419 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
2420 and component = 'block/$block->name'";
bbbf2d40 2421 break;
2422
2423 default:
2424 return false;
2425 }
2426
16e2e2f3 2427 if (!$records = get_records_sql($SQL.' '.$sort)) {
2428 $records = array();
2429 }
ba8d8027 2430
2431/// the rest of code is a bit hacky, think twice before modifying it :-(
69eb59f2 2432
2433 // special sorting of core system capabiltites and enrollments
e9c82dca 2434 if (in_array($context->contextlevel, array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE))) {
69eb59f2 2435 $first = array();
2436 foreach ($records as $key=>$record) {
2437 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
2438 $first[$key] = $record;
2439 unset($records[$key]);
2440 } else if (count($first)){
2441 break;
2442 }
2443 }
2444 if (count($first)) {
2445 $records = $first + $records; // merge the two arrays keeping the keys
2446 }
ba8d8027 2447 } else {
2448 $contextindependentcaps = fetch_context_independent_capabilities();
2449 $records = array_merge($contextindependentcaps, $records);
69eb59f2 2450 }
ba8d8027 2451
bbbf2d40 2452 return $records;
eef868d1 2453
bbbf2d40 2454}
2455
2456
759ac72d 2457/**
2458 * Gets the context-independent capabilities that should be overrridable in
2459 * any context.
2460 * @return array of capability records from the capabilities table.
2461 */
2462function fetch_context_independent_capabilities() {
eef868d1 2463
17e5635c 2464 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
759ac72d 2465 $contextindependentcaps = array(
2466 'moodle/site:accessallgroups'
2467 );
2468
2469 $records = array();
eef868d1 2470
759ac72d 2471 foreach ($contextindependentcaps as $capname) {
2472 $record = get_record('capabilities', 'name', $capname);
2473 array_push($records, $record);
2474 }
2475 return $records;
2476}
2477
2478
bbbf2d40 2479/**
2480 * This function pulls out all the resolved capabilities (overrides and
759ac72d 2481 * defaults) of a role used in capability overrides in contexts at a given
bbbf2d40 2482 * context.
0a8a95c9 2483 * @param obj $context
bbbf2d40 2484 * @param int $roleid
dc558690 2485 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
bbbf2d40 2486 * @return array
2487 */
1648afb2 2488function role_context_capabilities($roleid, $context, $cap='') {
dc558690 2489 global $CFG;
eef868d1 2490
8521d83a 2491 $contexts = get_parent_contexts($context);
2492 $contexts[] = $context->id;
98882637 2493 $contexts = '('.implode(',', $contexts).')';
eef868d1 2494
1648afb2 2495 if ($cap) {
e4697bf7 2496 $search = " AND rc.capability = '$cap' ";
1648afb2 2497 } else {
eef868d1 2498 $search = '';
1648afb2 2499 }
eef868d1 2500
2501 $SQL = "SELECT rc.*
2502 FROM {$CFG->prefix}role_capabilities rc,
dc558690 2503 {$CFG->prefix}context c
2504 WHERE rc.contextid in $contexts
2505 AND rc.roleid = $roleid
2506 AND rc.contextid = c.id $search
aad2ba95 2507 ORDER BY c.contextlevel DESC,
eef868d1 2508 rc.capability DESC";
759ac72d 2509
98882637 2510 $capabilities = array();
eef868d1 2511
4729012f 2512 if ($records = get_records_sql($SQL)) {
2513 // We are traversing via reverse order.
2514 foreach ($records as $record) {
2515 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2516 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2517 $capabilities[$record->capability] = $record->permission;
eef868d1 2518 }
4729012f 2519 }
98882637 2520 }
2521 return $capabilities;
bbbf2d40 2522}
2523
bbbf2d40 2524/**
eef868d1 2525 * Recursive function which, given a context, find all parent context ids,
bbbf2d40 2526 * and return the array in reverse order, i.e. parent first, then grand
2527 * parent, etc.
2528 * @param object $context
2529 * @return array()
2530 */
bbbf2d40 2531function get_parent_contexts($context) {
759ac72d 2532
aad2ba95 2533 switch ($context->contextlevel) {
bbbf2d40 2534
2535 case CONTEXT_SYSTEM: // no parent
957861f7 2536 return array();
bbbf2d40 2537 break;
2538
2539 case CONTEXT_PERSONAL:
21c9bace 2540 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
957861f7 2541 return array();
2542 } else {
2543 return array($parent->id);
2544 }
bbbf2d40 2545 break;
eef868d1 2546
4b10f08b 2547 case CONTEXT_USER:
21c9bace 2548 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
957861f7 2549 return array();
2550 } else {
2551 return array($parent->id);
2552 }
bbbf2d40 2553 break;
eef868d1 2554
bbbf2d40 2555 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
957861f7 2556 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
2557 return array();
2558 }
c5ddc3fd 2559 if (!empty($coursecat->parent)) { // return parent value if exist
bbbf2d40 2560 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
2561 return array_merge(array($parent->id), get_parent_contexts($parent));
2562 } else { // else return site value
21c9bace 2563 $parent = get_context_instance(CONTEXT_SYSTEM);
bbbf2d40 2564 return array($parent->id);
2565 }
2566 break;
2567
2568 case CONTEXT_COURSE: // 1 to 1 to course cat
957861f7 2569 if (!$course = get_record('course','id',$context->instanceid)) {
2570 return array();
2571 }
1936c10e 2572 if ($course->id != SITEID) {
957861f7 2573 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2574 return array_merge(array($parent->id), get_parent_contexts($parent));
2575 } else {
40a2a15f 2576 // Yu: Separating site and site course context
2577 $parent = get_context_instance(CONTEXT_SYSTEM);
2578 return array($parent->id);
957861f7 2579 }
bbbf2d40 2580 break;
2581
2582 case CONTEXT_GROUP: // 1 to 1 to course
957861f7 2583 if (!$group = get_record('groups','id',$context->instanceid)) {
2584 return array();
2585 }
2586 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
2587 return array_merge(array($parent->id), get_parent_contexts($parent));
2588 } else {
2589 return array();
2590 }
bbbf2d40 2591 break;
2592
2593 case CONTEXT_MODULE: // 1 to 1 to course
957861f7 2594 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
2595 return array();
2596 }
2597 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
2598 return array_merge(array($parent->id), get_parent_contexts($parent));
2599 } else {
2600 return array();
2601 }
bbbf2d40 2602 break;
2603
2604 case CONTEXT_BLOCK: // 1 to 1 to course
957861f7 2605 if (!$block = get_record('block_instance','id',$context->instanceid)) {
2606 return array();
2607 }
2608 if ($parent = get_context_instance(CONTEXT_COURSE, $block->pageid)) {
2609 return array_merge(array($parent->id), get_parent_contexts($parent));
2610 } else {
2611 return array();
2612 }
bbbf2d40 2613 break;
2614
2615 default:
957861f7 2616 error('This is an unknown context!');
bbbf2d40 2617 return false;
2618 }
bbbf2d40 2619}
2620
759ac72d 2621
2622/**
2623 * Gets a string for sql calls, searching for stuff in this context or above
ea8158c1 2624 * @param object $context
2625 * @return string
2626 */
2627function get_related_contexts_string($context) {
2628 if ($parents = get_parent_contexts($context)) {
eef868d1 2629 return (' IN ('.$context->id.','.implode(',', $parents).')');
ea8158c1 2630 } else {
2631 return (' ='.$context->id);
2632 }
2633}
759ac72d 2634
2635
bbbf2d40 2636/**
2637 * This function gets the capability of a role in a given context.
2638 * It is needed when printing override forms.
2639 * @param int $contextid
bbbf2d40 2640 * @param string $capability
2641 * @param array $capabilities - array loaded using role_context_capabilities
2642 * @return int (allow, prevent, prohibit, inherit)
2643 */
bbbf2d40 2644function get_role_context_capability($contextid, $capability, $capabilities) {
759ac72d 2645 if (isset($capabilities[$contextid][$capability])) {
2646 return $capabilities[$contextid][$capability];
2647 }
2648 else {
2649 return false;
2650 }
bbbf2d40 2651}
2652
2653
cee0901c 2654/**
2655 * Returns the human-readable, translated version of the capability.
2656 * Basically a big switch statement.
2657 * @param $capabilityname - e.g. mod/choice:readresponses
2658 */
ceb83c70 2659function get_capability_string($capabilityname) {
eef868d1 2660
cee0901c 2661 // Typical capabilityname is mod/choice:readresponses
ceb83c70 2662
2663 $names = split('/', $capabilityname);
2664 $stringname = $names[1]; // choice:readresponses
eef868d1 2665 $components = split(':', $stringname);
ceb83c70 2666 $componentname = $components[0]; // choice
98882637 2667
2668 switch ($names[0]) {
2669 case 'mod':
ceb83c70 2670 $string = get_string($stringname, $componentname);
98882637 2671 break;
eef868d1 2672
98882637 2673 case 'block':
ceb83c70 2674 $string = get_string($stringname, 'block_'.$componentname);
98882637 2675 break;
ceb83c70 2676
98882637 2677 case 'moodle':
ceb83c70 2678 $string = get_string($stringname, 'role');
98882637 2679 break;
eef868d1 2680
98882637 2681 case 'enrol':
ceb83c70 2682 $string = get_string($stringname, 'enrol_'.$componentname);
eef868d1 2683 break;
2684
98882637 2685 default:
ceb83c70 2686 $string = get_string($stringname);
eef868d1 2687 break;
2688
98882637 2689 }
ceb83c70 2690 return $string;
bbbf2d40 2691}
2692
2693
cee0901c 2694/**
2695 * This gets the mod/block/course/core etc strings.
2696 * @param $component
2697 * @param $contextlevel
2698 */
bbbf2d40 2699function get_component_string($component, $contextlevel) {
2700
98882637 2701 switch ($contextlevel) {
bbbf2d40 2702
98882637 2703 case CONTEXT_SYSTEM:
be382aaf 2704 if (preg_match('|^enrol/|', $component)) {
2705 $langname = str_replace('/', '_', $component);
2706 $string = get_string('enrolname', $langname);
f3652521 2707 } else if (preg_match('|^block/|', $component)) {
2708 $langname = str_replace('/', '_', $component);
2709 $string = get_string('blockname', $langname);
69eb59f2 2710 } else {
2711 $string = get_string('coresystem');
2712 }
bbbf2d40 2713 break;
2714
2715 case CONTEXT_PERSONAL:
98882637 2716 $string = get_string('personal');
bbbf2d40 2717 break;
2718
4b10f08b 2719 case CONTEXT_USER:
98882637 2720 $string = get_string('users');
bbbf2d40 2721 break;
2722
2723 case CONTEXT_COURSECAT:
98882637 2724 $string = get_string('categories');
bbbf2d40 2725 break;
2726
2727 case CONTEXT_COURSE:
98882637 2728 $string = get_string('course');
bbbf2d40 2729 break;
2730
2731 case CONTEXT_GROUP:
98882637 2732 $string = get_string('group');
bbbf2d40 2733 break;
2734
2735 case CONTEXT_MODULE:
98882637 2736 $string = get_string('modulename', basename($component));
bbbf2d40 2737 break;
2738
2739 case CONTEXT_BLOCK:
98882637 2740 $string = get_string('blockname', 'block_'.$component.'.php');
bbbf2d40 2741 break;
2742
2743 default:
2744 error ('This is an unknown context!');
2745 return false;
eef868d1 2746
98882637 2747 }
98882637 2748 return $string;
bbbf2d40 2749}
cee0901c 2750
759ac72d 2751/**
2752 * Gets the list of roles assigned to this context and up (parents)
945f88ca 2753 * @param object $context
3997cb40 2754 * @param view - set to true when roles are pulled for display only
2755 * this is so that we can filter roles with no visible
2756 * assignment, for example, you might want to "hide" all
2757 * course creators when browsing the course participants
2758 * list.
945f88ca 2759 * @return array
2760 */
3997cb40 2761function get_roles_used_in_context($context, $view = false) {
e4dd3222 2762
2763 global $CFG;
3997cb40 2764
2765 // filter for roles with all hidden assignments
2766 // no need to return when only pulling roles for reviewing
2767 // e.g. participants page.
d42c64ba 2768 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
2d9965e1 2769 $contextlist = get_related_contexts_string($context);
eef868d1 2770
759ac72d 2771 $sql = "SELECT DISTINCT r.id,
2772 r.name,
2773 r.shortname,
2774 r.sortorder
2775 FROM {$CFG->prefix}role_assignments ra,
eef868d1 2776 {$CFG->prefix}role r
2777 WHERE r.id = ra.roleid
759ac72d 2778 AND ra.contextid $contextlist
3997cb40 2779 $hiddensql
759ac72d 2780 ORDER BY r.sortorder ASC";
eef868d1 2781
759ac72d 2782 return get_records_sql($sql);
e4dd3222 2783}
2784
eef868d1 2785/** this function is used to print roles column in user profile page.
945f88ca 2786 * @param int userid
2787 * @param int contextid
2788 * @return string
2789 */
0a8a95c9 2790function get_user_roles_in_context($userid, $contextid){
2791 global $CFG;
eef868d1 2792
0a8a95c9 2793 $rolestring = '';
2794 $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';
2795 if ($roles = get_records_sql($SQL)) {
2796 foreach ($roles as $userrole) {
2797 $rolestring .= '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$userrole->contextid.'&amp;roleid='.$userrole->roleid.'">'.$userrole->name.'</a>, ';
eef868d1 2798 }
2799
0a8a95c9 2800 }
2801 return rtrim($rolestring, ', ');
2802}
68c52526 2803
2804
945f88ca 2805/**
2806 * Checks if a user can override capabilities of a particular role in this context
2807 * @param object $context
2808 * @param int targetroleid - the id of the role you want to override
2809 * @return boolean
2810 */
68c52526 2811function user_can_override($context, $targetroleid) {
2812 // first check if user has override capability
2813 // if not return false;
2814 if (!has_capability('moodle/role:override', $context)) {
eef868d1 2815 return false;
68c52526 2816 }
2817 // pull out all active roles of this user from this context(or above)
c0614051 2818 if ($userroles = get_user_roles($context)) {
2819 foreach ($userroles as $userrole) {
2820 // if any in the role_allow_override table, then it's ok
2821 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
2822 return true;
2823 }
68c52526 2824 }
2825 }
eef868d1 2826
68c52526 2827 return false;
eef868d1 2828
68c52526 2829}
2830
945f88ca 2831/**
2832 * Checks if a user can assign users to a particular role in this context
2833 * @param object $context
2834 * @param int targetroleid - the id of the role you want to assign users to
2835 * @return boolean
2836 */
68c52526 2837function user_can_assign($context, $targetroleid) {
eef868d1 2838
68c52526 2839 // first check if user has override capability
2840 // if not return false;
2841 if (!has_capability('moodle/role:assign', $context)) {
eef868d1 2842 return false;
68c52526 2843 }
2844 // pull out all active roles of this user from this context(or above)
c0614051 2845 if ($userroles = get_user_roles($context)) {
2846 foreach ($userroles as $userrole) {
2847 // if any in the role_allow_override table, then it's ok
2848 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
2849 return true;
2850 }
68c52526 2851 }
2852 }
eef868d1 2853
2854 return false;
68c52526 2855}
2856
ece4945b 2857/** Returns all site roles in correct sort order.
2858 *
2859 */
2860function get_all_roles() {
2861 return get_records('role', '', '', 'sortorder ASC');
2862}
2863
945f88ca 2864/**
2865 * gets all the user roles assigned in this context, or higher contexts
2866 * this is mainly used when checking if a user can assign a role, or overriding a role
2867 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2868 * allow_override tables
2869 * @param object $context
2870 * @param int $userid
b06334e8 2871 * @param view - set to true when roles are pulled for display only
2872 * this is so that we can filter roles with no visible
2873 * assignment, for example, you might want to "hide" all
2874 * course creators when browsing the course participants
2875 * list.
945f88ca 2876 * @return array
2877 */
b06334e8 2878function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
68c52526 2879
2880 global $USER, $CFG, $db;
c0614051 2881
2882 if (empty($userid)) {
2883 if (empty($USER->id)) {
2884 return array();
2885 }
2886 $userid = $USER->id;
2887 }
b06334e8 2888 // set up hidden sql
d42c64ba 2889 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
c0614051 2890
5b630667 2891 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
2892 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id.')';
c0614051 2893 } else {
5b630667 2894 $contexts = ' ra.contextid = \''.$context->id.'\'';
c0614051 2895 }
2896
31f26796 2897 return get_records_sql('SELECT ra.*, r.name, r.shortname
5b630667 2898 FROM '.$CFG->prefix.'role_assignments ra,
ec6eb110 2899 '.$CFG->prefix.'role r,
2900 '.$CFG->prefix.'context c
c0614051 2901 WHERE ra.userid = '.$userid.
5b630667 2902 ' AND ra.roleid = r.id
ec6eb110 2903 AND ra.contextid = c.id
b06334e8 2904 AND '.$contexts . $hiddensql .
ae9761ec 2905 ' ORDER BY '.$order);
68c52526 2906}
2907
945f88ca 2908/**
eef868d1 2909 * Creates a record in the allow_override table
945f88ca 2910 * @param int sroleid - source roleid
2911 * @param int troleid - target roleid
2912 * @return int - id or false
2913 */
2914function allow_override($sroleid, $troleid) {
ece4945b 2915 $record = new object();
945f88ca 2916 $record->roleid = $sroleid;
2917 $record->allowoverride = $troleid;
2918 return insert_record('role_allow_override', $record);
2919}
2920
2921/**
eef868d1 2922 * Creates a record in the allow_assign table
945f88ca 2923 * @param int sroleid - source roleid
2924 * @param int troleid - target roleid
2925 * @return int - id or false
2926 */
2927function allow_assign($sroleid, $troleid) {
ff64aaea 2928 $record = new object;
945f88ca 2929 $record->roleid = $sroleid;
2930 $record->allowassign = $troleid;
2931 return insert_record('role_allow_assign', $record);
2932}
2933
2934/**
ff64aaea 2935 * Gets a list of roles that this user can assign in this context
945f88ca 2936 * @param object $context
2937 * @return array
2938 */
5e67946d 2939function get_assignable_roles ($context, $field="name") {
945f88ca 2940
945f88ca 2941 $options = array();
ff64aaea 2942
ece4945b 2943 if ($roles = get_all_roles()) {
ff64aaea 2944 foreach ($roles as $role) {
2945 if (user_can_assign($context, $role->id)) {
5e67946d 2946 $options[$role->id] = strip_tags(format_string($role->{$field}, true));
ff64aaea 2947 }
945f88ca 2948 }
2949 }
2950 return $options;
2951}
2952
2953/**
ff64aaea 2954 * Gets a list of roles that this user can override in this context
945f88ca 2955 * @param object $context
2956 * @return array
2957 */
2958function get_overridable_roles ($context) {
2959
945f88ca 2960 $options = array();
ff64aaea 2961
ece4945b 2962 if ($roles = get_all_roles()) {
ff64aaea 2963 foreach ($roles as $role) {
2964 if (user_can_override($context, $role->id)) {
65b0c132 2965 $options[$role->id] = strip_tags(format_string($role->name, true));
ff64aaea 2966 }
945f88ca 2967 }
ff64aaea 2968 }
eef868d1 2969
2970 return $options;
945f88ca 2971}
1648afb2 2972
b963384f 2973/*
2974 * Returns a role object that is the default role for new enrolments
2975 * in a given course
2976 *
eef868d1 2977 * @param object $course
b963384f 2978 * @return object $role
2979 */
2980function get_default_course_role($course) {
2981 global $CFG;
2982
2983/// First let's take the default role the course may have
2984 if (!empty($course->defaultrole)) {
2985 if ($role = get_record('role', 'id', $course->defaultrole)) {
2986 return $role;
2987 }
2988 }
2989
2990/// Otherwise the site setting should tell us
2991 if ($CFG->defaultcourseroleid) {
2992 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid)) {
2993 return $role;
2994 }
2995 }
2996
2997/// It's unlikely we'll get here, but just in case, try and find a student role
2998 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
2999 return array_shift($studentroles); /// Take the first one
3000 }
3001
3002 return NULL;
3003}
3004
1648afb2 3005
3006/**
3007 * who has this capability in this context
3008 * does not handling user level resolving!!!
40a2a15f 3009 * (!)pleaes note if $fields is empty this function attempts to get u.*
3010 * which can get rather large.
1648afb2 3011 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
3012 * @param $context - object
3013 * @param $capability - string capability
3014 * @param $fields - fields to be pulled
3015 * @param $sort - the sort order
04417640 3016 * @param $limitfrom - number of records to skip (offset)
eef868d1 3017 * @param $limitnum - number of records to fetch
1c45e42e 3018 * @param $groups - single group or array of groups - group(s) user is in
71dea306 3019 * @param $exceptions - list of users to exclude
b06334e8 3020 * @param view - set to true when roles are pulled for display only
3021 * this is so that we can filter roles with no visible
3022 * assignment, for example, you might want to "hide" all
3023 * course creators when browsing the course participants
3024 * list.
1648afb2 3025 */
eef868d1 3026function get_users_by_capability($context, $capability, $fields='', $sort='',
b06334e8 3027 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true, $view=false) {
1648afb2 3028 global $CFG;
eef868d1 3029
64026e8c 3030/// Sorting out groups
1c45e42e 3031 if ($groups) {
71dea306 3032 $groupjoin = 'INNER JOIN '.$CFG->prefix.'groups_members gm ON gm.userid = ra.userid';
eef868d1 3033
1c45e42e 3034 if (is_array($groups)) {
a05708ad 3035 $groupsql = 'AND gm.groupid IN ('.implode(',', $groups).')';
1c45e42e 3036 } else {
eef868d1 3037 $groupsql = 'AND gm.groupid = '.$groups;
1c45e42e 3038 }
3039 } else {
3040 $groupjoin = '';
eef868d1 3041 $groupsql = '';
1c45e42e 3042 }
eef868d1 3043
64026e8c 3044/// Sorting out exceptions
5081e786 3045 $exceptionsql = $exceptions ? "AND u.id NOT IN ($exceptions)" : '';
64026e8c 3046
3047/// Set up default fields
3048 if (empty($fields)) {
5b630667 3049 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
64026e8c 3050 }
3051
3052/// Set up default sort
3053 if (empty($sort)) {
3054 $sort = 'ul.timeaccess';
3055 }
3056
eef868d1 3057 $sortby = $sort ? " ORDER BY $sort " : '';
b06334e8 3058/// Set up hidden sql
d42c64ba 3059 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
eef868d1 3060
64026e8c 3061/// If context is a course, then construct sql for ul
aad2ba95 3062 if ($context->contextlevel == CONTEXT_COURSE) {
71dea306 3063 $courseid = $context->instanceid;
ae9761ec 3064 $coursesql1 = "AND ul.courseid = $courseid";
5081e786 3065 } else {
ae9761ec 3066 $coursesql1 = '';
71dea306 3067 }
64026e8c 3068
3069/// Sorting out roles with this capability set
9d829c68 3070 if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context)) {
1d546bb1 3071 if (!$doanything) {
21c9bace 3072 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
1d546bb1 3073 return false; // Something is seriously wrong
3074 }
3075 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
e836a7dd 3076 }
e836a7dd 3077
9d829c68 3078 $validroleids = array();
e836a7dd 3079 foreach ($possibleroles as $possiblerole) {
1d546bb1 3080 if (!$doanything) {
3081 if (isset($doanythingroles[$possiblerole->id])) { // We don't want these included
3082 continue;
3083 }
e836a7dd 3084 }
bccdf227 3085 if ($caps = role_context_capabilities($possiblerole->id, $context, $capability)) { // resolved list
3086 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
3087 $validroleids[] = $possiblerole->id;
3088 }
9d829c68 3089 }
1648afb2 3090 }
1d546bb1 3091 if (empty($validroleids)) {
3092 return false;
3093 }
9d829c68 3094 $roleids = '('.implode(',', $validroleids).')';
3095 } else {
3096 return false; // No need to continue, since no roles have this capability set
eef868d1 3097 }
64026e8c 3098
3099/// Construct the main SQL
71dea306 3100 $select = " SELECT $fields";
eef868d1 3101 $from = " FROM {$CFG->prefix}user u
3102 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
0a3e9703 3103 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid
ae9761ec 3104 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON (ul.userid = u.id $coursesql1)
71dea306 3105 $groupjoin";
eef868d1 3106 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
3107 AND u.deleted = 0
3108 AND ra.roleid in $roleids
71dea306 3109 $exceptionsql
b06334e8 3110 $groupsql
3111 $hiddensql";
3112
eef868d1 3113 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
1648afb2 3114}
7700027f 3115
ab5c9044 3116/**
3117 * gets all the users assigned this role in this context or higher
3118 * @param int roleid
3119 * @param int contextid
3120 * @param bool parent if true, get list of users assigned in higher context too
3121 * @return array()
3122 */
d42c64ba 3123function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $view=false) {
ab5c9044 3124 global $CFG;
eef868d1 3125
2851ba9b 3126 if (empty($fields)) {
3127 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
3128 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
3129 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
3130 'u.emailstop, u.lang, u.timezone';
3131 }
3132
d42c64ba 3133 // whether this assignment is hidden
3134 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND r.hidden = 0 ':'';
ab5c9044 3135 if ($parent) {
3136 if ($contexts = get_parent_contexts($context)) {
7ea02fe9 3137 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
ab5c9044 3138 } else {
eef868d1 3139 $parentcontexts = '';
ab5c9044 3140 }
3141 } else {
eef868d1 3142 $parentcontexts = '';
3143 }
3144
b16de849 3145 if ($roleid) {
3146 $roleselect = "AND r.roleid = $roleid";
3147 } else {
3148 $roleselect = '';
3149 }
3150
7ea02fe9 3151 $SQL = "SELECT $fields
3152 FROM {$CFG->prefix}role_assignments r,
eef868d1 3153 {$CFG->prefix}user u
7ea02fe9 3154 WHERE (r.contextid = $context->id $parentcontexts)
b16de849 3155 AND u.id = r.userid $roleselect
d42c64ba 3156 $hiddensql
7ea02fe9 3157 ORDER BY $sort
3158 "; // join now so that we can just use fullname() later
eef868d1 3159
ab5c9044 3160 return get_records_sql($SQL);
3161}
3162
bac2f88a 3163/**
3164 * Counts all the users assigned this role in this context or higher
3165 * @param int roleid
3166 * @param int contextid
3167 * @param bool parent if true, get list of users assigned in higher context too
3168 * @return array()
3169 */
3170function count_role_users($roleid, $context, $parent=false) {
3171 global $CFG;
3172
3173 if ($parent) {
3174 if ($contexts = get_parent_contexts($context)) {
7ea02fe9 3175 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
bac2f88a 3176 } else {
3177 $parentcontexts = '';
3178 }
3179 } else {
3180 $parentcontexts = '';
3181 }
3182
3183 $SQL = "SELECT count(*)
3184 FROM {$CFG->prefix}role_assignments r
3185 WHERE (r.contextid = $context->id $parentcontexts)
3186 AND r.roleid = $roleid";
3187
3188 return count_records_sql($SQL);
3189}
3190
eef868d1 3191/**
d76a5a7f 3192 * This function gets the list of courses that this user has a particular capability in
3193 * This is not the most efficient way of doing this
3194 * @param string capability
3195 * @param int $userid
3196 * @return array
3197 */
3198function get_user_capability_course($capability, $userid='') {
eef868d1 3199
d76a5a7f 3200 global $USER;
3201 if (!$userid) {
eef868d1 3202 $userid = $USER->id;
d76a5a7f 3203 }
eef868d1 3204
d76a5a7f 3205 $usercourses = array();
3206 $courses = get_records_select('course', '', '', 'id, id');
eef868d1 3207
d76a5a7f 3208 foreach ($courses as $course) {
4dd5d751 3209 if (has_capability($capability, get_context_instance(CONTEXT_COURSE, $course->id))) {
d76a5a7f 3210 $usercourses[] = $course;
3211 }
3212 }
eef868d1 3213 return $usercourses;
e38f38c3 3214}
3215
3216
3217/** This function finds the roles assigned directly to this context only
3218 * i.e. no parents role
3219 * @param object $context
3220 * @return array