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