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