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