Automatic installer.php lang files by installer_builder (20070527)
[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 {
6eaa3f09 442 // This big SQL is expensive! We reduce it a little by avoiding checking for changed enrolments (false)
443 $capabilities = load_user_capability($capability, $context, $userid, false);
eef879ec 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
c3d1fbe9 786 * @param $checkenrolments boolean - Should we check enrolment plugins (potentially expensive)
21c9bace 787 * @return array of permissions (or nothing if they get assigned to $USER)
bbbf2d40 788 */
6eaa3f09 789function load_user_capability($capability='', $context=NULL, $userid=NULL, $checkenrolments=true) {
d140ad3f 790
98882637 791 global $USER, $CFG;
55526eee 792
40a2a15f 793 // this flag has not been set!
794 // (not clean install, or upgraded successfully to 1.7 and up)
2f1a4248 795 if (empty($CFG->rolesactive)) {
796 return false;
797 }
798
bbbf2d40 799 if (empty($userid)) {
dc411d1b 800 if (empty($USER->id)) { // We have no user to get capabilities for
64026e8c 801 debugging('User not logged in for load_user_capability!');
dc411d1b 802 return false;
803 }
64026e8c 804 unset($USER->capabilities); // We don't want possible older capabilites hanging around
805
6eaa3f09 806 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
807 check_enrolment_plugins($USER);
808 }
8f8ed475 809
bbbf2d40 810 $userid = $USER->id;
dc411d1b 811 $otheruserid = false;
bbbf2d40 812 } else {
64026e8c 813 if (!$user = get_record('user', 'id', $userid)) {
814 debugging('Non-existent userid in load_user_capability!');
815 return false;
816 }
817
6eaa3f09 818 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
819 check_enrolment_plugins($user);
820 }
64026e8c 821
9425b25f 822 $otheruserid = $userid;
bbbf2d40 823 }
9425b25f 824
5f70bcc3 825
826/// First we generate a list of all relevant contexts of the user
827
828 $usercontexts = array();
bbbf2d40 829
0468976c 830 if ($context) { // if context is specified
eef868d1 831 $usercontexts = get_parent_contexts($context);
9343a733 832 $usercontexts[] = $context->id; // Add the current context as well
98882637 833 } else { // else, we load everything
5f70bcc3 834 if ($userroles = get_records('role_assignments','userid',$userid)) {
835 foreach ($userroles as $userrole) {
0db6adc9 836 if (!in_array($userrole->contextid, $usercontexts)) {
837 $usercontexts[] = $userrole->contextid;
838 }
5f70bcc3 839 }
98882637 840 }
5f70bcc3 841 }
842
843/// Set up SQL fragments for searching contexts
844
845 if ($usercontexts) {
0468976c 846 $listofcontexts = '('.implode(',', $usercontexts).')';
5f70bcc3 847 $searchcontexts1 = "c1.id IN $listofcontexts AND";
5f70bcc3 848 } else {
c76e095f 849 $searchcontexts1 = '';
bbbf2d40 850 }
3ca2dea5 851
64026e8c 852 if ($capability) {
afe41398 853 // the doanything may override the requested capability
854 $capsearch = " AND (rc.capability = '$capability' OR rc.capability = 'moodle/site:doanything') ";
64026e8c 855 } else {
eef868d1 856 $capsearch ="";
64026e8c 857 }
858
5f70bcc3 859/// Then we use 1 giant SQL to bring out all relevant capabilities.
860/// The first part gets the capabilities of orginal role.
861/// The second part gets the capabilities of overriden roles.
bbbf2d40 862
21c9bace 863 $siteinstance = get_context_instance(CONTEXT_SYSTEM);
9fccc080 864 $capabilities = array(); // Reinitialize.
865
866 // SQL for normal capabilities
867 $SQL1 = "SELECT rc.capability, c1.id as id1, c1.id as id2, (c1.contextlevel * 100) AS aggrlevel,
bbbf2d40 868 SUM(rc.permission) AS sum
869 FROM
eef868d1 870 {$CFG->prefix}role_assignments ra,
42ac3ecf 871 {$CFG->prefix}role_capabilities rc,
872 {$CFG->prefix}context c1
bbbf2d40 873 WHERE
d4649c76 874 ra.contextid=c1.id AND
875 ra.roleid=rc.roleid AND
bbbf2d40 876 ra.userid=$userid AND
5f70bcc3 877 $searchcontexts1
eef868d1 878 rc.contextid=$siteinstance->id
98882637 879 $capsearch
bbbf2d40 880 GROUP BY
55526eee 881 rc.capability, c1.id, c1.contextlevel * 100
bbbf2d40 882 HAVING
9fccc080 883 SUM(rc.permission) != 0
0db6adc9 884
885 UNION ALL
886
887 SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
888 SUM(rc.permission) AS sum
889 FROM
890 {$CFG->prefix}role_assignments ra LEFT JOIN
891 {$CFG->prefix}role_capabilities rc on ra.roleid = rc.roleid LEFT JOIN
892 {$CFG->prefix}context c1 on ra.contextid = c1.id LEFT JOIN
893 {$CFG->prefix}context c2 on rc.contextid = c2.id LEFT JOIN
894 {$CFG->prefix}context_rel cr on cr.c1 = c2.id
895 WHERE
896 ra.userid=$userid AND
897 $searchcontexts1
898 rc.contextid != $siteinstance->id
899 $capsearch
0db6adc9 900 AND cr.c2 = c1.id
901 GROUP BY
55526eee 902 rc.capability, c1.id, c2.id, c1.contextlevel * 100 + c2.contextlevel
0db6adc9 903 HAVING
904 SUM(rc.permission) != 0
9fccc080 905 ORDER BY
906 aggrlevel ASC";
0db6adc9 907
9fccc080 908 if (!$rs = get_recordset_sql($SQL1)) {
909 error("Query failed in load_user_capability.");
910 }
bbbf2d40 911
9fccc080 912 if ($rs && $rs->RecordCount() > 0) {
bcf88cbb 913 while ($caprec = rs_fetch_next_record($rs)) {
914 $array = (array)$caprec;
9fccc080 915 $temprecord = new object;
916
917 foreach ($array as $key=>$val) {
918 if ($key == 'aggrlevel') {
919 $temprecord->contextlevel = $val;
920 } else {
921 $temprecord->{$key} = $val;
922 }
923 }
9fccc080 924 $capabilities[] = $temprecord;
9fccc080 925 }
bcf88cbb 926 rs_close($rs);
b7e40271 927 }
bcf88cbb 928
9fccc080 929 // SQL for overrides
930 // this is take out because we have no way of making sure c1 is indeed related to c2 (parent)
931 // if we do not group by sum, it is possible to have multiple records of rc.capability, c1.id, c2.id, tuple having
932 // different values, we can maually sum it when we go through the list
0db6adc9 933
934 /*
935
9fccc080 936 $SQL2 = "SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
937 rc.permission AS sum
bbbf2d40 938 FROM
42ac3ecf 939 {$CFG->prefix}role_assignments ra,
940 {$CFG->prefix}role_capabilities rc,
941 {$CFG->prefix}context c1,
942 {$CFG->prefix}context c2
bbbf2d40 943 WHERE
d4649c76 944 ra.contextid=c1.id AND
eef868d1 945 ra.roleid=rc.roleid AND
946 ra.userid=$userid AND
947 rc.contextid=c2.id AND
5f70bcc3 948 $searchcontexts1
5f70bcc3 949 rc.contextid != $siteinstance->id
bbbf2d40 950 $capsearch
eef868d1 951
bbbf2d40 952 GROUP BY
21c9bace 953 rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c1.id, c2.id, rc.permission
bbbf2d40 954 ORDER BY
75e84883 955 aggrlevel ASC
0db6adc9 956 ";*/
9fccc080 957
0db6adc9 958/*
9fccc080 959 if (!$rs = get_recordset_sql($SQL2)) {
75e84883 960 error("Query failed in load_user_capability.");
961 }
5cf38a57 962
bbbf2d40 963 if ($rs && $rs->RecordCount() > 0) {
bcf88cbb 964 while ($caprec = rs_fetch_next_record($rs)) {
965 $array = (array)$caprec;
75e84883 966 $temprecord = new object;
eef868d1 967
98882637 968 foreach ($array as $key=>$val) {
75e84883 969 if ($key == 'aggrlevel') {
aad2ba95 970 $temprecord->contextlevel = $val;
75e84883 971 } else {
972 $temprecord->{$key} = $val;
973 }
98882637 974 }
9fccc080 975 // for overrides, we have to make sure that context2 is a child of context1
976 // otherwise the combination makes no sense
0db6adc9 977 //if (is_parent_context($temprecord->id1, $temprecord->id2)) {
9fccc080 978 $capabilities[] = $temprecord;
0db6adc9 979 //} // only write if relevant
bbbf2d40 980 }
bcf88cbb 981 rs_close($rs);
bbbf2d40 982 }
0db6adc9 983
9fccc080 984 // this step sorts capabilities according to the contextlevel
985 // it is very important because the order matters when we
986 // go through each capabilities later. (i.e. higher level contextlevel
987 // will override lower contextlevel settings
988 usort($capabilities, 'roles_context_cmp');
0db6adc9 989*/
bbbf2d40 990 /* so up to this point we should have somethign like this
aad2ba95 991 * $capabilities[1] ->contextlevel = 1000
8ba412da 992 ->module = 0 // changed from SITEID in 1.8 (??)
bbbf2d40 993 ->capability = do_anything
994 ->id = 1 (id is the context id)
995 ->sum = 0
eef868d1 996
aad2ba95 997 * $capabilities[2] ->contextlevel = 1000
8ba412da 998 ->module = 0 // changed from SITEID in 1.8 (??)
bbbf2d40 999 ->capability = post_messages
1000 ->id = 1
1001 ->sum = -9000
1002
aad2ba95 1003 * $capabilittes[3] ->contextlevel = 3000
bbbf2d40 1004 ->module = course
1005 ->capability = view_course_activities
1006 ->id = 25
1007 ->sum = 1
1008
aad2ba95 1009 * $capabilittes[4] ->contextlevel = 3000
bbbf2d40 1010 ->module = course
1011 ->capability = view_course_activities
1012 ->id = 26
1013 ->sum = 0 (this is another course)
eef868d1 1014
aad2ba95 1015 * $capabilities[5] ->contextlevel = 3050
bbbf2d40 1016 ->module = course
1017 ->capability = view_course_activities
1018 ->id = 25 (override in course 25)
1019 ->sum = -1
1020 * ....
1021 * now we proceed to write the session array, going from top to bottom
1022 * at anypoint, we need to go up and check parent to look for prohibit
1023 */
1024 // print_object($capabilities);
1025
1026 /* This is where we write to the actualy capabilities array
1027 * what we need to do from here on is
1028 * going down the array from lowest level to highest level
1029 * 1) recursively check for prohibit,
1030 * if any, we write prohibit
1031 * else, we write the value
1032 * 2) at an override level, we overwrite current level
1033 * if it's not set to prohibit already, and if different
1034 * ........ that should be it ........
1035 */
efb58884 1036
1037 // This is the flag used for detecting the current context level. Since we are going through
1038 // the array in ascending order of context level. For normal capabilities, there should only
1039 // be 1 value per (capability, contextlevel, context), because they are already summed. But,
1040 // for overrides, since we are processing them separate, we need to sum the relevcant entries.
1041 // We set this flag when we hit a new level.
1042 // If the flag is already set, we keep adding (summing), otherwise, we just override previous
1043 // settings (from lower level contexts)
1044 $capflags = array(); // (contextid, contextlevel, capability)
98882637 1045 $usercap = array(); // for other user's capabilities
bbbf2d40 1046 foreach ($capabilities as $capability) {
1047
9fccc080 1048 if (!$context = get_context_instance_by_id($capability->id2)) {
7bfa3101 1049 continue; // incorrect stale context
1050 }
0468976c 1051
41811960 1052 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
eef868d1 1053
0468976c 1054 if (capability_prohibits($capability->capability, $context, $capability->sum, $usercap)) {
9fccc080 1055 $usercap[$capability->id2][$capability->capability] = CAP_PROHIBIT;
98882637 1056 continue;
1057 }
efb58884 1058 if (isset($usercap[$capability->id2][$capability->capability])) { // use isset because it can be sum 0
1059 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1060 $usercap[$capability->id2][$capability->capability] += $capability->sum;
1061 } else { // else we override, and update flag
1062 $usercap[$capability->id2][$capability->capability] = $capability->sum;
1063 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1064 }
9fccc080 1065 } else {
1066 $usercap[$capability->id2][$capability->capability] = $capability->sum;
efb58884 1067 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
9fccc080 1068 }
eef868d1 1069
98882637 1070 } else {
1071
0468976c 1072 if (capability_prohibits($capability->capability, $context, $capability->sum)) { // if any parent or parent's parent is set to prohibit
9fccc080 1073 $USER->capabilities[$capability->id2][$capability->capability] = CAP_PROHIBIT;
98882637 1074 continue;
1075 }
eef868d1 1076
98882637 1077 // if no parental prohibit set
1078 // just write to session, i am not sure this is correct yet
1079 // since 3050 shows up after 3000, and 3070 shows up after 3050,
1080 // it should be ok just to overwrite like this, provided that there's no
1081 // parental prohibits
98882637 1082 // we need to write even if it's 0, because it could be an inherit override
efb58884 1083 if (isset($USER->capabilities[$capability->id2][$capability->capability])) {
1084 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1085 $USER->capabilities[$capability->id2][$capability->capability] += $capability->sum;
1086 } else { // else we override, and update flag
1087 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
1088 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1089 }
9fccc080 1090 } else {
1091 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
efb58884 1092 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
9fccc080 1093 }
98882637 1094 }
bbbf2d40 1095 }
eef868d1 1096
bbbf2d40 1097 // now we don't care about the huge array anymore, we can dispose it.
1098 unset($capabilities);
efb58884 1099 unset($capflags);
eef868d1 1100
dbe7e582 1101 if (!empty($otheruserid)) {
eef868d1 1102 return $usercap; // return the array
bbbf2d40 1103 }
2f1a4248 1104}
1105
1106
eef879ec 1107/**
2f1a4248 1108 * A convenience function to completely load all the capabilities
1109 * for the current user. This is what gets called from login, for example.
1110 */
1111function load_all_capabilities() {
1112 global $USER;
1113
eef879ec 1114 //caching - helps user switching in cron
1115 static $defcaps = false;
bbbf2d40 1116
8e82745a 1117 unset($USER->mycourses); // Reset a cache used by get_my_courses
1118
eef879ec 1119 if (isguestuser()) {
2f1a4248 1120 load_guest_role(); // All non-guest users get this by default
eef879ec 1121
1122 } else if (isloggedin()) {
1123 if ($defcaps === false) {
1124 $defcaps = load_defaultuser_role(true);
1125 }
1126
3887fe4a 1127 load_user_capability();
1128
1129 // when in "course login as" - load only course caqpabilitites (it may not always work as expected)
1130 if (!empty($USER->realuser) and $USER->loginascontext->contextlevel != CONTEXT_SYSTEM) {
1131 $children = get_child_contexts($USER->loginascontext);
1132 $children[] = $USER->loginascontext->id;
1133 foreach ($USER->capabilities as $conid => $caps) {
1134 if (!in_array($conid, $children)) {
1135 unset($USER->capabilities[$conid]);
c16ec802 1136 }
f6f66b03 1137 }
1138 }
eef879ec 1139
3887fe4a 1140 // handle role switching in courses
de5e137a 1141 if (!empty($USER->switchrole)) {
de5e137a 1142 foreach ($USER->switchrole as $contextid => $roleid) {
1143 $context = get_context_instance_by_id($contextid);
1144
1145 // first prune context and any child contexts
1146 $children = get_child_contexts($context);
1147 foreach ($children as $childid) {
1148 unset($USER->capabilities[$childid]);
1149 }
1150 unset($USER->capabilities[$contextid]);
1151
1152 // now merge all switched role caps in context and bellow
1153 $swithccaps = get_role_context_caps($roleid, $context);
1154 $USER->capabilities = merge_role_caps($USER->capabilities, $swithccaps);
1155 }
eef879ec 1156 }
1157
c0aa9f09 1158 if (isset($USER->capabilities)) {
1159 $USER->capabilities = merge_role_caps($USER->capabilities, $defcaps);
1160 } else {
1161 $USER->capabilities = $defcaps;
1162 }
de5e137a 1163
2f1a4248 1164 } else {
eef879ec 1165 load_notloggedin_role();
2f1a4248 1166 }
bbbf2d40 1167}
1168
2f1a4248 1169
efe12f6c 1170/**
64026e8c 1171 * Check all the login enrolment information for the given user object
eef868d1 1172 * by querying the enrolment plugins
64026e8c 1173 */
1174function check_enrolment_plugins(&$user) {
1175 global $CFG;
1176
e4ec4e41 1177 static $inprogress; // To prevent this function being called more than once in an invocation
1178
218eb651 1179 if (!empty($inprogress[$user->id])) {
e4ec4e41 1180 return;
1181 }
1182
218eb651 1183 $inprogress[$user->id] = true; // Set the flag
e4ec4e41 1184
64026e8c 1185 require_once($CFG->dirroot .'/enrol/enrol.class.php');
eef868d1 1186
64026e8c 1187 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
1188 $plugins = array($CFG->enrol);
1189 }
1190
1191 foreach ($plugins as $plugin) {
1192 $enrol = enrolment_factory::factory($plugin);
1193 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1194 $enrol->setup_enrolments($user);
1195 } else { /// Run legacy enrolment methods
1196 if (method_exists($enrol, 'get_student_courses')) {
1197 $enrol->get_student_courses($user);
1198 }
1199 if (method_exists($enrol, 'get_teacher_courses')) {
1200 $enrol->get_teacher_courses($user);
1201 }
1202
1203 /// deal with $user->students and $user->teachers stuff
1204 unset($user->student);
1205 unset($user->teacher);
1206 }
1207 unset($enrol);
1208 }
e4ec4e41 1209
218eb651 1210 unset($inprogress[$user->id]); // Unset the flag
64026e8c 1211}
1212
bbbf2d40 1213
1214/**
1215 * This is a recursive function that checks whether the capability in this
1216 * context, or the parent capabilities are set to prohibit.
1217 *
1218 * At this point, we can probably just use the values already set in the
1219 * session variable, since we are going down the level. Any prohit set in
1220 * parents would already reflect in the session.
1221 *
1222 * @param $capability - capability name
1223 * @param $sum - sum of all capabilities values
0468976c 1224 * @param $context - the context object
bbbf2d40 1225 * @param $array - when loading another user caps, their caps are not stored in session but an array
1226 */
0468976c 1227function capability_prohibits($capability, $context, $sum='', $array='') {
bbbf2d40 1228 global $USER;
0468976c 1229
0db6adc9 1230 // caching, mainly to save unnecessary sqls
1231 static $prohibits; //[capability][contextid]
1232 if (isset($prohibits[$capability][$context->id])) {
1233 return $prohibits[$capability][$context->id];
1234 }
1235
2176adf1 1236 if (empty($context->id)) {
0db6adc9 1237 $prohibits[$capability][$context->id] = false;
2176adf1 1238 return false;
1239 }
1240
1241 if (empty($capability)) {
0db6adc9 1242 $prohibits[$capability][$context->id] = false;
2176adf1 1243 return false;
1244 }
1245
819e5a70 1246 if ($sum < (CAP_PROHIBIT/2)) {
bbbf2d40 1247 // If this capability is set to prohibit.
0db6adc9 1248 $prohibits[$capability][$context->id] = true;
bbbf2d40 1249 return true;
1250 }
eef868d1 1251
819e5a70 1252 if (!empty($array)) {
eef868d1 1253 if (isset($array[$context->id][$capability])
819e5a70 1254 && $array[$context->id][$capability] < (CAP_PROHIBIT/2)) {
0db6adc9 1255 $prohibits[$capability][$context->id] = true;
98882637 1256 return true;
eef868d1 1257 }
bbbf2d40 1258 } else {
98882637 1259 // Else if set in session.
eef868d1 1260 if (isset($USER->capabilities[$context->id][$capability])
819e5a70 1261 && $USER->capabilities[$context->id][$capability] < (CAP_PROHIBIT/2)) {
0db6adc9 1262 $prohibits[$capability][$context->id] = true;
98882637 1263 return true;
1264 }
bbbf2d40 1265 }
aad2ba95 1266 switch ($context->contextlevel) {
eef868d1 1267
bbbf2d40 1268 case CONTEXT_SYSTEM:
1269 // By now it's a definite an inherit.
1270 return 0;
1271 break;
1272
1273 case CONTEXT_PERSONAL:
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
4b10f08b 1279 case CONTEXT_USER:
2176adf1 1280 $parent = get_context_instance(CONTEXT_SYSTEM);
0db6adc9 1281 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1282 return $prohibits[$capability][$context->id];
bbbf2d40 1283 break;
1284
1285 case CONTEXT_COURSECAT:
1286 // Coursecat -> coursecat or site.
2176adf1 1287 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
0db6adc9 1288 $prohibits[$capability][$context->id] = false;
2176adf1 1289 return false;
40a2a15f 1290 }
41811960 1291 if (!empty($coursecat->parent)) {
bbbf2d40 1292 // return parent value if exist.
1293 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1294 } else {
1295 // Return site value.
2176adf1 1296 $parent = get_context_instance(CONTEXT_SYSTEM);
bbbf2d40 1297 }
0db6adc9 1298 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1299 return $prohibits[$capability][$context->id];
bbbf2d40 1300 break;
1301
1302 case CONTEXT_COURSE:
1303 // 1 to 1 to course cat.
1304 // Find the course cat, and return its value.
2176adf1 1305 if (!$course = get_record('course','id',$context->instanceid)) {
0db6adc9 1306 $prohibits[$capability][$context->id] = false;
2176adf1 1307 return false;
1308 }
40a2a15f 1309 // Yu: Separating site and site course context
1310 if ($course->id == SITEID) {
1311 $parent = get_context_instance(CONTEXT_SYSTEM);
1312 } else {
1313 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1314 }
0db6adc9 1315 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1316 return $prohibits[$capability][$context->id];
bbbf2d40 1317 break;
1318
1319 case CONTEXT_GROUP:
1320 // 1 to 1 to course.
f3f7610c 1321 if (!$courseid = groups_get_course($context->instanceid)) {
0db6adc9 1322 $prohibits[$capability][$context->id] = false;
2176adf1 1323 return false;
1324 }
f3f7610c 1325 $parent = get_context_instance(CONTEXT_COURSE, $courseid);
0db6adc9 1326 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1327 return $prohibits[$capability][$context->id];
bbbf2d40 1328 break;
1329
1330 case CONTEXT_MODULE:
1331 // 1 to 1 to course.
2176adf1 1332 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
0db6adc9 1333 $prohibits[$capability][$context->id] = false;
2176adf1 1334 return false;
1335 }
bbbf2d40 1336 $parent = get_context_instance(CONTEXT_COURSE, $cm->course);
0db6adc9 1337 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1338 return $prohibits[$capability][$context->id];
bbbf2d40 1339 break;
1340
1341 case CONTEXT_BLOCK:
1342 // 1 to 1 to course.
2176adf1 1343 if (!$block = get_record('block_instance','id',$context->instanceid)) {
0db6adc9 1344 $prohibits[$capability][$context->id] = false;
2176adf1 1345 return false;
1346 }
6ceebc1f 1347 if ($block->pagetype == 'course-view') {
1348 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
1349 } else {
1350 $parent = get_context_instance(CONTEXT_SYSTEM);
1351 }
0db6adc9 1352 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1353 return $prohibits[$capability][$context->id];
bbbf2d40 1354 break;
1355
1356 default:
2176adf1 1357 print_error('unknowncontext');
1358 return false;
bbbf2d40 1359 }
1360}
1361
1362
1363/**
1364 * A print form function. This should either grab all the capabilities from
1365 * files or a central table for that particular module instance, then present
1366 * them in check boxes. Only relevant capabilities should print for known
1367 * context.
1368 * @param $mod - module id of the mod
1369 */
1370function print_capabilities($modid=0) {
1371 global $CFG;
eef868d1 1372
bbbf2d40 1373 $capabilities = array();
1374
1375 if ($modid) {
1376 // We are in a module specific context.
1377
1378 // Get the mod's name.
1379 // Call the function that grabs the file and parse.
1380 $cm = get_record('course_modules', 'id', $modid);
1381 $module = get_record('modules', 'id', $cm->module);
eef868d1 1382
bbbf2d40 1383 } else {
1384 // Print all capabilities.
1385 foreach ($capabilities as $capability) {
1386 // Prints the check box component.
1387 }
1388 }
1389}
1390
1391
1392/**
1afecc03 1393 * Installs the roles system.
1394 * This function runs on a fresh install as well as on an upgrade from the old
1395 * hard-coded student/teacher/admin etc. roles to the new roles system.
bbbf2d40 1396 */
1afecc03 1397function moodle_install_roles() {
bbbf2d40 1398
1afecc03 1399 global $CFG, $db;
eef868d1 1400
459c1ff1 1401/// Create a system wide context for assignemnt.
21c9bace 1402 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
bbbf2d40 1403
1afecc03 1404
459c1ff1 1405/// Create default/legacy roles and capabilities.
1406/// (1 legacy capability per legacy role at system level).
1407
69aaada0 1408 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1409 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1410 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1411 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1412 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1413 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1414 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1415 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1416 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1417 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1418 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1419 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
c785d40a 1420 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1421 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
2851ba9b 1422
17e5635c 1423/// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
459c1ff1 1424
98882637 1425 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
bbbf2d40 1426 error('Could not assign moodle/site:doanything to the admin role');
1427 }
250934b8 1428 if (!update_capabilities()) {
1429 error('Had trouble upgrading the core capabilities for the Roles System');
1430 }
1afecc03 1431
459c1ff1 1432/// Look inside user_admin, user_creator, user_teachers, user_students and
1433/// assign above new roles. If a user has both teacher and student role,
1434/// only teacher role is assigned. The assignment should be system level.
1435
1afecc03 1436 $dbtables = $db->MetaTables('TABLES');
eef868d1 1437
72da5046 1438/// Set up the progress bar
1439
1440 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1441
1442 $totalcount = $progresscount = 0;
1443 foreach ($usertables as $usertable) {
1444 if (in_array($CFG->prefix.$usertable, $dbtables)) {
1445 $totalcount += count_records($usertable);
1446 }
1447 }
1448
aae37b63 1449 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1450
459c1ff1 1451/// Upgrade the admins.
1452/// Sort using id ASC, first one is primary admin.
1453
1afecc03 1454 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
f1dcf000 1455 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
0f5dafff 1456 while ($admin = rs_fetch_next_record($rs)) {
1afecc03 1457 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
72da5046 1458 $progresscount++;
aae37b63 1459 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1460 }
0f5dafff 1461 rs_close($rs);
1afecc03 1462 }
1463 } else {
1464 // This is a fresh install.
bbbf2d40 1465 }
1afecc03 1466
1467
459c1ff1 1468/// Upgrade course creators.
1afecc03 1469 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
f1dcf000 1470 if ($rs = get_recordset('user_coursecreators')) {
0f5dafff 1471 while ($coursecreator = rs_fetch_next_record($rs)) {
56b4d70d 1472 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
72da5046 1473 $progresscount++;
aae37b63 1474 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1475 }
0f5dafff 1476 rs_close($rs);
1afecc03 1477 }
bbbf2d40 1478 }
1479
1afecc03 1480
459c1ff1 1481/// Upgrade editting teachers and non-editting teachers.
1afecc03 1482 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
f1dcf000 1483 if ($rs = get_recordset('user_teachers')) {
0f5dafff 1484 while ($teacher = rs_fetch_next_record($rs)) {
d5511451 1485
1486 // removed code here to ignore site level assignments
1487 // since the contexts are separated now
1488
17d6a25e 1489 // populate the user_lastaccess table
ece4945b 1490 $access = new object();
17d6a25e 1491 $access->timeaccess = $teacher->timeaccess;
1492 $access->userid = $teacher->userid;
1493 $access->courseid = $teacher->course;
1494 insert_record('user_lastaccess', $access);
f1dcf000 1495
17d6a25e 1496 // assign the default student role
1afecc03 1497 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
3fe54e51 1498 // hidden teacher
1499 if ($teacher->authority == 0) {
1500 $hiddenteacher = 1;
1501 } else {
1502 $hiddenteacher = 0;
1503 }
1504
1afecc03 1505 if ($teacher->editall) { // editting teacher
3fe54e51 1506 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1afecc03 1507 } else {
3fe54e51 1508 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1afecc03 1509 }
72da5046 1510 $progresscount++;
aae37b63 1511 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1512 }
0f5dafff 1513 rs_close($rs);
bbbf2d40 1514 }
1515 }
1afecc03 1516
1517
459c1ff1 1518/// Upgrade students.
1afecc03 1519 if (in_array($CFG->prefix.'user_students', $dbtables)) {
f1dcf000 1520 if ($rs = get_recordset('user_students')) {
0f5dafff 1521 while ($student = rs_fetch_next_record($rs)) {
f1dcf000 1522
17d6a25e 1523 // populate the user_lastaccess table
f1dcf000 1524 $access = new object;
17d6a25e 1525 $access->timeaccess = $student->timeaccess;
1526 $access->userid = $student->userid;
1527 $access->courseid = $student->course;
1528 insert_record('user_lastaccess', $access);
f1dcf000 1529
17d6a25e 1530 // assign the default student role
1afecc03 1531 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
1532 role_assign($studentrole, $student->userid, 0, $coursecontext->id);
72da5046 1533 $progresscount++;
aae37b63 1534 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1535 }
0f5dafff 1536 rs_close($rs);
1afecc03 1537 }
bbbf2d40 1538 }
1afecc03 1539
1540
459c1ff1 1541/// Upgrade guest (only 1 entry).
1afecc03 1542 if ($guestuser = get_record('user', 'username', 'guest')) {
1543 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
1544 }
aae37b63 1545 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1546
459c1ff1 1547
1548/// Insert the correct records for legacy roles
945f88ca 1549 allow_assign($adminrole, $adminrole);
1550 allow_assign($adminrole, $coursecreatorrole);
1551 allow_assign($adminrole, $noneditteacherrole);
eef868d1 1552 allow_assign($adminrole, $editteacherrole);
945f88ca 1553 allow_assign($adminrole, $studentrole);
1554 allow_assign($adminrole, $guestrole);
eef868d1 1555
945f88ca 1556 allow_assign($coursecreatorrole, $noneditteacherrole);
1557 allow_assign($coursecreatorrole, $editteacherrole);
eef868d1 1558 allow_assign($coursecreatorrole, $studentrole);
945f88ca 1559 allow_assign($coursecreatorrole, $guestrole);
eef868d1 1560
1561 allow_assign($editteacherrole, $noneditteacherrole);
1562 allow_assign($editteacherrole, $studentrole);
945f88ca 1563 allow_assign($editteacherrole, $guestrole);
eef868d1 1564
459c1ff1 1565/// Set up default permissions for overrides
945f88ca 1566 allow_override($adminrole, $adminrole);
1567 allow_override($adminrole, $coursecreatorrole);
1568 allow_override($adminrole, $noneditteacherrole);
eef868d1 1569 allow_override($adminrole, $editteacherrole);
945f88ca 1570 allow_override($adminrole, $studentrole);
eef868d1 1571 allow_override($adminrole, $guestrole);
c785d40a 1572 allow_override($adminrole, $userrole);
1afecc03 1573
746a04c5 1574
459c1ff1 1575/// Delete the old user tables when we are done
1576
83ea392e 1577 drop_table(new XMLDBTable('user_students'));
1578 drop_table(new XMLDBTable('user_teachers'));
1579 drop_table(new XMLDBTable('user_coursecreators'));
1580 drop_table(new XMLDBTable('user_admins'));
459c1ff1 1581
bbbf2d40 1582}
1583
3562486b 1584/**
1585 * Returns array of all legacy roles.
1586 */
1587function get_legacy_roles() {
1588 return array(
a83addc5 1589 'admin' => 'moodle/legacy:admin',
3562486b 1590 'coursecreator' => 'moodle/legacy:coursecreator',
a83addc5 1591 'editingteacher' => 'moodle/legacy:editingteacher',
1592 'teacher' => 'moodle/legacy:teacher',
1593 'student' => 'moodle/legacy:student',
efe12f6c 1594 'guest' => 'moodle/legacy:guest',
1595 'user' => 'moodle/legacy:user'
3562486b 1596 );
1597}
1598
b357ed13 1599function get_legacy_type($roleid) {
1600 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1601 $legacyroles = get_legacy_roles();
1602
1603 $result = '';
1604 foreach($legacyroles as $ltype=>$lcap) {
1605 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
1606 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
1607 //choose first selected legacy capability - reset the rest
1608 if (empty($result)) {
1609 $result = $ltype;
1610 } else {
66a27728 1611 unassign_capability($lcap, $roleid);
b357ed13 1612 }
1613 }
1614 }
1615
1616 return $result;
1617}
1618
bbbf2d40 1619/**
1620 * Assign the defaults found in this capabality definition to roles that have
1621 * the corresponding legacy capabilities assigned to them.
1622 * @param $legacyperms - an array in the format (example):
1623 * 'guest' => CAP_PREVENT,
1624 * 'student' => CAP_ALLOW,
1625 * 'teacher' => CAP_ALLOW,
1626 * 'editingteacher' => CAP_ALLOW,
1627 * 'coursecreator' => CAP_ALLOW,
1628 * 'admin' => CAP_ALLOW
1629 * @return boolean - success or failure.
1630 */
1631function assign_legacy_capabilities($capability, $legacyperms) {
eef868d1 1632
3562486b 1633 $legacyroles = get_legacy_roles();
1634
bbbf2d40 1635 foreach ($legacyperms as $type => $perm) {
eef868d1 1636
21c9bace 1637 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
eef868d1 1638
3562486b 1639 if (!array_key_exists($type, $legacyroles)) {
1640 error('Incorrect legacy role definition for type: '.$type);
1641 }
eef868d1 1642
3562486b 1643 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW)) {
2e85fffe 1644 foreach ($roles as $role) {
1645 // Assign a site level capability.
1646 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1647 return false;
1648 }
bbbf2d40 1649 }
1650 }
1651 }
1652 return true;
1653}
1654
1655
cee0901c 1656/**
1657 * Checks to see if a capability is a legacy capability.
1658 * @param $capabilityname
1659 * @return boolean
1660 */
bbbf2d40 1661function islegacy($capabilityname) {
d67de0ca 1662 if (strpos($capabilityname, 'moodle/legacy') === 0) {
eef868d1 1663 return true;
d67de0ca 1664 } else {
1665 return false;
98882637 1666 }
bbbf2d40 1667}
1668
cee0901c 1669
1670
1671/**********************************
bbbf2d40 1672 * Context Manipulation functions *
1673 **********************************/
1674
bbbf2d40 1675/**
9991d157 1676 * Create a new context record for use by all roles-related stuff
bbbf2d40 1677 * @param $level
1678 * @param $instanceid
3ca2dea5 1679 *
1680 * @return object newly created context (or existing one with a debug warning)
bbbf2d40 1681 */
aad2ba95 1682function create_context($contextlevel, $instanceid) {
3ca2dea5 1683 if (!$context = get_record('context','contextlevel',$contextlevel,'instanceid',$instanceid)) {
1684 if (!validate_context($contextlevel, $instanceid)) {
1685 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1686 return NULL;
1687 }
8ba412da 1688 if ($contextlevel == CONTEXT_SYSTEM) {
1689 return create_system_context();
1690
1691 }
3ca2dea5 1692 $context = new object();
aad2ba95 1693 $context->contextlevel = $contextlevel;
bbbf2d40 1694 $context->instanceid = $instanceid;
3ca2dea5 1695 if ($id = insert_record('context',$context)) {
0db6adc9 1696 // we need to populate context_rel for every new context inserted
1697 $c = get_record('context','id',$id);
1698 insert_context_rel ($c);
1699 return $c;
3ca2dea5 1700 } else {
1701 debugging('Error: could not insert new context level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1702 return NULL;
1703 }
1704 } else {
1705 debugging('Warning: Context id "'.s($context->id).'" not created, because it already exists.');
1706 return $context;
bbbf2d40 1707 }
1708}
1709
efe12f6c 1710/**
8ba412da 1711 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
1712 */
1713function create_system_context() {
1714 if ($context = get_record('context', 'contextlevel', CONTEXT_SYSTEM, 'instanceid', SITEID)) {
1715 // we are going to change instanceid of system context to 0 now
1716 $context->instanceid = 0;
1717 update_record('context', $context);
1718 //context rel not affected
1719 return $context;
1720
1721 } else {
1722 $context = new object();
1723 $context->contextlevel = CONTEXT_SYSTEM;
1724 $context->instanceid = 0;
1725 if ($context->id = insert_record('context',$context)) {
1726 // we need not to populate context_rel for system context
1727 return $context;
1728 } else {
1729 debugging('Can not create system context');
1730 return NULL;
1731 }
1732 }
1733}
9991d157 1734/**
1735 * Create a new context record for use by all roles-related stuff
1736 * @param $level
1737 * @param $instanceid
3ca2dea5 1738 *
1739 * @return true if properly deleted
9991d157 1740 */
1741function delete_context($contextlevel, $instanceid) {
0db6adc9 1742 if ($context = get_context_instance($contextlevel, $instanceid)) {
1743 delete_records('context_rel', 'c2', $context->id); // might not be a parent
9991d157 1744 return delete_records('context', 'id', $context->id) &&
1745 delete_records('role_assignments', 'contextid', $context->id) &&
0db6adc9 1746 delete_records('role_capabilities', 'contextid', $context->id) &&
1747 delete_records('context_rel', 'c1', $context->id);
9991d157 1748 }
1749 return true;
1750}
1751
3ca2dea5 1752/**
1753 * Validate that object with instanceid really exists in given context level.
1754 *
1755 * return if instanceid object exists
1756 */
1757function validate_context($contextlevel, $instanceid) {
1758 switch ($contextlevel) {
1759
1760 case CONTEXT_SYSTEM:
8ba412da 1761 return ($instanceid == 0);
3ca2dea5 1762
1763 case CONTEXT_PERSONAL:
1764 return (boolean)count_records('user', 'id', $instanceid);
1765
1766 case CONTEXT_USER:
1767 return (boolean)count_records('user', 'id', $instanceid);
1768
1769 case CONTEXT_COURSECAT:
1cd3eba9 1770 if ($instanceid == 0) {
1771 return true; // site course category
1772 }
3ca2dea5 1773 return (boolean)count_records('course_categories', 'id', $instanceid);
1774
1775 case CONTEXT_COURSE:
1776 return (boolean)count_records('course', 'id', $instanceid);
1777
1778 case CONTEXT_GROUP:
f3f7610c 1779 return groups_group_exists($instanceid);
3ca2dea5 1780
1781 case CONTEXT_MODULE:
1782 return (boolean)count_records('course_modules', 'id', $instanceid);
1783
1784 case CONTEXT_BLOCK:
1785 return (boolean)count_records('block_instance', 'id', $instanceid);
1786
1787 default:
1788 return false;
1789 }
1790}
bbbf2d40 1791
1792/**
1793 * Get the context instance as an object. This function will create the
1794 * context instance if it does not exist yet.
1795 * @param $level
1796 * @param $instance
1797 */
8ba412da 1798function get_context_instance($contextlevel=NULL, $instance=0) {
e5605780 1799
51195e6f 1800 global $context_cache, $context_cache_id, $CONTEXT;
a36a3a3f 1801 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_PERSONAL, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_GROUP, CONTEXT_MODULE, CONTEXT_BLOCK);
d9a35e12 1802
8ba412da 1803 // Yu: Separating site and site course context - removed CONTEXT_COURSE override when SITEID
9251b26f 1804
1805 // fix for MDL-9016
1806 if ($contextlevel == 'clearcache') {
1807 // Clear ALL cache
1808 $context_cache = array();
1809 $context_cache_id = array();
1810 $CONTEXT = '';
1811 return false;
1812 }
b7cec865 1813
340ea4e8 1814/// If no level is supplied then return the current global context if there is one
aad2ba95 1815 if (empty($contextlevel)) {
340ea4e8 1816 if (empty($CONTEXT)) {
a36a3a3f 1817 //fatal error, code must be fixed
1818 error("Error: get_context_instance() called without a context");
340ea4e8 1819 } else {
1820 return $CONTEXT;
1821 }
e5605780 1822 }
1823
8ba412da 1824/// Backwards compatibility with obsoleted (CONTEXT_SYSTEM, SITEID)
1825 if ($contextlevel == CONTEXT_SYSTEM) {
1826 $instance = 0;
1827 }
1828
a36a3a3f 1829/// check allowed context levels
1830 if (!in_array($contextlevel, $allowed_contexts)) {
7bfa3101 1831 // fatal error, code must be fixed - probably typo or switched parameters
a36a3a3f 1832 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
1833 }
1834
340ea4e8 1835/// Check the cache
aad2ba95 1836 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
1837 return $context_cache[$contextlevel][$instance];
e5605780 1838 }
1839
340ea4e8 1840/// Get it from the database, or create it
aad2ba95 1841 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
1842 create_context($contextlevel, $instance);
1843 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
e5605780 1844 }
1845
ccfc5ecc 1846/// Only add to cache if context isn't empty.
1847 if (!empty($context)) {
aad2ba95 1848 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
ccfc5ecc 1849 $context_cache_id[$context->id] = $context; // Cache it for later
1850 }
0468976c 1851
bbbf2d40 1852 return $context;
1853}
1854
cee0901c 1855
340ea4e8 1856/**
1857 * Get a context instance as an object, from a given id.
1858 * @param $id
1859 */
1860function get_context_instance_by_id($id) {
1861
d9a35e12 1862 global $context_cache, $context_cache_id;
1863
340ea4e8 1864 if (isset($context_cache_id[$id])) { // Already cached
75e84883 1865 return $context_cache_id[$id];
340ea4e8 1866 }
1867
1868 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
aad2ba95 1869 $context_cache[$context->contextlevel][$context->instanceid] = $context;
340ea4e8 1870 $context_cache_id[$context->id] = $context;
1871 return $context;
1872 }
1873
1874 return false;
1875}
1876
bbbf2d40 1877
8737be58 1878/**
1879 * Get the local override (if any) for a given capability in a role in a context
1880 * @param $roleid
0468976c 1881 * @param $contextid
1882 * @param $capability
8737be58 1883 */
1884function get_local_override($roleid, $contextid, $capability) {
1885 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1886}
1887
1888
bbbf2d40 1889
1890/************************************
1891 * DB TABLE RELATED FUNCTIONS *
1892 ************************************/
1893
cee0901c 1894/**
bbbf2d40 1895 * function that creates a role
1896 * @param name - role name
31f26796 1897 * @param shortname - role short name
bbbf2d40 1898 * @param description - role description
1899 * @param legacy - optional legacy capability
1900 * @return id or false
1901 */
8420bee9 1902function create_role($name, $shortname, $description, $legacy='') {
eef868d1 1903
98882637 1904 // check for duplicate role name
eef868d1 1905
98882637 1906 if ($role = get_record('role','name', $name)) {
eef868d1 1907 error('there is already a role with this name!');
98882637 1908 }
eef868d1 1909
31f26796 1910 if ($role = get_record('role','shortname', $shortname)) {
eef868d1 1911 error('there is already a role with this shortname!');
31f26796 1912 }
1913
b5959f30 1914 $role = new object();
98882637 1915 $role->name = $name;
31f26796 1916 $role->shortname = $shortname;
98882637 1917 $role->description = $description;
eef868d1 1918
8420bee9 1919 //find free sortorder number
1920 $role->sortorder = count_records('role');
1921 while (get_record('role','sortorder', $role->sortorder)) {
1922 $role->sortorder += 1;
b5959f30 1923 }
1924
21c9bace 1925 if (!$context = get_context_instance(CONTEXT_SYSTEM)) {
1926 return false;
1927 }
eef868d1 1928
98882637 1929 if ($id = insert_record('role', $role)) {
eef868d1 1930 if ($legacy) {
1931 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
98882637 1932 }
eef868d1 1933
ec7a8b79 1934 /// By default, users with role:manage at site level
1935 /// should be able to assign users to this new role, and override this new role's capabilities
eef868d1 1936
ec7a8b79 1937 // find all admin roles
e46c0987 1938 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
1939 // foreach admin role
1940 foreach ($adminroles as $arole) {
1941 // write allow_assign and allow_overrid
1942 allow_assign($arole->id, $id);
eef868d1 1943 allow_override($arole->id, $id);
e46c0987 1944 }
ec7a8b79 1945 }
eef868d1 1946
98882637 1947 return $id;
1948 } else {
eef868d1 1949 return false;
98882637 1950 }
eef868d1 1951
bbbf2d40 1952}
1953
8420bee9 1954/**
1955 * function that deletes a role and cleanups up after it
1956 * @param roleid - id of role to delete
1957 * @return success
1958 */
1959function delete_role($roleid) {
1960 $success = true;
1961
1962// first unssign all users
1963 if (!role_unassign($roleid)) {
1964 debugging("Error while unassigning all users from role with ID $roleid!");
1965 $success = false;
1966 }
1967
1968// cleanup all references to this role, ignore errors
1969 if ($success) {
1970 delete_records('role_capabilities', 'roleid', $roleid);
1971 delete_records('role_allow_assign', 'roleid', $roleid);
1972 delete_records('role_allow_assign', 'allowassign', $roleid);
1973 delete_records('role_allow_override', 'roleid', $roleid);
1974 delete_records('role_allow_override', 'allowoverride', $roleid);
1975 delete_records('role_names', 'roleid', $roleid);
1976 }
1977
1978// finally delete the role itself
1979 if ($success and !delete_records('role', 'id', $roleid)) {
ece4945b 1980 debugging("Could not delete role record with ID $roleid!");
8420bee9 1981 $success = false;
1982 }
1983
1984 return $success;
1985}
1986
bbbf2d40 1987/**
1988 * Function to write context specific overrides, or default capabilities.
1989 * @param module - string name
1990 * @param capability - string name
1991 * @param contextid - context id
1992 * @param roleid - role id
1993 * @param permission - int 1,-1 or -1000
96986241 1994 * should not be writing if permission is 0
bbbf2d40 1995 */
e7876c1e 1996function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
eef868d1 1997
98882637 1998 global $USER;
eef868d1 1999
96986241 2000 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
eef868d1 2001 unassign_capability($capability, $roleid, $contextid);
96986241 2002 return true;
98882637 2003 }
eef868d1 2004
2e85fffe 2005 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
e7876c1e 2006
2007 if ($existing and !$overwrite) { // We want to keep whatever is there already
2008 return true;
2009 }
2010
bbbf2d40 2011 $cap = new object;
2012 $cap->contextid = $contextid;
2013 $cap->roleid = $roleid;
2014 $cap->capability = $capability;
2015 $cap->permission = $permission;
2016 $cap->timemodified = time();
9db12da7 2017 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
e7876c1e 2018
2019 if ($existing) {
2020 $cap->id = $existing->id;
2021 return update_record('role_capabilities', $cap);
2022 } else {
2023 return insert_record('role_capabilities', $cap);
2024 }
bbbf2d40 2025}
2026
2027
2028/**
2029 * Unassign a capability from a role.
2030 * @param $roleid - the role id
2031 * @param $capability - the name of the capability
2032 * @return boolean - success or failure
2033 */
2034function unassign_capability($capability, $roleid, $contextid=NULL) {
eef868d1 2035
98882637 2036 if (isset($contextid)) {
2037 $status = delete_records('role_capabilities', 'capability', $capability,
2038 'roleid', $roleid, 'contextid', $contextid);
2039 } else {
2040 $status = delete_records('role_capabilities', 'capability', $capability,
2041 'roleid', $roleid);
2042 }
2043 return $status;
bbbf2d40 2044}
2045
2046
2047/**
759ac72d 2048 * Get the roles that have a given capability assigned to it. This function
2049 * does not resolve the actual permission of the capability. It just checks
2050 * for assignment only.
bbbf2d40 2051 * @param $capability - capability name (string)
2052 * @param $permission - optional, the permission defined for this capability
2053 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2054 * @return array or role objects
2055 */
ec7a8b79 2056function get_roles_with_capability($capability, $permission=NULL, $context='') {
2057
bbbf2d40 2058 global $CFG;
eef868d1 2059
ec7a8b79 2060 if ($context) {
2061 if ($contexts = get_parent_contexts($context)) {
2062 $listofcontexts = '('.implode(',', $contexts).')';
2063 } else {
21c9bace 2064 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
eef868d1 2065 $listofcontexts = '('.$sitecontext->id.')'; // must be site
2066 }
42ac3ecf 2067 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
ec7a8b79 2068 } else {
2069 $contextstr = '';
2070 }
eef868d1 2071
2072 $selectroles = "SELECT r.*
42ac3ecf 2073 FROM {$CFG->prefix}role r,
2074 {$CFG->prefix}role_capabilities rc
bbbf2d40 2075 WHERE rc.capability = '$capability'
ec7a8b79 2076 AND rc.roleid = r.id $contextstr";
bbbf2d40 2077
2078 if (isset($permission)) {
2079 $selectroles .= " AND rc.permission = '$permission'";
2080 }
2081 return get_records_sql($selectroles);
2082}
2083
2084
2085/**
a9e1c058 2086 * This function makes a role-assignment (a role for a user or group in a particular context)
bbbf2d40 2087 * @param $roleid - the role of the id
2088 * @param $userid - userid
2089 * @param $groupid - group id
2090 * @param $contextid - id of the context
2091 * @param $timestart - time this assignment becomes effective
2092 * @param $timeend - time this assignemnt ceases to be effective
2093 * @uses $USER
2094 * @return id - new id of the assigment
2095 */
f44152f4 2096function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual') {
aa311411 2097 global $USER, $CFG;
bbbf2d40 2098
7eb0b60a 2099 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER);
bbbf2d40 2100
a9e1c058 2101/// Do some data validation
2102
bbbf2d40 2103 if (empty($roleid)) {
9d829c68 2104 debugging('Role ID not provided');
a9e1c058 2105 return false;
bbbf2d40 2106 }
2107
2108 if (empty($userid) && empty($groupid)) {
9d829c68 2109 debugging('Either userid or groupid must be provided');
a9e1c058 2110 return false;
bbbf2d40 2111 }
eef868d1 2112
7700027f 2113 if ($userid && !record_exists('user', 'id', $userid)) {
82396e5b 2114 debugging('User ID '.intval($userid).' does not exist!');
7700027f 2115 return false;
2116 }
bbbf2d40 2117
f3f7610c 2118 if ($groupid && !groups_group_exists($groupid)) {
82396e5b 2119 debugging('Group ID '.intval($groupid).' does not exist!');
dc411d1b 2120 return false;
2121 }
2122
7700027f 2123 if (!$context = get_context_instance_by_id($contextid)) {
82396e5b 2124 debugging('Context ID '.intval($contextid).' does not exist!');
a9e1c058 2125 return false;
bbbf2d40 2126 }
2127
a9e1c058 2128 if (($timestart and $timeend) and ($timestart > $timeend)) {
9d829c68 2129 debugging('The end time can not be earlier than the start time');
a9e1c058 2130 return false;
2131 }
2132
7700027f 2133
a9e1c058 2134/// Check for existing entry
2135 if ($userid) {
7700027f 2136 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
a9e1c058 2137 } else {
7700027f 2138 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
a9e1c058 2139 }
2140
9ebcb4d2 2141
a9e1c058 2142 $newra = new object;
bbbf2d40 2143
a9e1c058 2144 if (empty($ra)) { // Create a new entry
2145 $newra->roleid = $roleid;
7700027f 2146 $newra->contextid = $context->id;
a9e1c058 2147 $newra->userid = $userid;
a9e1c058 2148 $newra->hidden = $hidden;
f44152f4 2149 $newra->enrol = $enrol;
0616d3e8 2150 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2151 /// by repeating queries with the same exact parameters in a 100 secs time window
2152 $newra->timestart = round($timestart, -2);
a9e1c058 2153 $newra->timeend = $timeend;
2154 $newra->timemodified = time();
115faa2f 2155 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
a9e1c058 2156
9ebcb4d2 2157 $success = insert_record('role_assignments', $newra);
a9e1c058 2158
2159 } else { // We already have one, just update it
2160
2161 $newra->id = $ra->id;
2162 $newra->hidden = $hidden;
f44152f4 2163 $newra->enrol = $enrol;
0616d3e8 2164 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2165 /// by repeating queries with the same exact parameters in a 100 secs time window
2166 $newra->timestart = round($timestart, -2);
a9e1c058 2167 $newra->timeend = $timeend;
2168 $newra->timemodified = time();
115faa2f 2169 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
a9e1c058 2170
9ebcb4d2 2171 $success = update_record('role_assignments', $newra);
2172 }
2173
7700027f 2174 if ($success) { /// Role was assigned, so do some other things
2175
2176 /// If the user is the current user, then reload the capabilities too.
2177 if (!empty($USER->id) && $USER->id == $userid) {
2f1a4248 2178 load_all_capabilities();
7700027f 2179 }
9b5d7a46 2180
0f161e1f 2181 /// Ask all the modules if anything needs to be done for this user
2182 if ($mods = get_list_of_plugins('mod')) {
2183 foreach ($mods as $mod) {
2184 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2185 $functionname = $mod.'_role_assign';
2186 if (function_exists($functionname)) {
a7bb9b8f 2187 $functionname($userid, $context, $roleid);
0f161e1f 2188 }
2189 }
2190 }
2191
2192 /// Make sure they have an entry in user_lastaccess for courses they can access
2193 // role_add_lastaccess_entries($userid, $context);
a9e1c058 2194 }
eef868d1 2195
4e5f3064 2196 /// now handle metacourse role assignments if in course context
aad2ba95 2197 if ($success and $context->contextlevel == CONTEXT_COURSE) {
4e5f3064 2198 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2199 foreach ($parents as $parent) {
1aad4310 2200 sync_metacourse($parent->parent_course);
4e5f3064 2201 }
2202 }
2203 }
6eb4f823 2204
2205 return $success;
bbbf2d40 2206}
2207
2208
2209/**
1dc1f037 2210 * Deletes one or more role assignments. You must specify at least one parameter.
bbbf2d40 2211 * @param $roleid
2212 * @param $userid
2213 * @param $groupid
2214 * @param $contextid
6bc1e5d5 2215 * @param $enrol unassign only if enrolment type matches, NULL means anything
bbbf2d40 2216 * @return boolean - success or failure
2217 */
6bc1e5d5 2218function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
d74067e8 2219
2220 global $USER, $CFG;
eef868d1 2221
4e5f3064 2222 $success = true;
d74067e8 2223
1dc1f037 2224 $args = array('roleid', 'userid', 'groupid', 'contextid');
2225 $select = array();
2226 foreach ($args as $arg) {
2227 if ($$arg) {
2228 $select[] = $arg.' = '.$$arg;
2229 }
2230 }
6bc1e5d5 2231 if (!empty($enrol)) {
2232 $select[] = "enrol='$enrol'";
2233 }
d74067e8 2234
1dc1f037 2235 if ($select) {
4e5f3064 2236 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2237 $mods = get_list_of_plugins('mod');
2238 foreach($ras as $ra) {
86e2c51d 2239 /// infinite loop protection when deleting recursively
2240 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
2241 continue;
2242 }
4e5f3064 2243 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
86e2c51d 2244
4e5f3064 2245 /// If the user is the current user, then reload the capabilities too.
2246 if (!empty($USER->id) && $USER->id == $ra->userid) {
2f1a4248 2247 load_all_capabilities();
4e5f3064 2248 }
2249 $context = get_record('context', 'id', $ra->contextid);
0f161e1f 2250
2251 /// Ask all the modules if anything needs to be done for this user
4e5f3064 2252 foreach ($mods as $mod) {
2253 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2254 $functionname = $mod.'_role_unassign';
2255 if (function_exists($functionname)) {
2256 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
2257 }
2258 }
2259
2260 /// now handle metacourse role unassigment and removing from goups if in course context
aad2ba95 2261 if (!empty($context) and $context->contextlevel == CONTEXT_COURSE) {
4e5f3064 2262 //remove from groups when user has no role
2263 $roles = get_user_roles($context, $ra->userid, true);
2264 if (empty($roles)) {
2265 if ($groups = get_groups($context->instanceid, $ra->userid)) {
2266 foreach ($groups as $group) {
2267 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
2268 }
2269 }
2270 }
1aad4310 2271 //unassign roles in metacourses if needed
4e5f3064 2272 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2273 foreach ($parents as $parent) {
1aad4310 2274 sync_metacourse($parent->parent_course);
0f161e1f 2275 }
2276 }
0f161e1f 2277 }
2278 }
d74067e8 2279 }
1dc1f037 2280 }
4e5f3064 2281
2282 return $success;
bbbf2d40 2283}
2284
efe12f6c 2285/**
eef868d1 2286 * A convenience function to take care of the common case where you
b963384f 2287 * just want to enrol someone using the default role into a course
2288 *
2289 * @param object $course
2290 * @param object $user
2291 * @param string $enrol - the plugin used to do this enrolment
2292 */
2293function enrol_into_course($course, $user, $enrol) {
2294
9492291c 2295 $timestart = time();
b963384f 2296 if ($course->enrolperiod) {
b963384f 2297 $timeend = time() + $course->enrolperiod;
2298 } else {
9492291c 2299 $timeend = 0;
b963384f 2300 }
2301
2302 if ($role = get_default_course_role($course)) {
c4381ef5 2303
2304 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2305
e2183037 2306 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
b963384f 2307 return false;
2308 }
eef868d1 2309
b963384f 2310 email_welcome_message_to_user($course, $user);
eef868d1 2311
b963384f 2312 add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
2313
2314 return true;
2315 }
2316
2317 return false;
2318}
2319
0f161e1f 2320/**
2321 * Add last access times to user_lastaccess as required
2322 * @param $userid
2323 * @param $context
2324 * @return boolean - success or failure
2325 */
2326function role_add_lastaccess_entries($userid, $context) {
2327
2328 global $USER, $CFG;
2329
aad2ba95 2330 if (empty($context->contextlevel)) {
0f161e1f 2331 return false;
2332 }
2333
2334 $lastaccess = new object; // Reusable object below
2335 $lastaccess->userid = $userid;
2336 $lastaccess->timeaccess = 0;
2337
aad2ba95 2338 switch ($context->contextlevel) {
0f161e1f 2339
2340 case CONTEXT_SYSTEM: // For the whole site
2341 if ($courses = get_record('course')) {
2342 foreach ($courses as $course) {
2343 $lastaccess->courseid = $course->id;
2344 role_set_lastaccess($lastaccess);
2345 }
2346 }
2347 break;
2348
2349 case CONTEXT_CATEGORY: // For a whole category
2350 if ($courses = get_record('course', 'category', $context->instanceid)) {
2351 foreach ($courses as $course) {
2352 $lastaccess->courseid = $course->id;
2353 role_set_lastaccess($lastaccess);
2354 }
2355 }
2356 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
2357 foreach ($categories as $category) {
2358 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
2359 role_add_lastaccess_entries($userid, $subcontext);
2360 }
2361 }
2362 break;
eef868d1 2363
0f161e1f 2364
2365 case CONTEXT_COURSE: // For a whole course
2366 if ($course = get_record('course', 'id', $context->instanceid)) {
2367 $lastaccess->courseid = $course->id;
2368 role_set_lastaccess($lastaccess);
2369 }
2370 break;
2371 }
2372}
2373
2374/**
2375 * Delete last access times from user_lastaccess as required
2376 * @param $userid
2377 * @param $context
2378 * @return boolean - success or failure
2379 */
2380function role_remove_lastaccess_entries($userid, $context) {
2381
2382 global $USER, $CFG;
2383
2384}
2385
bbbf2d40 2386
2387/**
2388 * Loads the capability definitions for the component (from file). If no
2389 * capabilities are defined for the component, we simply return an empty array.
2390 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2391 * @return array of capabilities
2392 */
2393function load_capability_def($component) {
2394 global $CFG;
2395
2396 if ($component == 'moodle') {
2397 $defpath = $CFG->libdir.'/db/access.php';
2398 $varprefix = 'moodle';
2399 } else {
0c4d9f49 2400 $compparts = explode('/', $component);
eef868d1 2401
0c4d9f49 2402 if ($compparts[0] == 'block') {
2403 // Blocks are an exception. Blocks directory is 'blocks', and not
2404 // 'block'. So we need to jump through hoops.
2405 $defpath = $CFG->dirroot.'/'.$compparts[0].
2406 's/'.$compparts[1].'/db/access.php';
2407 $varprefix = $compparts[0].'_'.$compparts[1];
ae628043 2408 } else if ($compparts[0] == 'format') {
ce34ed3a 2409 // Similar to the above, course formats are 'format' while they
ae628043 2410 // are stored in 'course/format'.
2411 $defpath = $CFG->dirroot.'/course/'.$component.'/db/access.php';
2412 $varprefix = $compparts[0].'_'.$compparts[1];
ce34ed3a 2413 } else if ($compparts[0] == 'gradeimport') {
2414 $defpath = $CFG->dirroot.'/grade/import/'.$component.'/db/access.php';
2415 $varprefix = $component;
2416 } else if ($compparts[0] == 'gradeexport') {
2417 $defpath = $CFG->dirroot.'/grade/export/'.$component.'/db/access.php';
2418 $varprefix = $component;
2419 } else if ($compparts[0] == 'gradereport') {
2420 $defpath = $CFG->dirroot.'/grade/report/'.$component.'/db/access.php';
2421 $varprefix = $component;
0c4d9f49 2422 } else {
2423 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
2424 $varprefix = str_replace('/', '_', $component);
2425 }
bbbf2d40 2426 }
2427 $capabilities = array();
eef868d1 2428
bbbf2d40 2429 if (file_exists($defpath)) {
dc268b2f 2430 require($defpath);
bbbf2d40 2431 $capabilities = ${$varprefix.'_capabilities'};
2432 }
2433 return $capabilities;
2434}
2435
2436
2437/**
2438 * Gets the capabilities that have been cached in the database for this
2439 * component.
2440 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2441 * @return array of capabilities
2442 */
2443function get_cached_capabilities($component='moodle') {
2444 if ($component == 'moodle') {
2445 $storedcaps = get_records_select('capabilities',
2446 "name LIKE 'moodle/%:%'");
2447 } else {
2448 $storedcaps = get_records_select('capabilities',
2449 "name LIKE '$component:%'");
2450 }
2451 return $storedcaps;
2452}
2453
3562486b 2454/**
2455 * Returns default capabilities for given legacy role type.
2456 *
2457 * @param string legacy role name
2458 * @return array
2459 */
2460function get_default_capabilities($legacyrole) {
2461 if (!$allcaps = get_records('capabilities')) {
2462 error('Error: no capabilitites defined!');
2463 }
2464 $alldefs = array();
2465 $defaults = array();
2466 $components = array();
2467 foreach ($allcaps as $cap) {
efe12f6c 2468 if (!in_array($cap->component, $components)) {
3562486b 2469 $components[] = $cap->component;
2470 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2471 }
2472 }
2473 foreach($alldefs as $name=>$def) {
2474 if (isset($def['legacy'][$legacyrole])) {
2475 $defaults[$name] = $def['legacy'][$legacyrole];
2476 }
2477 }
2478
2479 //some exceptions
2480 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW;
2481 if ($legacyrole == 'admin') {
2482 $defaults['moodle/site:doanything'] = CAP_ALLOW;
2483 }
2484 return $defaults;
2485}
bbbf2d40 2486
efe12f6c 2487/**
2488 * Reset role capabilitites to default according to selected legacy capability.
2489 * If several legacy caps selected, use the first from get_default_capabilities.
2490 * If no legacy selected, removes all capabilities.
2491 *
2492 * @param int @roleid
2493 */
2494function reset_role_capabilities($roleid) {
2495 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2496 $legacyroles = get_legacy_roles();
2497
2498 $defaultcaps = array();
2499 foreach($legacyroles as $ltype=>$lcap) {
2500 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
2501 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
2502 //choose first selected legacy capability
2503 $defaultcaps = get_default_capabilities($ltype);
2504 break;
2505 }
2506 }
2507
2508 delete_records('role_capabilities', 'roleid', $roleid);
2509 if (!empty($defaultcaps)) {
2510 foreach($defaultcaps as $cap=>$permission) {
2511 assign_capability($cap, $permission, $roleid, $sitecontext->id);
2512 }
2513 }
2514}
2515
bbbf2d40 2516/**
2517 * Updates the capabilities table with the component capability definitions.
2518 * If no parameters are given, the function updates the core moodle
2519 * capabilities.
2520 *
2521 * Note that the absence of the db/access.php capabilities definition file
2522 * will cause any stored capabilities for the component to be removed from
eef868d1 2523 * the database.
bbbf2d40 2524 *
2525 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2526 * @return boolean
2527 */
2528function update_capabilities($component='moodle') {
eef868d1 2529
bbbf2d40 2530 $storedcaps = array();
be4486da 2531
2532 $filecaps = load_capability_def($component);
bbbf2d40 2533 $cachedcaps = get_cached_capabilities($component);
2534 if ($cachedcaps) {
2535 foreach ($cachedcaps as $cachedcap) {
2536 array_push($storedcaps, $cachedcap->name);
5e992f56 2537 // update risk bitmasks and context levels in existing capabilities if needed
be4486da 2538 if (array_key_exists($cachedcap->name, $filecaps)) {
2539 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2b531945 2540 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
be4486da 2541 }
2542 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
5e992f56 2543 $updatecap = new object();
be4486da 2544 $updatecap->id = $cachedcap->id;
2545 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2546 if (!update_record('capabilities', $updatecap)) {
5e992f56 2547 return false;
2548 }
2549 }
2550
2551 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2552 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2553 }
2554 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2555 $updatecap = new object();
2556 $updatecap->id = $cachedcap->id;
2557 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2558 if (!update_record('capabilities', $updatecap)) {
be4486da 2559 return false;
2560 }
2561 }
2562 }
bbbf2d40 2563 }
2564 }
be4486da 2565
bbbf2d40 2566 // Are there new capabilities in the file definition?
2567 $newcaps = array();
eef868d1 2568
bbbf2d40 2569 foreach ($filecaps as $filecap => $def) {
eef868d1 2570 if (!$storedcaps ||
bbbf2d40 2571 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2b531945 2572 if (!array_key_exists('riskbitmask', $def)) {
2573 $def['riskbitmask'] = 0; // no risk if not specified
2574 }
bbbf2d40 2575 $newcaps[$filecap] = $def;
2576 }
2577 }
2578 // Add new capabilities to the stored definition.
2579 foreach ($newcaps as $capname => $capdef) {
2580 $capability = new object;
2581 $capability->name = $capname;
2582 $capability->captype = $capdef['captype'];
2583 $capability->contextlevel = $capdef['contextlevel'];
2584 $capability->component = $component;
be4486da 2585 $capability->riskbitmask = $capdef['riskbitmask'];
eef868d1 2586
bbbf2d40 2587 if (!insert_record('capabilities', $capability, false, 'id')) {
2588 return false;
2589 }
eef868d1 2590
bbbf2d40 2591 // Do we need to assign the new capabilities to roles that have the
2592 // legacy capabilities moodle/legacy:* as well?
2593 if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
2594 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2e85fffe 2595 notify('Could not assign legacy capabilities for '.$capname);
bbbf2d40 2596 }
2597 }
2598 // Are there any capabilities that have been removed from the file
2599 // definition that we need to delete from the stored capabilities and
2600 // role assignments?
2601 capabilities_cleanup($component, $filecaps);
eef868d1 2602
bbbf2d40 2603 return true;
2604}
2605
2606
2607/**
2608 * Deletes cached capabilities that are no longer needed by the component.
2609 * Also unassigns these capabilities from any roles that have them.
2610 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2611 * @param $newcapdef - array of the new capability definitions that will be
2612 * compared with the cached capabilities
2613 * @return int - number of deprecated capabilities that have been removed
2614 */
2615function capabilities_cleanup($component, $newcapdef=NULL) {
eef868d1 2616
bbbf2d40 2617 $removedcount = 0;
eef868d1 2618
bbbf2d40 2619 if ($cachedcaps = get_cached_capabilities($component)) {
2620 foreach ($cachedcaps as $cachedcap) {
2621 if (empty($newcapdef) ||
2622 array_key_exists($cachedcap->name, $newcapdef) === false) {
eef868d1 2623
bbbf2d40 2624 // Remove from capabilities cache.
2625 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
2626 error('Could not delete deprecated capability '.$cachedcap->name);
2627 } else {
2628 $removedcount++;
2629 }
2630 // Delete from roles.
2631 if($roles = get_roles_with_capability($cachedcap->name)) {
2632 foreach($roles as $role) {
46943f7b 2633 if (!unassign_capability($cachedcap->name, $role->id)) {
bbbf2d40 2634 error('Could not unassign deprecated capability '.
2635 $cachedcap->name.' from role '.$role->name);
2636 }
2637 }
2638 }
2639 } // End if.
2640 }
2641 }
2642 return $removedcount;
2643}
2644
2645
2646
cee0901c 2647/****************
2648 * UI FUNCTIONS *
2649 ****************/
bbbf2d40 2650
2651
2652/**
2653 * prints human readable context identifier.
2654 */
cd26d8e0 2655function print_context_name($context, $withprefix = true, $short = false) {
340ea4e8 2656
ec0810ee 2657 $name = '';
aad2ba95 2658 switch ($context->contextlevel) {
ec0810ee 2659
bbbf2d40 2660 case CONTEXT_SYSTEM: // by now it's a definite an inherit
8cf990bc 2661 $name = get_string('coresystem');
340ea4e8 2662 break;
bbbf2d40 2663
2664 case CONTEXT_PERSONAL:
ec0810ee 2665 $name = get_string('personal');
340ea4e8 2666 break;
2667
4b10f08b 2668 case CONTEXT_USER:
ec0810ee 2669 if ($user = get_record('user', 'id', $context->instanceid)) {
cd26d8e0 2670 if ($withprefix){
2671 $name = get_string('user').': ';
2672 }
2673 $name .= fullname($user);
ec0810ee 2674 }
340ea4e8 2675 break;
2676
bbbf2d40 2677 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
ec0810ee 2678 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
cd26d8e0 2679 if ($withprefix){
2680 $name = get_string('category').': ';
2681 }
2682 $name .=format_string($category->name);
ec0810ee 2683 }
340ea4e8 2684 break;
bbbf2d40 2685
2686 case CONTEXT_COURSE: // 1 to 1 to course cat
ec0810ee 2687 if ($course = get_record('course', 'id', $context->instanceid)) {
cd26d8e0 2688 if ($withprefix){
2689 if ($context->instanceid == SITEID) {
2690 $name = get_string('site').': ';
2691 } else {
2692 $name = get_string('course').': ';
2693 }
8cf990bc 2694 }
cd26d8e0 2695 if ($short){
2696 $name .=format_string($course->shortname);
2697 } else {
2698 $name .=format_string($course->fullname);
2699 }
2700
ec0810ee 2701 }
340ea4e8 2702 break;
bbbf2d40 2703
2704 case CONTEXT_GROUP: // 1 to 1 to course
f3f7610c 2705 if ($name = groups_get_group_name($context->instanceid)) {
cd26d8e0 2706 if ($withprefix){
2707 $name = get_string('group').': '. $name;
2708 }
ec0810ee 2709 }
340ea4e8 2710 break;
bbbf2d40 2711
2712 case CONTEXT_MODULE: // 1 to 1 to course
98882637 2713 if ($cm = get_record('course_modules','id',$context->instanceid)) {
2714 if ($module = get_record('modules','id',$cm->module)) {
2715 if ($mod = get_record($module->name, 'id', $cm->instance)) {
cd26d8e0 2716 if ($withprefix){
2717 $name = get_string('activitymodule').': ';
2718 }
2719 $name .= $mod->name;
98882637 2720 }
ec0810ee 2721 }
2722 }
340ea4e8 2723 break;
bbbf2d40 2724
2725 case CONTEXT_BLOCK: // 1 to 1 to course
98882637 2726 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
2727 if ($block = get_record('block','id',$blockinstance->blockid)) {
91be52d7 2728 global $CFG;
2729 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
2730 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
2731 $blockname = "block_$block->name";
2732 if ($blockobject = new $blockname()) {
cd26d8e0 2733 if ($withprefix){
2734 $name = get_string('block').': ';
2735 }
2736 $name .= $blockobject->title;
91be52d7 2737 }
ec0810ee 2738 }
2739 }
340ea4e8 2740 break;
bbbf2d40 2741
2742 default:
8388ade8 2743 error ('This is an unknown context (' . $context->contextlevel . ') in print_context_name!');
340ea4e8 2744 return false;
2745
2746 }
340ea4e8 2747 return $name;
bbbf2d40 2748}
2749
2750
2751/**
eef868d1 2752 * Extracts the relevant capabilities given a contextid.
bbbf2d40 2753 * All case based, example an instance of forum context.
2754 * Will fetch all forum related capabilities, while course contexts
2755 * Will fetch all capabilities
0468976c 2756 * @param object context
bbbf2d40 2757 * @return array();
2758 *
2759 * capabilities
2760 * `name` varchar(150) NOT NULL,
2761 * `captype` varchar(50) NOT NULL,
2762 * `contextlevel` int(10) NOT NULL,
2763 * `component` varchar(100) NOT NULL,
2764 */
0468976c 2765function fetch_context_capabilities($context) {
eef868d1 2766
98882637 2767 global $CFG;
bbbf2d40 2768
2769 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
eef868d1 2770
aad2ba95 2771 switch ($context->contextlevel) {
bbbf2d40 2772
98882637 2773 case CONTEXT_SYSTEM: // all
2774 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2775 break;
2776
2777 case CONTEXT_PERSONAL:
0a8a95c9 2778 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
bbbf2d40 2779 break;
eef868d1 2780
4b10f08b 2781 case CONTEXT_USER:
8020a016 2782 $SQL = "SELECT *
2783 FROM {$CFG->prefix}capabilities
2784 WHERE contextlevel = ".CONTEXT_USER;
bbbf2d40 2785 break;
eef868d1 2786
bbbf2d40 2787 case CONTEXT_COURSECAT: // all
98882637 2788 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2789 break;
2790
2791 case CONTEXT_COURSE: // all
98882637 2792 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2793 break;
2794
2795 case CONTEXT_GROUP: // group caps
2796 break;
2797
2798 case CONTEXT_MODULE: // mod caps
98882637 2799 $cm = get_record('course_modules', 'id', $context->instanceid);
2800 $module = get_record('modules', 'id', $cm->module);
eef868d1 2801
98882637 2802 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
2803 and component = 'mod/$module->name'";
bbbf2d40 2804 break;
2805
2806 case CONTEXT_BLOCK: // block caps
98882637 2807 $cb = get_record('block_instance', 'id', $context->instanceid);
2808 $block = get_record('block', 'id', $cb->blockid);
eef868d1 2809
98882637 2810 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
2811 and component = 'block/$block->name'";
bbbf2d40 2812 break;
2813
2814 default:
2815 return false;
2816 }
2817
16e2e2f3 2818 if (!$records = get_records_sql($SQL.' '.$sort)) {
2819 $records = array();
2820 }
ba8d8027 2821
2822/// the rest of code is a bit hacky, think twice before modifying it :-(
69eb59f2 2823
2824 // special sorting of core system capabiltites and enrollments
e9c82dca 2825 if (in_array($context->contextlevel, array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE))) {
69eb59f2 2826 $first = array();
2827 foreach ($records as $key=>$record) {
2828 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
2829 $first[$key] = $record;
2830 unset($records[$key]);
2831 } else if (count($first)){
2832 break;
2833 }
2834 }
2835 if (count($first)) {
2836 $records = $first + $records; // merge the two arrays keeping the keys
2837 }
ba8d8027 2838 } else {
2839 $contextindependentcaps = fetch_context_independent_capabilities();
2840 $records = array_merge($contextindependentcaps, $records);
69eb59f2 2841 }
ba8d8027 2842
bbbf2d40 2843 return $records;
eef868d1 2844
bbbf2d40 2845}
2846
2847
759ac72d 2848/**
2849 * Gets the context-independent capabilities that should be overrridable in
2850 * any context.
2851 * @return array of capability records from the capabilities table.
2852 */
2853function fetch_context_independent_capabilities() {
eef868d1 2854
17e5635c 2855 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
759ac72d 2856 $contextindependentcaps = array(
2857 'moodle/site:accessallgroups'
2858 );
2859
2860 $records = array();
eef868d1 2861
759ac72d 2862 foreach ($contextindependentcaps as $capname) {
2863 $record = get_record('capabilities', 'name', $capname);
2864 array_push($records, $record);
2865 }
2866 return $records;
2867}
2868
2869
bbbf2d40 2870/**
2871 * This function pulls out all the resolved capabilities (overrides and
759ac72d 2872 * defaults) of a role used in capability overrides in contexts at a given
bbbf2d40 2873 * context.
0a8a95c9 2874 * @param obj $context
bbbf2d40 2875 * @param int $roleid
dc558690 2876 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
bbbf2d40 2877 * @return array
2878 */
1648afb2 2879function role_context_capabilities($roleid, $context, $cap='') {
dc558690 2880 global $CFG;
eef868d1 2881
8521d83a 2882 $contexts = get_parent_contexts($context);
2883 $contexts[] = $context->id;
98882637 2884 $contexts = '('.implode(',', $contexts).')';
eef868d1 2885
1648afb2 2886 if ($cap) {
e4697bf7 2887 $search = " AND rc.capability = '$cap' ";
1648afb2 2888 } else {
eef868d1 2889 $search = '';
1648afb2 2890 }
eef868d1 2891
2892 $SQL = "SELECT rc.*
2893 FROM {$CFG->prefix}role_capabilities rc,
dc558690 2894 {$CFG->prefix}context c
2895 WHERE rc.contextid in $contexts
2896 AND rc.roleid = $roleid
2897 AND rc.contextid = c.id $search
aad2ba95 2898 ORDER BY c.contextlevel DESC,
eef868d1 2899 rc.capability DESC";
759ac72d 2900
98882637 2901 $capabilities = array();
eef868d1 2902
4729012f 2903 if ($records = get_records_sql($SQL)) {
2904 // We are traversing via reverse order.
2905 foreach ($records as $record) {
2906 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2907 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2908 $capabilities[$record->capability] = $record->permission;
eef868d1 2909 }
4729012f 2910 }
98882637 2911 }
2912 return $capabilities;
bbbf2d40 2913}
2914
bbbf2d40 2915/**
eef868d1 2916 * Recursive function which, given a context, find all parent context ids,
bbbf2d40 2917 * and return the array in reverse order, i.e. parent first, then grand
2918 * parent, etc.
2919 * @param object $context
2920 * @return array()
2921 */
bbbf2d40 2922function get_parent_contexts($context) {
759ac72d 2923
1cd03601 2924 static $pcontexts; // cache
2925 if (isset($pcontexts[$context->id])) {
2926 return ($pcontexts[$context->id]);
2927 }
2928
aad2ba95 2929 switch ($context->contextlevel) {
bbbf2d40 2930
2931 case CONTEXT_SYSTEM: // no parent
957861f7 2932 return array();
bbbf2d40 2933 break;
2934
2935 case CONTEXT_PERSONAL:
21c9bace 2936 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
957861f7 2937 return array();
2938 } else {
1cd03601 2939 $res = array($parent->id);
0de75c4c 2940 $pcontexts[$context->id] = $res;
1cd03601 2941 return $res;
957861f7 2942 }
bbbf2d40 2943 break;
eef868d1 2944
4b10f08b 2945 case CONTEXT_USER:
21c9bace 2946 if (!$parent = get_context_instance(CONTEXT_SYSTEM)) {
957861f7 2947 return array();
2948 } else {
1cd03601 2949 $res = array($parent->id);
0de75c4c 2950 $pcontexts[$context->id] = $res;
1cd03601 2951 return $res;
957861f7 2952 }
bbbf2d40 2953 break;
eef868d1 2954
bbbf2d40 2955 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
957861f7 2956 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
2957 return array();
2958 }
c5ddc3fd 2959 if (!empty($coursecat->parent)) { // return parent value if exist
bbbf2d40 2960 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1cd03601 2961 $res = array_merge(array($parent->id), get_parent_contexts($parent));
2962 $pcontexts[$context->id] = $res;
2963 return $res;
bbbf2d40 2964 } else { // else return site value
21c9bace 2965 $parent = get_context_instance(CONTEXT_SYSTEM);
1cd03601 2966 $res = array($parent->id);
2967 $pcontexts[$context->id] = $res;
2968 return $res;
bbbf2d40 2969 }
2970 break;
2971
2972 case CONTEXT_COURSE: // 1 to 1 to course cat
957861f7 2973 if (!$course = get_record('course','id',$context->instanceid)) {
2974 return array();
2975 }
1936c10e 2976 if ($course->id != SITEID) {
957861f7 2977 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1cd03601 2978 $res = array_merge(array($parent->id), get_parent_contexts($parent));
2979 return $res;
957861f7 2980 } else {
40a2a15f 2981 // Yu: Separating site and site course context
2982 $parent = get_context_instance(CONTEXT_SYSTEM);
1cd03601 2983 $res = array($parent->id);
2984 $pcontexts[$context->id] = $res;
2985 return $res;
957861f7 2986 }
bbbf2d40 2987 break;
2988
2989 case CONTEXT_GROUP: // 1 to 1 to course
f3f7610c 2990 if (! $group = groups_get_group($context->instanceid)) {
957861f7 2991 return array();
2992 }
2993 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
1cd03601 2994 $res = array_merge(array($parent->id), get_parent_contexts($parent));
2995 $pcontexts[$context->id] = $res;
2996 return $res;
957861f7 2997 } else {
2998 return array();
2999 }
bbbf2d40 3000 break;
3001
3002 case CONTEXT_MODULE: // 1 to 1 to course
957861f7 3003 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
3004 return array();
3005 }
3006 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
1cd03601 3007 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3008 $pcontexts[$context->id] = $res;
3009 return $res;
957861f7 3010 } else {
3011 return array();
3012 }
bbbf2d40 3013 break;
3014
3015 case CONTEXT_BLOCK: // 1 to 1 to course
957861f7 3016 if (!$block = get_record('block_instance','id',$context->instanceid)) {
3017 return array();
3018 }
6ceebc1f 3019 // fix for MDL-9656, block parents are not necessarily courses
3020 if ($block->pagetype == 'course-view') {
3021 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid);
3022 } else {
3023 $parent = get_context_instance(CONTEXT_SYSTEM);
3024 }
3025
3026 if ($parent) {
1cd03601 3027 $res = array_merge(array($parent->id), get_parent_contexts($parent));
3028 $pcontexts[$context->id] = $res;
3029 return $res;
957861f7 3030 } else {
6ceebc1f 3031 return array();
957861f7 3032 }
bbbf2d40 3033 break;
3034
3035 default:
8388ade8 3036 error('This is an unknown context (' . $context->contextlevel . ') in get_parent_contexts!');
bbbf2d40 3037 return false;
3038 }
bbbf2d40 3039}
3040
759ac72d 3041
cdfa3035 3042/**
3043 * Recursive function which, given a context, find all its children context ids.
3044 * @param object $context.
3045 * @return array of children context ids.
3046 */
3047function get_child_contexts($context) {
3048
3049 global $CFG;
3050 $children = array();
3051
3052 switch ($context->contextlevel) {
3053
3054 case CONTEXT_BLOCK:
3055 // No children.
3056 return array();
3057 break;
3058
3059 case CONTEXT_MODULE:
3060 // No children.
3061 return array();
3062 break;
3063
3064 case CONTEXT_GROUP:
3065 // No children.
3066 return array();
3067 break;
3068
3069 case CONTEXT_COURSE:
3070 // Find all block instances for the course.
3071 $page = new page_course;
3072 $page->id = $context->instanceid;
3073 $page->type = 'course-view';
3074 if ($blocks = blocks_get_by_page_pinned($page)) {
3075 foreach ($blocks['l'] as $leftblock) {
2b91b669 3076 if ($child = get_context_instance(CONTEXT_BLOCK, $leftblock->id)) {
cdfa3035 3077 array_push($children, $child->id);
3078 }
3079 }
3080 foreach ($blocks['r'] as $rightblock) {
2b91b669 3081 if ($child = get_context_instance(CONTEXT_BLOCK, $rightblock->id)) {
cdfa3035 3082 array_push($children, $child->id);
3083 }
3084 }
3085 }
3086 // Find all module instances for the course.
3087 if ($modules = get_records('course_modules', 'course', $context->instanceid)) {
3088 foreach ($modules as $module) {
3089 if ($child = get_context_instance(CONTEXT_MODULE, $module->id)) {
3090 array_push($children, $child->id);
3091 }
3092 }
3093 }
3094 // Find all group instances for the course.
2b91b669 3095 if ($groupids = groups_get_groups($context->instanceid)) {
3096 foreach ($groupids as $groupid) {
3097 if ($child = get_context_instance(CONTEXT_GROUP, $groupid)) {
cdfa3035 3098 array_push($children, $child->id);
3099 }
3100 }
3101 }
3102 return $children;
3103 break;
3104
3105 case CONTEXT_COURSECAT:
3106 // We need to get the contexts for:
3107 // 1) The subcategories of the given category
3108 // 2) The courses in the given category and all its subcategories
3109 // 3) All the child contexts for these courses
3110
3111 $categories = get_all_subcategories($context->instanceid);
3112
3113 // Add the contexts for all the subcategories.
3114 foreach ($categories as $catid) {
3115 if ($catci = get_context_instance(CONTEXT_COURSECAT, $catid)) {
3116 array_push($children, $catci->id);
3117 }
3118 }
3119
3120 // Add the parent category as well so we can find the contexts
3121 // for its courses.
3122 array_unshift($categories, $context->instanceid);
3123
3124 foreach ($categories as $catid) {
3125 // Find all courses for the category.
3126 if ($courses = get_records('course', 'category', $catid)) {
3127 foreach ($courses as $course) {
3128 if ($courseci = get_context_instance(CONTEXT_COURSE, $course->id)) {
3129 array_push($children, $courseci->id);
3130 $children = array_merge($children, get_child_contexts($courseci));
3131 }
3132 }
3133 }
3134 }
3135 return $children;
3136 break;
3137
3138 case CONTEXT_USER:
3139 // No children.
3140 return array();
3141 break;
3142
3143 case CONTEXT_PERSONAL:
3144 // No children.
3145 return array();
3146 break;
3147
3148 case CONTEXT_SYSTEM:
3149 // Just get all the contexts except for CONTEXT_SYSTEM level.
3150 $sql = 'SELECT c.id '.
3151 'FROM '.$CFG->prefix.'context AS c '.
3152 'WHERE contextlevel != '.CONTEXT_SYSTEM;
3153
3154 $contexts = get_records_sql($sql);
3155 foreach ($contexts as $cid) {
3156 array_push($children, $cid->id);
3157 }
3158 return $children;
3159 break;
3160
3161 default:
8388ade8 3162 error('This is an unknown context (' . $context->contextlevel . ') in get_child_contexts!');
cdfa3035 3163 return false;
3164 }
3165}
3166
3167
759ac72d 3168/**
3169 * Gets a string for sql calls, searching for stuff in this context or above
ea8158c1 3170 * @param object $context
3171 * @return string
3172 */
3173function get_related_contexts_string($context) {
3174 if ($parents = get_parent_contexts($context)) {
eef868d1 3175 return (' IN ('.$context->id.','.implode(',', $parents).')');
ea8158c1 3176 } else {
3177 return (' ='.$context->id);
3178 }
3179}
759ac72d 3180
3181
bbbf2d40 3182/**
3183 * This function gets the capability of a role in a given context.
3184 * It is needed when printing override forms.
3185 * @param int $contextid
bbbf2d40 3186 * @param string $capability
3187 * @param array $capabilities - array loaded using role_context_capabilities
3188 * @return int (allow, prevent, prohibit, inherit)
3189 */
bbbf2d40 3190function get_role_context_capability($contextid, $capability, $capabilities) {
759ac72d 3191 if (isset($capabilities[$contextid][$capability])) {
3192 return $capabilities[$contextid][$capability];
3193 }
3194 else {
3195 return false;
3196 }
bbbf2d40 3197}
3198
3199
cee0901c 3200/**
3201 * Returns the human-readable, translated version of the capability.
3202 * Basically a big switch statement.
3203 * @param $capabilityname - e.g. mod/choice:readresponses
3204 */
ceb83c70 3205function get_capability_string($capabilityname) {
eef868d1 3206
cee0901c 3207 // Typical capabilityname is mod/choice:readresponses
ceb83c70 3208
3209 $names = split('/', $capabilityname);
3210 $stringname = $names[1]; // choice:readresponses
eef868d1 3211 $components = split(':', $stringname);
ceb83c70 3212 $componentname = $components[0]; // choice
98882637 3213
3214 switch ($names[0]) {
3215 case 'mod':
ceb83c70 3216 $string = get_string($stringname, $componentname);
98882637 3217 break;
eef868d1 3218