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