sanitise request in create_context() and show debug info when appropriate MDL-6715
[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])) {
7eb0b60a 432 debugging("Found $capability in context $context->id at level $context->contextlevel: ".$capabilities[$context->id][$capability], DEBUG_DEVELOPER);
0468976c 433 return ($capabilities[$context->id][$capability]);
bbbf2d40 434 }
9425b25f 435
bbbf2d40 436 /* Then, we check the cache recursively */
9425b25f 437 $permission = 0;
438
aad2ba95 439 switch ($context->contextlevel) {
bbbf2d40 440
441 case CONTEXT_SYSTEM: // by now it's a definite an inherit
442 $permission = 0;
443 break;
444
445 case CONTEXT_PERSONAL:
0468976c 446 $parentcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
447 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 448 break;
9425b25f 449
4b10f08b 450 case CONTEXT_USER:
0468976c 451 $parentcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
452 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 453 break;
9425b25f 454
bbbf2d40 455 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
456 $coursecat = get_record('course_categories','id',$context->instanceid);
0468976c 457 if (!empty($coursecat->parent)) { // return parent value if it exists
458 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
bbbf2d40 459 } else { // else return site value
0468976c 460 $parentcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
bbbf2d40 461 }
0468976c 462 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 463 break;
464
465 case CONTEXT_COURSE: // 1 to 1 to course cat
466 // find the course cat, and return its value
467 $course = get_record('course','id',$context->instanceid);
0468976c 468 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $course->category);
469 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 470 break;
471
472 case CONTEXT_GROUP: // 1 to 1 to course
473 $group = get_record('groups','id',$context->instanceid);
0468976c 474 $parentcontext = get_context_instance(CONTEXT_COURSE, $group->courseid);
475 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 476 break;
477
478 case CONTEXT_MODULE: // 1 to 1 to course
479 $cm = get_record('course_modules','id',$context->instanceid);
0468976c 480 $parentcontext = get_context_instance(CONTEXT_COURSE, $cm->course);
481 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 482 break;
483
484 case CONTEXT_BLOCK: // 1 to 1 to course
485 $block = get_record('block_instance','id',$context->instanceid);
0468976c 486 $parentcontext = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
487 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 488 break;
489
490 default:
491 error ('This is an unknown context!');
492 return false;
493 }
7eb0b60a 494 debugging("Found $capability recursively from context $context->id at level $context->contextlevel: $permission", DEBUG_DEVELOPER);
9425b25f 495
98882637 496 return $permission;
bbbf2d40 497}
498
499
500/**
501 * This function should be called immediately after a login, when $USER is set.
502 * It will build an array of all the capabilities at each level
503 * i.e. site/metacourse/course_category/course/moduleinstance
504 * Note we should only load capabilities if they are explicitly assigned already,
505 * we should not load all module's capability!
506 * @param $userid - the id of the user whose capabilities we want to load
507 * @return array
508 * possible just s simple 2D array with [contextid][capabilityname]
509 * [Capabilities] => [26][forum_post] = 1
510 * [26][forum_start] = -8990
511 * [26][forum_edit] = -1
512 * [273][blah blah] = 1
513 * [273][blah blah blah] = 2
514 */
0468976c 515function load_user_capability($capability='', $context ='', $userid='') {
d140ad3f 516
98882637 517 global $USER, $CFG;
bbbf2d40 518
519 if (empty($userid)) {
dc411d1b 520 if (empty($USER->id)) { // We have no user to get capabilities for
64026e8c 521 debugging('User not logged in for load_user_capability!');
dc411d1b 522 return false;
523 }
64026e8c 524 unset($USER->capabilities); // We don't want possible older capabilites hanging around
525
526 check_enrolment_plugins($USER); // Call "enrol" system to ensure that we have the correct picture
8f8ed475 527
bbbf2d40 528 $userid = $USER->id;
dc411d1b 529 $otheruserid = false;
bbbf2d40 530 } else {
64026e8c 531 if (!$user = get_record('user', 'id', $userid)) {
532 debugging('Non-existent userid in load_user_capability!');
533 return false;
534 }
535
536 check_enrolment_plugins($user); // Ensure that we have the correct picture
537
9425b25f 538 $otheruserid = $userid;
bbbf2d40 539 }
9425b25f 540
5f70bcc3 541
542/// First we generate a list of all relevant contexts of the user
543
544 $usercontexts = array();
bbbf2d40 545
0468976c 546 if ($context) { // if context is specified
eef868d1 547 $usercontexts = get_parent_contexts($context);
98882637 548 } else { // else, we load everything
5f70bcc3 549 if ($userroles = get_records('role_assignments','userid',$userid)) {
550 foreach ($userroles as $userrole) {
551 $usercontexts[] = $userrole->contextid;
552 }
98882637 553 }
5f70bcc3 554 }
555
556/// Set up SQL fragments for searching contexts
557
558 if ($usercontexts) {
0468976c 559 $listofcontexts = '('.implode(',', $usercontexts).')';
5f70bcc3 560 $searchcontexts1 = "c1.id IN $listofcontexts AND";
5f70bcc3 561 } else {
c76e095f 562 $searchcontexts1 = '';
bbbf2d40 563 }
3ca2dea5 564
64026e8c 565 if ($capability) {
566 $capsearch = " AND rc.capability = '$capability' ";
567 } else {
eef868d1 568 $capsearch ="";
64026e8c 569 }
570
e38f38c3 571/// Set up SQL fragments for timestart, timeend etc
572 $now = time();
85f101fa 573 $timesql = "AND ((ra.timestart = 0 OR ra.timestart < $now) AND (ra.timeend = 0 OR ra.timeend > $now))";
e38f38c3 574
5f70bcc3 575/// Then we use 1 giant SQL to bring out all relevant capabilities.
576/// The first part gets the capabilities of orginal role.
577/// The second part gets the capabilities of overriden roles.
bbbf2d40 578
98882637 579 $siteinstance = get_context_instance(CONTEXT_SYSTEM, SITEID);
bbbf2d40 580
c76e095f 581 $SQL = " SELECT rc.capability, c1.id, (c1.contextlevel * 100) AS aggrlevel,
bbbf2d40 582 SUM(rc.permission) AS sum
583 FROM
eef868d1 584 {$CFG->prefix}role_assignments ra,
42ac3ecf 585 {$CFG->prefix}role_capabilities rc,
586 {$CFG->prefix}context c1
bbbf2d40 587 WHERE
d4649c76 588 ra.contextid=c1.id AND
589 ra.roleid=rc.roleid AND
bbbf2d40 590 ra.userid=$userid AND
5f70bcc3 591 $searchcontexts1
eef868d1 592 rc.contextid=$siteinstance->id
98882637 593 $capsearch
e38f38c3 594 $timesql
bbbf2d40 595 GROUP BY
aad2ba95 596 rc.capability, (c1.contextlevel * 100), c1.id
bbbf2d40 597 HAVING
41811960 598 SUM(rc.permission) != 0
bbbf2d40 599 UNION
600
c76e095f 601 SELECT rc.capability, c2.id, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
bbbf2d40 602 SUM(rc.permission) AS sum
603 FROM
42ac3ecf 604 {$CFG->prefix}role_assignments ra,
605 {$CFG->prefix}role_capabilities rc,
606 {$CFG->prefix}context c1,
607 {$CFG->prefix}context c2
bbbf2d40 608 WHERE
d4649c76 609 ra.contextid=c1.id AND
eef868d1 610 ra.roleid=rc.roleid AND
611 ra.userid=$userid AND
612 rc.contextid=c2.id AND
5f70bcc3 613 $searchcontexts1
5f70bcc3 614 rc.contextid != $siteinstance->id
bbbf2d40 615 $capsearch
e38f38c3 616 $timesql
eef868d1 617
bbbf2d40 618 GROUP BY
c76e095f 619 rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c2.id, c1.id
bbbf2d40 620 HAVING
41811960 621 SUM(rc.permission) != 0
bbbf2d40 622 ORDER BY
75e84883 623 aggrlevel ASC
bbbf2d40 624 ";
625
98882637 626 $capabilities = array(); // Reinitialize.
75e84883 627 if (!$rs = get_recordset_sql($SQL)) {
628 error("Query failed in load_user_capability.");
629 }
5cf38a57 630
bbbf2d40 631 if ($rs && $rs->RecordCount() > 0) {
632 while (!$rs->EOF) {
75e84883 633 $array = $rs->fields;
634 $temprecord = new object;
eef868d1 635
98882637 636 foreach ($array as $key=>$val) {
75e84883 637 if ($key == 'aggrlevel') {
aad2ba95 638 $temprecord->contextlevel = $val;
75e84883 639 } else {
640 $temprecord->{$key} = $val;
641 }
98882637 642 }
bbbf2d40 643 $capabilities[] = $temprecord;
644 $rs->MoveNext();
645 }
646 }
eef868d1 647
bbbf2d40 648 /* so up to this point we should have somethign like this
aad2ba95 649 * $capabilities[1] ->contextlevel = 1000
bbbf2d40 650 ->module = SITEID
651 ->capability = do_anything
652 ->id = 1 (id is the context id)
653 ->sum = 0
eef868d1 654
aad2ba95 655 * $capabilities[2] ->contextlevel = 1000
bbbf2d40 656 ->module = SITEID
657 ->capability = post_messages
658 ->id = 1
659 ->sum = -9000
660
aad2ba95 661 * $capabilittes[3] ->contextlevel = 3000
bbbf2d40 662 ->module = course
663 ->capability = view_course_activities
664 ->id = 25
665 ->sum = 1
666
aad2ba95 667 * $capabilittes[4] ->contextlevel = 3000
bbbf2d40 668 ->module = course
669 ->capability = view_course_activities
670 ->id = 26
671 ->sum = 0 (this is another course)
eef868d1 672
aad2ba95 673 * $capabilities[5] ->contextlevel = 3050
bbbf2d40 674 ->module = course
675 ->capability = view_course_activities
676 ->id = 25 (override in course 25)
677 ->sum = -1
678 * ....
679 * now we proceed to write the session array, going from top to bottom
680 * at anypoint, we need to go up and check parent to look for prohibit
681 */
682 // print_object($capabilities);
683
684 /* This is where we write to the actualy capabilities array
685 * what we need to do from here on is
686 * going down the array from lowest level to highest level
687 * 1) recursively check for prohibit,
688 * if any, we write prohibit
689 * else, we write the value
690 * 2) at an override level, we overwrite current level
691 * if it's not set to prohibit already, and if different
692 * ........ that should be it ........
693 */
98882637 694 $usercap = array(); // for other user's capabilities
bbbf2d40 695 foreach ($capabilities as $capability) {
696
0468976c 697 $context = get_context_instance_by_id($capability->id);
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
933
934 // Look inside user_admin, user_creator, user_teachers, user_students and
935 // assign above new roles. If a user has both teacher and student role,
936 // only teacher role is assigned. The assignment should be system level.
937 $dbtables = $db->MetaTables('TABLES');
eef868d1 938
1afecc03 939
98882637 940 /**
bbbf2d40 941 * Upgrade the admins.
1afecc03 942 * Sort using id ASC, first one is primary admin.
bbbf2d40 943 */
1afecc03 944 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
f1dcf000 945 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
946 while (! $rs->EOF) {
947 $admin = $rs->FetchObj();
1afecc03 948 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
f1dcf000 949 $rs->MoveNext();
1afecc03 950 }
951 }
952 } else {
953 // This is a fresh install.
bbbf2d40 954 }
1afecc03 955
956
bbbf2d40 957 /**
958 * Upgrade course creators.
959 */
1afecc03 960 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
f1dcf000 961 if ($rs = get_recordset('user_coursecreators')) {
962 while (! $rs->EOF) {
963 $coursecreator = $rs->FetchObj();
56b4d70d 964 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
f1dcf000 965 $rs->MoveNext();
1afecc03 966 }
967 }
bbbf2d40 968 }
969
1afecc03 970
bbbf2d40 971 /**
972 * Upgrade editting teachers and non-editting teachers.
973 */
1afecc03 974 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
f1dcf000 975 if ($rs = get_recordset('user_teachers')) {
976 while (! $rs->EOF) {
977 $teacher = $rs->FetchObj();
978
17d6a25e 979 // populate the user_lastaccess table
ece4945b 980 $access = new object();
17d6a25e 981 $access->timeaccess = $teacher->timeaccess;
982 $access->userid = $teacher->userid;
983 $access->courseid = $teacher->course;
984 insert_record('user_lastaccess', $access);
f1dcf000 985
17d6a25e 986 // assign the default student role
1afecc03 987 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
988 if ($teacher->editall) { // editting teacher
989 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id);
990 } else {
991 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id);
992 }
f1dcf000 993
994 $rs->MoveNext();
1afecc03 995 }
bbbf2d40 996 }
997 }
1afecc03 998
999
bbbf2d40 1000 /**
1001 * Upgrade students.
1002 */
1afecc03 1003 if (in_array($CFG->prefix.'user_students', $dbtables)) {
f1dcf000 1004 if ($rs = get_recordset('user_students')) {
1005 while (! $rs->EOF) {
1006 $student = $rs->FetchObj();
1007
17d6a25e 1008 // populate the user_lastaccess table
f1dcf000 1009 $access = new object;
17d6a25e 1010 $access->timeaccess = $student->timeaccess;
1011 $access->userid = $student->userid;
1012 $access->courseid = $student->course;
1013 insert_record('user_lastaccess', $access);
f1dcf000 1014
17d6a25e 1015 // assign the default student role
1afecc03 1016 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
1017 role_assign($studentrole, $student->userid, 0, $coursecontext->id);
f1dcf000 1018
1019 $rs->MoveNext();
1afecc03 1020 }
1021 }
bbbf2d40 1022 }
1afecc03 1023
1024
bbbf2d40 1025 /**
1026 * Upgrade guest (only 1 entry).
1027 */
1afecc03 1028 if ($guestuser = get_record('user', 'username', 'guest')) {
1029 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
1030 }
1031
945f88ca 1032 /**
eef868d1 1033 * Insert the correct records for legacy roles
945f88ca 1034 */
1035 allow_assign($adminrole, $adminrole);
1036 allow_assign($adminrole, $coursecreatorrole);
1037 allow_assign($adminrole, $noneditteacherrole);
eef868d1 1038 allow_assign($adminrole, $editteacherrole);
945f88ca 1039 allow_assign($adminrole, $studentrole);
1040 allow_assign($adminrole, $guestrole);
eef868d1 1041
945f88ca 1042 allow_assign($coursecreatorrole, $noneditteacherrole);
1043 allow_assign($coursecreatorrole, $editteacherrole);
eef868d1 1044 allow_assign($coursecreatorrole, $studentrole);
945f88ca 1045 allow_assign($coursecreatorrole, $guestrole);
eef868d1 1046
1047 allow_assign($editteacherrole, $noneditteacherrole);
1048 allow_assign($editteacherrole, $studentrole);
945f88ca 1049 allow_assign($editteacherrole, $guestrole);
eef868d1 1050
945f88ca 1051 /// overrides
1052 allow_override($adminrole, $adminrole);
1053 allow_override($adminrole, $coursecreatorrole);
1054 allow_override($adminrole, $noneditteacherrole);
eef868d1 1055 allow_override($adminrole, $editteacherrole);
945f88ca 1056 allow_override($adminrole, $studentrole);
eef868d1 1057 allow_override($adminrole, $guestrole);
1afecc03 1058
746a04c5 1059
1afecc03 1060 // Should we delete the tables after we are done? Not yet.
bbbf2d40 1061}
1062
bbbf2d40 1063/**
1064 * Assign the defaults found in this capabality definition to roles that have
1065 * the corresponding legacy capabilities assigned to them.
1066 * @param $legacyperms - an array in the format (example):
1067 * 'guest' => CAP_PREVENT,
1068 * 'student' => CAP_ALLOW,
1069 * 'teacher' => CAP_ALLOW,
1070 * 'editingteacher' => CAP_ALLOW,
1071 * 'coursecreator' => CAP_ALLOW,
1072 * 'admin' => CAP_ALLOW
1073 * @return boolean - success or failure.
1074 */
1075function assign_legacy_capabilities($capability, $legacyperms) {
eef868d1 1076
bbbf2d40 1077 foreach ($legacyperms as $type => $perm) {
eef868d1 1078
bbbf2d40 1079 $systemcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
eef868d1 1080
bbbf2d40 1081 // The legacy capabilities are:
1082 // 'moodle/legacy:guest'
1083 // 'moodle/legacy:student'
1084 // 'moodle/legacy:teacher'
1085 // 'moodle/legacy:editingteacher'
1086 // 'moodle/legacy:coursecreator'
1087 // 'moodle/legacy:admin'
eef868d1 1088
2e85fffe 1089 if ($roles = get_roles_with_capability('moodle/legacy:'.$type, CAP_ALLOW)) {
1090 foreach ($roles as $role) {
1091 // Assign a site level capability.
1092 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1093 return false;
1094 }
bbbf2d40 1095 }
1096 }
1097 }
1098 return true;
1099}
1100
1101
cee0901c 1102/**
1103 * Checks to see if a capability is a legacy capability.
1104 * @param $capabilityname
1105 * @return boolean
1106 */
bbbf2d40 1107function islegacy($capabilityname) {
98882637 1108 if (strstr($capabilityname, 'legacy') === false) {
eef868d1 1109 return false;
98882637 1110 } else {
eef868d1 1111 return true;
98882637 1112 }
bbbf2d40 1113}
1114
cee0901c 1115
1116
1117/**********************************
bbbf2d40 1118 * Context Manipulation functions *
1119 **********************************/
1120
bbbf2d40 1121/**
9991d157 1122 * Create a new context record for use by all roles-related stuff
bbbf2d40 1123 * @param $level
1124 * @param $instanceid
3ca2dea5 1125 *
1126 * @return object newly created context (or existing one with a debug warning)
bbbf2d40 1127 */
aad2ba95 1128function create_context($contextlevel, $instanceid) {
3ca2dea5 1129 if (!$context = get_record('context','contextlevel',$contextlevel,'instanceid',$instanceid)) {
1130 if (!validate_context($contextlevel, $instanceid)) {
1131 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1132 return NULL;
1133 }
1134 $context = new object();
aad2ba95 1135 $context->contextlevel = $contextlevel;
bbbf2d40 1136 $context->instanceid = $instanceid;
3ca2dea5 1137 if ($id = insert_record('context',$context)) {
1138 return get_record('context','id',$id);
1139 } else {
1140 debugging('Error: could not insert new context level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1141 return NULL;
1142 }
1143 } else {
1144 debugging('Warning: Context id "'.s($context->id).'" not created, because it already exists.');
1145 return $context;
bbbf2d40 1146 }
1147}
1148
9991d157 1149/**
1150 * Create a new context record for use by all roles-related stuff
1151 * @param $level
1152 * @param $instanceid
3ca2dea5 1153 *
1154 * @return true if properly deleted
9991d157 1155 */
1156function delete_context($contextlevel, $instanceid) {
1157 if ($context = get_context_instance($contextlevel, $instanceid)) {
1158 return delete_records('context', 'id', $context->id) &&
1159 delete_records('role_assignments', 'contextid', $context->id) &&
1160 delete_records('role_role_capabilities', 'contextid', $context->id);
1161 }
1162 return true;
1163}
1164
3ca2dea5 1165/**
1166 * Validate that object with instanceid really exists in given context level.
1167 *
1168 * return if instanceid object exists
1169 */
1170function validate_context($contextlevel, $instanceid) {
1171 switch ($contextlevel) {
1172
1173 case CONTEXT_SYSTEM:
1174 return ($instanceid == SITEID);
1175
1176 case CONTEXT_PERSONAL:
1177 return (boolean)count_records('user', 'id', $instanceid);
1178
1179 case CONTEXT_USER:
1180 return (boolean)count_records('user', 'id', $instanceid);
1181
1182 case CONTEXT_COURSECAT:
1183 return (boolean)count_records('course_categories', 'id', $instanceid);
1184
1185 case CONTEXT_COURSE:
1186 return (boolean)count_records('course', 'id', $instanceid);
1187
1188 case CONTEXT_GROUP:
1189 return (boolean)count_records('groups', 'id', $instanceid);
1190
1191 case CONTEXT_MODULE:
1192 return (boolean)count_records('course_modules', 'id', $instanceid);
1193
1194 case CONTEXT_BLOCK:
1195 return (boolean)count_records('block_instance', 'id', $instanceid);
1196
1197 default:
1198 return false;
1199 }
1200}
bbbf2d40 1201
1202/**
1203 * Get the context instance as an object. This function will create the
1204 * context instance if it does not exist yet.
1205 * @param $level
1206 * @param $instance
1207 */
aad2ba95 1208function get_context_instance($contextlevel=NULL, $instance=SITEID) {
e5605780 1209
51195e6f 1210 global $context_cache, $context_cache_id, $CONTEXT;
d9a35e12 1211
340ea4e8 1212/// If no level is supplied then return the current global context if there is one
aad2ba95 1213 if (empty($contextlevel)) {
340ea4e8 1214 if (empty($CONTEXT)) {
ea82d6b6 1215 debugging("Error: get_context_instance() called without a context");
340ea4e8 1216 } else {
1217 return $CONTEXT;
1218 }
e5605780 1219 }
1220
340ea4e8 1221/// Check the cache
aad2ba95 1222 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
1223 return $context_cache[$contextlevel][$instance];
e5605780 1224 }
1225
340ea4e8 1226/// Get it from the database, or create it
aad2ba95 1227 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
1228 create_context($contextlevel, $instance);
1229 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
e5605780 1230 }
1231
ccfc5ecc 1232/// Only add to cache if context isn't empty.
1233 if (!empty($context)) {
aad2ba95 1234 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
ccfc5ecc 1235 $context_cache_id[$context->id] = $context; // Cache it for later
1236 }
0468976c 1237
bbbf2d40 1238 return $context;
1239}
1240
cee0901c 1241
340ea4e8 1242/**
1243 * Get a context instance as an object, from a given id.
1244 * @param $id
1245 */
1246function get_context_instance_by_id($id) {
1247
d9a35e12 1248 global $context_cache, $context_cache_id;
1249
340ea4e8 1250 if (isset($context_cache_id[$id])) { // Already cached
75e84883 1251 return $context_cache_id[$id];
340ea4e8 1252 }
1253
1254 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
aad2ba95 1255 $context_cache[$context->contextlevel][$context->instanceid] = $context;
340ea4e8 1256 $context_cache_id[$context->id] = $context;
1257 return $context;
1258 }
1259
1260 return false;
1261}
1262
bbbf2d40 1263
8737be58 1264/**
1265 * Get the local override (if any) for a given capability in a role in a context
1266 * @param $roleid
0468976c 1267 * @param $contextid
1268 * @param $capability
8737be58 1269 */
1270function get_local_override($roleid, $contextid, $capability) {
1271 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1272}
1273
1274
bbbf2d40 1275
1276/************************************
1277 * DB TABLE RELATED FUNCTIONS *
1278 ************************************/
1279
cee0901c 1280/**
bbbf2d40 1281 * function that creates a role
1282 * @param name - role name
31f26796 1283 * @param shortname - role short name
bbbf2d40 1284 * @param description - role description
1285 * @param legacy - optional legacy capability
1286 * @return id or false
1287 */
8420bee9 1288function create_role($name, $shortname, $description, $legacy='') {
eef868d1 1289
98882637 1290 // check for duplicate role name
eef868d1 1291
98882637 1292 if ($role = get_record('role','name', $name)) {
eef868d1 1293 error('there is already a role with this name!');
98882637 1294 }
eef868d1 1295
31f26796 1296 if ($role = get_record('role','shortname', $shortname)) {
eef868d1 1297 error('there is already a role with this shortname!');
31f26796 1298 }
1299
b5959f30 1300 $role = new object();
98882637 1301 $role->name = $name;
31f26796 1302 $role->shortname = $shortname;
98882637 1303 $role->description = $description;
eef868d1 1304
8420bee9 1305 //find free sortorder number
1306 $role->sortorder = count_records('role');
1307 while (get_record('role','sortorder', $role->sortorder)) {
1308 $role->sortorder += 1;
b5959f30 1309 }
1310
eef868d1 1311 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
1312
98882637 1313 if ($id = insert_record('role', $role)) {
eef868d1 1314 if ($legacy) {
1315 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
98882637 1316 }
eef868d1 1317
ec7a8b79 1318 /// By default, users with role:manage at site level
1319 /// should be able to assign users to this new role, and override this new role's capabilities
eef868d1 1320
ec7a8b79 1321 // find all admin roles
e46c0987 1322 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
1323 // foreach admin role
1324 foreach ($adminroles as $arole) {
1325 // write allow_assign and allow_overrid
1326 allow_assign($arole->id, $id);
eef868d1 1327 allow_override($arole->id, $id);
e46c0987 1328 }
ec7a8b79 1329 }
eef868d1 1330
98882637 1331 return $id;
1332 } else {
eef868d1 1333 return false;
98882637 1334 }
eef868d1 1335
bbbf2d40 1336}
1337
8420bee9 1338/**
1339 * function that deletes a role and cleanups up after it
1340 * @param roleid - id of role to delete
1341 * @return success
1342 */
1343function delete_role($roleid) {
1344 $success = true;
1345
1346// first unssign all users
1347 if (!role_unassign($roleid)) {
1348 debugging("Error while unassigning all users from role with ID $roleid!");
1349 $success = false;
1350 }
1351
1352// cleanup all references to this role, ignore errors
1353 if ($success) {
1354 delete_records('role_capabilities', 'roleid', $roleid);
1355 delete_records('role_allow_assign', 'roleid', $roleid);
1356 delete_records('role_allow_assign', 'allowassign', $roleid);
1357 delete_records('role_allow_override', 'roleid', $roleid);
1358 delete_records('role_allow_override', 'allowoverride', $roleid);
1359 delete_records('role_names', 'roleid', $roleid);
1360 }
1361
1362// finally delete the role itself
1363 if ($success and !delete_records('role', 'id', $roleid)) {
ece4945b 1364 debugging("Could not delete role record with ID $roleid!");
8420bee9 1365 $success = false;
1366 }
1367
1368 return $success;
1369}
1370
bbbf2d40 1371/**
1372 * Function to write context specific overrides, or default capabilities.
1373 * @param module - string name
1374 * @param capability - string name
1375 * @param contextid - context id
1376 * @param roleid - role id
1377 * @param permission - int 1,-1 or -1000
1378 */
e7876c1e 1379function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
eef868d1 1380
98882637 1381 global $USER;
eef868d1 1382
98882637 1383 if (empty($permission) || $permission == 0) { // if permission is not set
eef868d1 1384 unassign_capability($capability, $roleid, $contextid);
98882637 1385 }
eef868d1 1386
2e85fffe 1387 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
e7876c1e 1388
1389 if ($existing and !$overwrite) { // We want to keep whatever is there already
1390 return true;
1391 }
1392
bbbf2d40 1393 $cap = new object;
1394 $cap->contextid = $contextid;
1395 $cap->roleid = $roleid;
1396 $cap->capability = $capability;
1397 $cap->permission = $permission;
1398 $cap->timemodified = time();
9db12da7 1399 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
e7876c1e 1400
1401 if ($existing) {
1402 $cap->id = $existing->id;
1403 return update_record('role_capabilities', $cap);
1404 } else {
1405 return insert_record('role_capabilities', $cap);
1406 }
bbbf2d40 1407}
1408
1409
1410/**
1411 * Unassign a capability from a role.
1412 * @param $roleid - the role id
1413 * @param $capability - the name of the capability
1414 * @return boolean - success or failure
1415 */
1416function unassign_capability($capability, $roleid, $contextid=NULL) {
eef868d1 1417
98882637 1418 if (isset($contextid)) {
1419 $status = delete_records('role_capabilities', 'capability', $capability,
1420 'roleid', $roleid, 'contextid', $contextid);
1421 } else {
1422 $status = delete_records('role_capabilities', 'capability', $capability,
1423 'roleid', $roleid);
1424 }
1425 return $status;
bbbf2d40 1426}
1427
1428
1429/**
759ac72d 1430 * Get the roles that have a given capability assigned to it. This function
1431 * does not resolve the actual permission of the capability. It just checks
1432 * for assignment only.
bbbf2d40 1433 * @param $capability - capability name (string)
1434 * @param $permission - optional, the permission defined for this capability
1435 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
1436 * @return array or role objects
1437 */
ec7a8b79 1438function get_roles_with_capability($capability, $permission=NULL, $context='') {
1439
bbbf2d40 1440 global $CFG;
eef868d1 1441
ec7a8b79 1442 if ($context) {
1443 if ($contexts = get_parent_contexts($context)) {
1444 $listofcontexts = '('.implode(',', $contexts).')';
1445 } else {
1446 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
eef868d1 1447 $listofcontexts = '('.$sitecontext->id.')'; // must be site
1448 }
42ac3ecf 1449 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
ec7a8b79 1450 } else {
1451 $contextstr = '';
1452 }
eef868d1 1453
1454 $selectroles = "SELECT r.*
42ac3ecf 1455 FROM {$CFG->prefix}role r,
1456 {$CFG->prefix}role_capabilities rc
bbbf2d40 1457 WHERE rc.capability = '$capability'
ec7a8b79 1458 AND rc.roleid = r.id $contextstr";
bbbf2d40 1459
1460 if (isset($permission)) {
1461 $selectroles .= " AND rc.permission = '$permission'";
1462 }
1463 return get_records_sql($selectroles);
1464}
1465
1466
1467/**
a9e1c058 1468 * This function makes a role-assignment (a role for a user or group in a particular context)
bbbf2d40 1469 * @param $roleid - the role of the id
1470 * @param $userid - userid
1471 * @param $groupid - group id
1472 * @param $contextid - id of the context
1473 * @param $timestart - time this assignment becomes effective
1474 * @param $timeend - time this assignemnt ceases to be effective
1475 * @uses $USER
1476 * @return id - new id of the assigment
1477 */
f44152f4 1478function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual') {
aa311411 1479 global $USER, $CFG;
bbbf2d40 1480
7eb0b60a 1481 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER);
bbbf2d40 1482
a9e1c058 1483/// Do some data validation
1484
bbbf2d40 1485 if (empty($roleid)) {
9d829c68 1486 debugging('Role ID not provided');
a9e1c058 1487 return false;
bbbf2d40 1488 }
1489
1490 if (empty($userid) && empty($groupid)) {
9d829c68 1491 debugging('Either userid or groupid must be provided');
a9e1c058 1492 return false;
bbbf2d40 1493 }
eef868d1 1494
7700027f 1495 if ($userid && !record_exists('user', 'id', $userid)) {
82396e5b 1496 debugging('User ID '.intval($userid).' does not exist!');
7700027f 1497 return false;
1498 }
bbbf2d40 1499
dc411d1b 1500 if ($groupid && !record_exists('groups', 'id', $groupid)) {
82396e5b 1501 debugging('Group ID '.intval($groupid).' does not exist!');
dc411d1b 1502 return false;
1503 }
1504
7700027f 1505 if (!$context = get_context_instance_by_id($contextid)) {
82396e5b 1506 debugging('Context ID '.intval($contextid).' does not exist!');
a9e1c058 1507 return false;
bbbf2d40 1508 }
1509
a9e1c058 1510 if (($timestart and $timeend) and ($timestart > $timeend)) {
9d829c68 1511 debugging('The end time can not be earlier than the start time');
a9e1c058 1512 return false;
1513 }
1514
7700027f 1515
a9e1c058 1516/// Check for existing entry
1517 if ($userid) {
7700027f 1518 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
a9e1c058 1519 } else {
7700027f 1520 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
a9e1c058 1521 }
1522
9ebcb4d2 1523
a9e1c058 1524 $newra = new object;
bbbf2d40 1525
a9e1c058 1526 if (empty($ra)) { // Create a new entry
1527 $newra->roleid = $roleid;
7700027f 1528 $newra->contextid = $context->id;
a9e1c058 1529 $newra->userid = $userid;
1530 $newra->groupid = $groupid;
1531
1532 $newra->hidden = $hidden;
f44152f4 1533 $newra->enrol = $enrol;
a9e1c058 1534 $newra->timestart = $timestart;
1535 $newra->timeend = $timeend;
1536 $newra->timemodified = time();
1537 $newra->modifier = empty($USER->id) ? 0 : $USER->id;
1538
9ebcb4d2 1539 $success = insert_record('role_assignments', $newra);
a9e1c058 1540
1541 } else { // We already have one, just update it
1542
1543 $newra->id = $ra->id;
1544 $newra->hidden = $hidden;
f44152f4 1545 $newra->enrol = $enrol;
a9e1c058 1546 $newra->timestart = $timestart;
1547 $newra->timeend = $timeend;
1548 $newra->timemodified = time();
1549 $newra->modifier = empty($USER->id) ? 0 : $USER->id;
1550
9ebcb4d2 1551 $success = update_record('role_assignments', $newra);
1552 }
1553
7700027f 1554 if ($success) { /// Role was assigned, so do some other things
1555
1556 /// If the user is the current user, then reload the capabilities too.
1557 if (!empty($USER->id) && $USER->id == $userid) {
1558 load_user_capability();
1559 }
1560
0f161e1f 1561 /// Ask all the modules if anything needs to be done for this user
1562 if ($mods = get_list_of_plugins('mod')) {
1563 foreach ($mods as $mod) {
1564 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
1565 $functionname = $mod.'_role_assign';
1566 if (function_exists($functionname)) {
1567 $functionname($userid, $context);
1568 }
1569 }
1570 }
1571
1572 /// Make sure they have an entry in user_lastaccess for courses they can access
1573 // role_add_lastaccess_entries($userid, $context);
a9e1c058 1574 }
eef868d1 1575
4e5f3064 1576 /// now handle metacourse role assignments if in course context
aad2ba95 1577 if ($success and $context->contextlevel == CONTEXT_COURSE) {
4e5f3064 1578 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
1579 foreach ($parents as $parent) {
1aad4310 1580 sync_metacourse($parent->parent_course);
4e5f3064 1581 }
1582 }
1583 }
6eb4f823 1584
1585 return $success;
bbbf2d40 1586}
1587
1588
1589/**
1dc1f037 1590 * Deletes one or more role assignments. You must specify at least one parameter.
bbbf2d40 1591 * @param $roleid
1592 * @param $userid
1593 * @param $groupid
1594 * @param $contextid
1595 * @return boolean - success or failure
1596 */
1dc1f037 1597function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0) {
d74067e8 1598
1599 global $USER, $CFG;
eef868d1 1600
4e5f3064 1601 $success = true;
d74067e8 1602
1dc1f037 1603 $args = array('roleid', 'userid', 'groupid', 'contextid');
1604 $select = array();
1605 foreach ($args as $arg) {
1606 if ($$arg) {
1607 $select[] = $arg.' = '.$$arg;
1608 }
1609 }
d74067e8 1610
1dc1f037 1611 if ($select) {
4e5f3064 1612 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
1613 $mods = get_list_of_plugins('mod');
1614 foreach($ras as $ra) {
86e2c51d 1615 /// infinite loop protection when deleting recursively
1616 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
1617 continue;
1618 }
4e5f3064 1619 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
86e2c51d 1620
4e5f3064 1621 /// If the user is the current user, then reload the capabilities too.
1622 if (!empty($USER->id) && $USER->id == $ra->userid) {
1623 load_user_capability();
1624 }
1625 $context = get_record('context', 'id', $ra->contextid);
0f161e1f 1626
1627 /// Ask all the modules if anything needs to be done for this user
4e5f3064 1628 foreach ($mods as $mod) {
1629 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
1630 $functionname = $mod.'_role_unassign';
1631 if (function_exists($functionname)) {
1632 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
1633 }
1634 }
1635
1636 /// now handle metacourse role unassigment and removing from goups if in course context
aad2ba95 1637 if (!empty($context) and $context->contextlevel == CONTEXT_COURSE) {
4e5f3064 1638 //remove from groups when user has no role
1639 $roles = get_user_roles($context, $ra->userid, true);
1640 if (empty($roles)) {
1641 if ($groups = get_groups($context->instanceid, $ra->userid)) {
1642 foreach ($groups as $group) {
1643 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
1644 }
1645 }
1646 }
1aad4310 1647 //unassign roles in metacourses if needed
4e5f3064 1648 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
1649 foreach ($parents as $parent) {
1aad4310 1650 sync_metacourse($parent->parent_course);
0f161e1f 1651 }
1652 }
0f161e1f 1653 }
1654 }
d74067e8 1655 }
1dc1f037 1656 }
4e5f3064 1657
1658 return $success;
bbbf2d40 1659}
1660
eef868d1 1661/*
1662 * A convenience function to take care of the common case where you
b963384f 1663 * just want to enrol someone using the default role into a course
1664 *
1665 * @param object $course
1666 * @param object $user
1667 * @param string $enrol - the plugin used to do this enrolment
1668 */
1669function enrol_into_course($course, $user, $enrol) {
1670
1671 if ($course->enrolperiod) {
1672 $timestart = time();
1673 $timeend = time() + $course->enrolperiod;
1674 } else {
1675 $timestart = $timeend = 0;
1676 }
1677
1678 if ($role = get_default_course_role($course)) {
c4381ef5 1679
1680 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1681
e2183037 1682 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
b963384f 1683 return false;
1684 }
eef868d1 1685
b963384f 1686 email_welcome_message_to_user($course, $user);
eef868d1 1687
b963384f 1688 add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
1689
1690 return true;
1691 }
1692
1693 return false;
1694}
1695
0f161e1f 1696/**
1697 * Add last access times to user_lastaccess as required
1698 * @param $userid
1699 * @param $context
1700 * @return boolean - success or failure
1701 */
1702function role_add_lastaccess_entries($userid, $context) {
1703
1704 global $USER, $CFG;
1705
aad2ba95 1706 if (empty($context->contextlevel)) {
0f161e1f 1707 return false;
1708 }
1709
1710 $lastaccess = new object; // Reusable object below
1711 $lastaccess->userid = $userid;
1712 $lastaccess->timeaccess = 0;
1713
aad2ba95 1714 switch ($context->contextlevel) {
0f161e1f 1715
1716 case CONTEXT_SYSTEM: // For the whole site
1717 if ($courses = get_record('course')) {
1718 foreach ($courses as $course) {
1719 $lastaccess->courseid = $course->id;
1720 role_set_lastaccess($lastaccess);
1721 }
1722 }
1723 break;
1724
1725 case CONTEXT_CATEGORY: // For a whole category
1726 if ($courses = get_record('course', 'category', $context->instanceid)) {
1727 foreach ($courses as $course) {
1728 $lastaccess->courseid = $course->id;
1729 role_set_lastaccess($lastaccess);
1730 }
1731 }
1732 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
1733 foreach ($categories as $category) {
1734 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
1735 role_add_lastaccess_entries($userid, $subcontext);
1736 }
1737 }
1738 break;
eef868d1 1739
0f161e1f 1740
1741 case CONTEXT_COURSE: // For a whole course
1742 if ($course = get_record('course', 'id', $context->instanceid)) {
1743 $lastaccess->courseid = $course->id;
1744 role_set_lastaccess($lastaccess);
1745 }
1746 break;
1747 }
1748}
1749
1750/**
1751 * Delete last access times from user_lastaccess as required
1752 * @param $userid
1753 * @param $context
1754 * @return boolean - success or failure
1755 */
1756function role_remove_lastaccess_entries($userid, $context) {
1757
1758 global $USER, $CFG;
1759
1760}
1761
bbbf2d40 1762
1763/**
1764 * Loads the capability definitions for the component (from file). If no
1765 * capabilities are defined for the component, we simply return an empty array.
1766 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1767 * @return array of capabilities
1768 */
1769function load_capability_def($component) {
1770 global $CFG;
1771
1772 if ($component == 'moodle') {
1773 $defpath = $CFG->libdir.'/db/access.php';
1774 $varprefix = 'moodle';
1775 } else {
0c4d9f49 1776 $compparts = explode('/', $component);
eef868d1 1777
0c4d9f49 1778 if ($compparts[0] == 'block') {
1779 // Blocks are an exception. Blocks directory is 'blocks', and not
1780 // 'block'. So we need to jump through hoops.
1781 $defpath = $CFG->dirroot.'/'.$compparts[0].
1782 's/'.$compparts[1].'/db/access.php';
1783 $varprefix = $compparts[0].'_'.$compparts[1];
1784 } else {
1785 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
1786 $varprefix = str_replace('/', '_', $component);
1787 }
bbbf2d40 1788 }
1789 $capabilities = array();
eef868d1 1790
bbbf2d40 1791 if (file_exists($defpath)) {
1792 require_once($defpath);
1793 $capabilities = ${$varprefix.'_capabilities'};
1794 }
1795 return $capabilities;
1796}
1797
1798
1799/**
1800 * Gets the capabilities that have been cached in the database for this
1801 * component.
1802 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1803 * @return array of capabilities
1804 */
1805function get_cached_capabilities($component='moodle') {
1806 if ($component == 'moodle') {
1807 $storedcaps = get_records_select('capabilities',
1808 "name LIKE 'moodle/%:%'");
1809 } else {
1810 $storedcaps = get_records_select('capabilities',
1811 "name LIKE '$component:%'");
1812 }
1813 return $storedcaps;
1814}
1815
1816
1817/**
1818 * Updates the capabilities table with the component capability definitions.
1819 * If no parameters are given, the function updates the core moodle
1820 * capabilities.
1821 *
1822 * Note that the absence of the db/access.php capabilities definition file
1823 * will cause any stored capabilities for the component to be removed from
eef868d1 1824 * the database.
bbbf2d40 1825 *
1826 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1827 * @return boolean
1828 */
1829function update_capabilities($component='moodle') {
eef868d1 1830
bbbf2d40 1831 $storedcaps = array();
be4486da 1832
1833 $filecaps = load_capability_def($component);
bbbf2d40 1834 $cachedcaps = get_cached_capabilities($component);
1835 if ($cachedcaps) {
1836 foreach ($cachedcaps as $cachedcap) {
1837 array_push($storedcaps, $cachedcap->name);
be4486da 1838 // update risk bitmasks in existing capabilitites if needed
1839 if (array_key_exists($cachedcap->name, $filecaps)) {
1840 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2b531945 1841 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
be4486da 1842 }
1843 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
1844 $updatecap = new object;
1845 $updatecap->id = $cachedcap->id;
1846 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
1847 if (!update_record('capabilities', $updatecap)) {
1848 return false;
1849 }
1850 }
1851 }
bbbf2d40 1852 }
1853 }
be4486da 1854
bbbf2d40 1855 // Are there new capabilities in the file definition?
1856 $newcaps = array();
eef868d1 1857
bbbf2d40 1858 foreach ($filecaps as $filecap => $def) {
eef868d1 1859 if (!$storedcaps ||
bbbf2d40 1860 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2b531945 1861 if (!array_key_exists('riskbitmask', $def)) {
1862 $def['riskbitmask'] = 0; // no risk if not specified
1863 }
bbbf2d40 1864 $newcaps[$filecap] = $def;
1865 }
1866 }
1867 // Add new capabilities to the stored definition.
1868 foreach ($newcaps as $capname => $capdef) {
1869 $capability = new object;
1870 $capability->name = $capname;
1871 $capability->captype = $capdef['captype'];
1872 $capability->contextlevel = $capdef['contextlevel'];
1873 $capability->component = $component;
be4486da 1874 $capability->riskbitmask = $capdef['riskbitmask'];
eef868d1 1875
bbbf2d40 1876 if (!insert_record('capabilities', $capability, false, 'id')) {
1877 return false;
1878 }
eef868d1 1879
bbbf2d40 1880 // Do we need to assign the new capabilities to roles that have the
1881 // legacy capabilities moodle/legacy:* as well?
1882 if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
1883 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2e85fffe 1884 notify('Could not assign legacy capabilities for '.$capname);
bbbf2d40 1885 }
1886 }
1887 // Are there any capabilities that have been removed from the file
1888 // definition that we need to delete from the stored capabilities and
1889 // role assignments?
1890 capabilities_cleanup($component, $filecaps);
eef868d1 1891
bbbf2d40 1892 return true;
1893}
1894
1895
1896/**
1897 * Deletes cached capabilities that are no longer needed by the component.
1898 * Also unassigns these capabilities from any roles that have them.
1899 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1900 * @param $newcapdef - array of the new capability definitions that will be
1901 * compared with the cached capabilities
1902 * @return int - number of deprecated capabilities that have been removed
1903 */
1904function capabilities_cleanup($component, $newcapdef=NULL) {
eef868d1 1905
bbbf2d40 1906 $removedcount = 0;
eef868d1 1907
bbbf2d40 1908 if ($cachedcaps = get_cached_capabilities($component)) {
1909 foreach ($cachedcaps as $cachedcap) {
1910 if (empty($newcapdef) ||
1911 array_key_exists($cachedcap->name, $newcapdef) === false) {
eef868d1 1912
bbbf2d40 1913 // Remove from capabilities cache.
1914 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
1915 error('Could not delete deprecated capability '.$cachedcap->name);
1916 } else {
1917 $removedcount++;
1918 }
1919 // Delete from roles.
1920 if($roles = get_roles_with_capability($cachedcap->name)) {
1921 foreach($roles as $role) {
46943f7b 1922 if (!unassign_capability($cachedcap->name, $role->id)) {
bbbf2d40 1923 error('Could not unassign deprecated capability '.
1924 $cachedcap->name.' from role '.$role->name);
1925 }
1926 }
1927 }
1928 } // End if.
1929 }
1930 }
1931 return $removedcount;
1932}
1933
1934
1935
cee0901c 1936/****************
1937 * UI FUNCTIONS *
1938 ****************/
bbbf2d40 1939
1940
1941/**
1942 * prints human readable context identifier.
1943 */
0468976c 1944function print_context_name($context) {
340ea4e8 1945
ec0810ee 1946 $name = '';
aad2ba95 1947 switch ($context->contextlevel) {
ec0810ee 1948
bbbf2d40 1949 case CONTEXT_SYSTEM: // by now it's a definite an inherit
ec0810ee 1950 $name = get_string('site');
340ea4e8 1951 break;
bbbf2d40 1952
1953 case CONTEXT_PERSONAL:
ec0810ee 1954 $name = get_string('personal');
340ea4e8 1955 break;
1956
4b10f08b 1957 case CONTEXT_USER:
ec0810ee 1958 if ($user = get_record('user', 'id', $context->instanceid)) {
1959 $name = get_string('user').': '.fullname($user);
1960 }
340ea4e8 1961 break;
1962
bbbf2d40 1963 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
ec0810ee 1964 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
1965 $name = get_string('category').': '.$category->name;
1966 }
340ea4e8 1967 break;
bbbf2d40 1968
1969 case CONTEXT_COURSE: // 1 to 1 to course cat
ec0810ee 1970 if ($course = get_record('course', 'id', $context->instanceid)) {
1971 $name = get_string('course').': '.$course->fullname;
1972 }
340ea4e8 1973 break;
bbbf2d40 1974
1975 case CONTEXT_GROUP: // 1 to 1 to course
ec0810ee 1976 if ($group = get_record('groups', 'id', $context->instanceid)) {
1977 $name = get_string('group').': '.$group->name;
1978 }
340ea4e8 1979 break;
bbbf2d40 1980
1981 case CONTEXT_MODULE: // 1 to 1 to course
98882637 1982 if ($cm = get_record('course_modules','id',$context->instanceid)) {
1983 if ($module = get_record('modules','id',$cm->module)) {
1984 if ($mod = get_record($module->name, 'id', $cm->instance)) {
ec0810ee 1985 $name = get_string('activitymodule').': '.$mod->name;
98882637 1986 }
ec0810ee 1987 }
1988 }
340ea4e8 1989 break;
bbbf2d40 1990
1991 case CONTEXT_BLOCK: // 1 to 1 to course
98882637 1992 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
1993 if ($block = get_record('block','id',$blockinstance->blockid)) {
91be52d7 1994 global $CFG;
1995 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
1996 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
1997 $blockname = "block_$block->name";
1998 if ($blockobject = new $blockname()) {
1999 $name = $blockobject->title.' ('.get_string('block').')';
2000 }
ec0810ee 2001 }
2002 }
340ea4e8 2003 break;
bbbf2d40 2004
2005 default:
2006 error ('This is an unknown context!');
340ea4e8 2007 return false;
2008
2009 }
340ea4e8 2010 return $name;
bbbf2d40 2011}
2012
2013
2014/**
eef868d1 2015 * Extracts the relevant capabilities given a contextid.
bbbf2d40 2016 * All case based, example an instance of forum context.
2017 * Will fetch all forum related capabilities, while course contexts
2018 * Will fetch all capabilities
0468976c 2019 * @param object context
bbbf2d40 2020 * @return array();
2021 *
2022 * capabilities
2023 * `name` varchar(150) NOT NULL,
2024 * `captype` varchar(50) NOT NULL,
2025 * `contextlevel` int(10) NOT NULL,
2026 * `component` varchar(100) NOT NULL,
2027 */
0468976c 2028function fetch_context_capabilities($context) {
eef868d1 2029
98882637 2030 global $CFG;
bbbf2d40 2031
2032 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
eef868d1 2033
aad2ba95 2034 switch ($context->contextlevel) {
bbbf2d40 2035
98882637 2036 case CONTEXT_SYSTEM: // all
2037 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2038 break;
2039
2040 case CONTEXT_PERSONAL:
0a8a95c9 2041 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
bbbf2d40 2042 break;
eef868d1 2043
4b10f08b 2044 case CONTEXT_USER:
2045 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_USER;
bbbf2d40 2046 break;
eef868d1 2047
bbbf2d40 2048 case CONTEXT_COURSECAT: // all
98882637 2049 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2050 break;
2051
2052 case CONTEXT_COURSE: // all
98882637 2053 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 2054 break;
2055
2056 case CONTEXT_GROUP: // group caps
2057 break;
2058
2059 case CONTEXT_MODULE: // mod caps
98882637 2060 $cm = get_record('course_modules', 'id', $context->instanceid);
2061 $module = get_record('modules', 'id', $cm->module);
eef868d1 2062
98882637 2063 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
2064 and component = 'mod/$module->name'";
bbbf2d40 2065 break;
2066
2067 case CONTEXT_BLOCK: // block caps
98882637 2068 $cb = get_record('block_instance', 'id', $context->instanceid);
2069 $block = get_record('block', 'id', $cb->blockid);
eef868d1 2070
98882637 2071 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
2072 and component = 'block/$block->name'";
bbbf2d40 2073 break;
2074
2075 default:
2076 return false;
2077 }
2078
16e2e2f3 2079 if (!$records = get_records_sql($SQL.' '.$sort)) {
2080 $records = array();
2081 }
759ac72d 2082 $contextindependentcaps = fetch_context_independent_capabilities();
2083 $records = array_merge($records, $contextindependentcaps);
69eb59f2 2084
2085 // special sorting of core system capabiltites and enrollments
aad2ba95 2086 if ($context->contextlevel == CONTEXT_SYSTEM) {
69eb59f2 2087 $first = array();
2088 foreach ($records as $key=>$record) {
2089 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
2090 $first[$key] = $record;
2091 unset($records[$key]);
2092 } else if (count($first)){
2093 break;
2094 }
2095 }
2096 if (count($first)) {
2097 $records = $first + $records; // merge the two arrays keeping the keys
2098 }
2099 }
2100 // end of special sorting
bbbf2d40 2101 return $records;
eef868d1 2102
bbbf2d40 2103}
2104
2105
759ac72d 2106/**
2107 * Gets the context-independent capabilities that should be overrridable in
2108 * any context.
2109 * @return array of capability records from the capabilities table.
2110 */
2111function fetch_context_independent_capabilities() {
eef868d1 2112
759ac72d 2113 $contextindependentcaps = array(
2114 'moodle/site:accessallgroups'
2115 );
2116
2117 $records = array();
eef868d1 2118
759ac72d 2119 foreach ($contextindependentcaps as $capname) {
2120 $record = get_record('capabilities', 'name', $capname);
2121 array_push($records, $record);
2122 }
2123 return $records;
2124}
2125
2126
bbbf2d40 2127/**
2128 * This function pulls out all the resolved capabilities (overrides and
759ac72d 2129 * defaults) of a role used in capability overrides in contexts at a given
bbbf2d40 2130 * context.
0a8a95c9 2131 * @param obj $context
bbbf2d40 2132 * @param int $roleid
dc558690 2133 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
bbbf2d40 2134 * @return array
2135 */
1648afb2 2136function role_context_capabilities($roleid, $context, $cap='') {
dc558690 2137 global $CFG;
eef868d1 2138
8521d83a 2139 $contexts = get_parent_contexts($context);
2140 $contexts[] = $context->id;
98882637 2141 $contexts = '('.implode(',', $contexts).')';
eef868d1 2142
1648afb2 2143 if ($cap) {
e4697bf7 2144 $search = " AND rc.capability = '$cap' ";
1648afb2 2145 } else {
eef868d1 2146 $search = '';
1648afb2 2147 }
eef868d1 2148
2149 $SQL = "SELECT rc.*
2150 FROM {$CFG->prefix}role_capabilities rc,
dc558690 2151 {$CFG->prefix}context c
2152 WHERE rc.contextid in $contexts
2153 AND rc.roleid = $roleid
2154 AND rc.contextid = c.id $search
aad2ba95 2155 ORDER BY c.contextlevel DESC,
eef868d1 2156 rc.capability DESC";
759ac72d 2157
98882637 2158 $capabilities = array();
eef868d1 2159
4729012f 2160 if ($records = get_records_sql($SQL)) {
2161 // We are traversing via reverse order.
2162 foreach ($records as $record) {
2163 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2164 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2165 $capabilities[$record->capability] = $record->permission;
eef868d1 2166 }
4729012f 2167 }
98882637 2168 }
2169 return $capabilities;
bbbf2d40 2170}
2171
bbbf2d40 2172/**
eef868d1 2173 * Recursive function which, given a context, find all parent context ids,
bbbf2d40 2174 * and return the array in reverse order, i.e. parent first, then grand
2175 * parent, etc.
2176 * @param object $context
2177 * @return array()
2178 */
bbbf2d40 2179function get_parent_contexts($context) {
759ac72d 2180
aad2ba95 2181 switch ($context->contextlevel) {
bbbf2d40 2182
2183 case CONTEXT_SYSTEM: // no parent
957861f7 2184 return array();
bbbf2d40 2185 break;
2186
2187 case CONTEXT_PERSONAL:
957861f7 2188 if (!$parent = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
2189 return array();
2190 } else {
2191 return array($parent->id);
2192 }
bbbf2d40 2193 break;
eef868d1 2194
4b10f08b 2195 case CONTEXT_USER:
957861f7 2196 if (!$parent = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
2197 return array();
2198 } else {
2199 return array($parent->id);
2200 }
bbbf2d40 2201 break;
eef868d1 2202
bbbf2d40 2203 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
957861f7 2204 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
2205 return array();
2206 }
c5ddc3fd 2207 if (!empty($coursecat->parent)) { // return parent value if exist
bbbf2d40 2208 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
2209 return array_merge(array($parent->id), get_parent_contexts($parent));
2210 } else { // else return site value
2211 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
2212 return array($parent->id);
2213 }
2214 break;
2215
2216 case CONTEXT_COURSE: // 1 to 1 to course cat
957861f7 2217 if (!$course = get_record('course','id',$context->instanceid)) {
2218 return array();
2219 }
2220 if (!empty($course->category)) {
2221 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2222 return array_merge(array($parent->id), get_parent_contexts($parent));
2223 } else {
2224 return array();
2225 }
bbbf2d40 2226 break;
2227
2228 case CONTEXT_GROUP: // 1 to 1 to course
957861f7 2229 if (!$group = get_record('groups','id',$context->instanceid)) {
2230 return array();
2231 }
2232 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
2233 return array_merge(array($parent->id), get_parent_contexts($parent));
2234 } else {
2235 return array();
2236 }
bbbf2d40 2237 break;
2238
2239 case CONTEXT_MODULE: // 1 to 1 to course
957861f7 2240 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
2241 return array();
2242 }
2243 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
2244 return array_merge(array($parent->id), get_parent_contexts($parent));
2245 } else {
2246 return array();
2247 }
bbbf2d40 2248 break;
2249
2250 case CONTEXT_BLOCK: // 1 to 1 to course
957861f7 2251 if (!$block = get_record('block_instance','id',$context->instanceid)) {
2252 return array();
2253 }
2254 if ($parent = get_context_instance(CONTEXT_COURSE, $block->pageid)) {
2255 return array_merge(array($parent->id), get_parent_contexts($parent));
2256 } else {
2257 return array();
2258 }
bbbf2d40 2259 break;
2260
2261 default:
957861f7 2262 error('This is an unknown context!');
bbbf2d40 2263 return false;
2264 }
bbbf2d40 2265}
2266
759ac72d 2267
2268/**
2269 * Gets a string for sql calls, searching for stuff in this context or above
ea8158c1 2270 * @param object $context
2271 * @return string
2272 */
2273function get_related_contexts_string($context) {
2274 if ($parents = get_parent_contexts($context)) {
eef868d1 2275 return (' IN ('.$context->id.','.implode(',', $parents).')');
ea8158c1 2276 } else {
2277 return (' ='.$context->id);
2278 }
2279}
759ac72d 2280
2281
bbbf2d40 2282/**
2283 * This function gets the capability of a role in a given context.
2284 * It is needed when printing override forms.
2285 * @param int $contextid
bbbf2d40 2286 * @param string $capability
2287 * @param array $capabilities - array loaded using role_context_capabilities
2288 * @return int (allow, prevent, prohibit, inherit)
2289 */
bbbf2d40 2290function get_role_context_capability($contextid, $capability, $capabilities) {
759ac72d 2291 if (isset($capabilities[$contextid][$capability])) {
2292 return $capabilities[$contextid][$capability];
2293 }
2294 else {
2295 return false;
2296 }
bbbf2d40 2297}
2298
2299
cee0901c 2300/**
2301 * Returns the human-readable, translated version of the capability.
2302 * Basically a big switch statement.
2303 * @param $capabilityname - e.g. mod/choice:readresponses
2304 */
ceb83c70 2305function get_capability_string($capabilityname) {
eef868d1 2306
cee0901c 2307 // Typical capabilityname is mod/choice:readresponses
ceb83c70 2308
2309 $names = split('/', $capabilityname);
2310 $stringname = $names[1]; // choice:readresponses
eef868d1 2311 $components = split(':', $stringname);
ceb83c70 2312 $componentname = $components[0]; // choice
98882637 2313
2314 switch ($names[0]) {
2315 case 'mod':
ceb83c70 2316 $string = get_string($stringname, $componentname);
98882637 2317 break;
eef868d1 2318
98882637 2319 case 'block':
ceb83c70 2320 $string = get_string($stringname, 'block_'.$componentname);
98882637 2321 break;
ceb83c70 2322
98882637 2323 case 'moodle':
ceb83c70 2324 $string = get_string($stringname, 'role');
98882637 2325 break;
eef868d1 2326
98882637 2327 case 'enrol':
ceb83c70 2328 $string = get_string($stringname, 'enrol_'.$componentname);
eef868d1 2329 break;
2330
98882637 2331 default:
ceb83c70 2332 $string = get_string($stringname);
eef868d1 2333 break;
2334
98882637 2335 }
ceb83c70 2336 return $string;
bbbf2d40 2337}
2338
2339
cee0901c 2340/**
2341 * This gets the mod/block/course/core etc strings.
2342 * @param $component
2343 * @param $contextlevel
2344 */
bbbf2d40 2345function get_component_string($component, $contextlevel) {
2346
98882637 2347 switch ($contextlevel) {
bbbf2d40 2348
98882637 2349 case CONTEXT_SYSTEM:
be382aaf 2350 if (preg_match('|^enrol/|', $component)) {
2351 $langname = str_replace('/', '_', $component);
2352 $string = get_string('enrolname', $langname);
f3652521 2353 } else if (preg_match('|^block/|', $component)) {
2354 $langname = str_replace('/', '_', $component);
2355 $string = get_string('blockname', $langname);
69eb59f2 2356 } else {
2357 $string = get_string('coresystem');
2358 }
bbbf2d40 2359 break;
2360
2361 case CONTEXT_PERSONAL:
98882637 2362 $string = get_string('personal');
bbbf2d40 2363 break;
2364
4b10f08b 2365 case CONTEXT_USER:
98882637 2366 $string = get_string('users');
bbbf2d40 2367 break;
2368
2369 case CONTEXT_COURSECAT:
98882637 2370 $string = get_string('categories');
bbbf2d40 2371 break;
2372
2373 case CONTEXT_COURSE:
98882637 2374 $string = get_string('course');
bbbf2d40 2375 break;
2376
2377 case CONTEXT_GROUP:
98882637 2378 $string = get_string('group');
bbbf2d40 2379 break;
2380
2381 case CONTEXT_MODULE:
98882637 2382 $string = get_string('modulename', basename($component));
bbbf2d40 2383 break;
2384
2385 case CONTEXT_BLOCK:
98882637 2386 $string = get_string('blockname', 'block_'.$component.'.php');
bbbf2d40 2387 break;
2388
2389 default:
2390 error ('This is an unknown context!');
2391 return false;
eef868d1 2392
98882637 2393 }
98882637 2394 return $string;
bbbf2d40 2395}
cee0901c 2396
759ac72d 2397/**
2398 * Gets the list of roles assigned to this context and up (parents)
945f88ca 2399 * @param object $context
2400 * @return array
2401 */
e4dd3222 2402function get_roles_used_in_context($context) {
2403
2404 global $CFG;
2d9965e1 2405 $contextlist = get_related_contexts_string($context);
eef868d1 2406
759ac72d 2407 $sql = "SELECT DISTINCT r.id,
2408 r.name,
2409 r.shortname,
2410 r.sortorder
2411 FROM {$CFG->prefix}role_assignments ra,
eef868d1 2412 {$CFG->prefix}role r
2413 WHERE r.id = ra.roleid
759ac72d 2414 AND ra.contextid $contextlist
2415 ORDER BY r.sortorder ASC";
eef868d1 2416
759ac72d 2417 return get_records_sql($sql);
e4dd3222 2418}
2419
eef868d1 2420/** this function is used to print roles column in user profile page.
945f88ca 2421 * @param int userid
2422 * @param int contextid
2423 * @return string
2424 */
0a8a95c9 2425function get_user_roles_in_context($userid, $contextid){
2426 global $CFG;
eef868d1 2427
0a8a95c9 2428 $rolestring = '';
2429 $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';
2430 if ($roles = get_records_sql($SQL)) {
2431 foreach ($roles as $userrole) {
2432 $rolestring .= '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$userrole->contextid.'&amp;roleid='.$userrole->roleid.'">'.$userrole->name.'</a>, ';
eef868d1 2433 }
2434
0a8a95c9 2435 }
2436 return rtrim($rolestring, ', ');
2437}
68c52526 2438
2439
945f88ca 2440/**
2441 * Checks if a user can override capabilities of a particular role in this context
2442 * @param object $context
2443 * @param int targetroleid - the id of the role you want to override
2444 * @return boolean
2445 */
68c52526 2446function user_can_override($context, $targetroleid) {
2447 // first check if user has override capability
2448 // if not return false;
2449 if (!has_capability('moodle/role:override', $context)) {
eef868d1 2450 return false;
68c52526 2451 }
2452 // pull out all active roles of this user from this context(or above)
c0614051 2453 if ($userroles = get_user_roles($context)) {
2454 foreach ($userroles as $userrole) {
2455 // if any in the role_allow_override table, then it's ok
2456 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
2457 return true;
2458 }
68c52526 2459 }
2460 }
eef868d1 2461
68c52526 2462 return false;
eef868d1 2463
68c52526 2464}
2465
945f88ca 2466/**
2467 * Checks if a user can assign users to a particular role in this context
2468 * @param object $context
2469 * @param int targetroleid - the id of the role you want to assign users to
2470 * @return boolean
2471 */
68c52526 2472function user_can_assign($context, $targetroleid) {
eef868d1 2473
68c52526 2474 // first check if user has override capability
2475 // if not return false;
2476 if (!has_capability('moodle/role:assign', $context)) {
eef868d1 2477 return false;
68c52526 2478 }
2479 // pull out all active roles of this user from this context(or above)
c0614051 2480 if ($userroles = get_user_roles($context)) {
2481 foreach ($userroles as $userrole) {
2482 // if any in the role_allow_override table, then it's ok
2483 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
2484 return true;
2485 }
68c52526 2486 }
2487 }
eef868d1 2488
2489 return false;
68c52526 2490}
2491
ece4945b 2492/** Returns all site roles in correct sort order.
2493 *
2494 */
2495function get_all_roles() {
2496 return get_records('role', '', '', 'sortorder ASC');
2497}
2498
945f88ca 2499/**
2500 * gets all the user roles assigned in this context, or higher contexts
2501 * this is mainly used when checking if a user can assign a role, or overriding a role
2502 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2503 * allow_override tables
2504 * @param object $context
2505 * @param int $userid
2506 * @return array
2507 */
5b630667 2508function get_user_roles($context, $userid=0, $checkparentcontexts=true) {
68c52526 2509
2510 global $USER, $CFG, $db;
c0614051 2511
2512 if (empty($userid)) {
2513 if (empty($USER->id)) {
2514 return array();
2515 }
2516 $userid = $USER->id;
2517 }
2518
5b630667 2519 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
2520 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id.')';
c0614051 2521 } else {
5b630667 2522 $contexts = ' ra.contextid = \''.$context->id.'\'';
c0614051 2523 }
2524
31f26796 2525 return get_records_sql('SELECT ra.*, r.name, r.shortname
5b630667 2526 FROM '.$CFG->prefix.'role_assignments ra,
ec6eb110 2527 '.$CFG->prefix.'role r,
2528 '.$CFG->prefix.'context c
c0614051 2529 WHERE ra.userid = '.$userid.
5b630667 2530 ' AND ra.roleid = r.id
ec6eb110 2531 AND ra.contextid = c.id
eef868d1 2532 AND '.$contexts.
ece4945b 2533 ' ORDER BY c.contextlevel DESC, r.sortorder ASC');
68c52526 2534}
2535
945f88ca 2536/**
eef868d1 2537 * Creates a record in the allow_override table
945f88ca 2538 * @param int sroleid - source roleid
2539 * @param int troleid - target roleid
2540 * @return int - id or false
2541 */
2542function allow_override($sroleid, $troleid) {
ece4945b 2543 $record = new object();
945f88ca 2544 $record->roleid = $sroleid;
2545 $record->allowoverride = $troleid;
2546 return insert_record('role_allow_override', $record);
2547}
2548
2549/**
eef868d1 2550 * Creates a record in the allow_assign table
945f88ca 2551 * @param int sroleid - source roleid
2552 * @param int troleid - target roleid
2553 * @return int - id or false
2554 */
2555function allow_assign($sroleid, $troleid) {
ff64aaea 2556 $record = new object;
945f88ca 2557 $record->roleid = $sroleid;
2558 $record->allowassign = $troleid;
2559 return insert_record('role_allow_assign', $record);
2560}
2561
2562/**
ff64aaea 2563 * Gets a list of roles that this user can assign in this context
945f88ca 2564 * @param object $context
2565 * @return array
2566 */
2567function get_assignable_roles ($context) {
2568
945f88ca 2569 $options = array();
ff64aaea 2570
ece4945b 2571 if ($roles = get_all_roles()) {
ff64aaea 2572 foreach ($roles as $role) {
2573 if (user_can_assign($context, $role->id)) {
65b0c132 2574 $options[$role->id] = strip_tags(format_string($role->name, true));
ff64aaea 2575 }
945f88ca 2576 }
2577 }
2578 return $options;
2579}
2580
2581/**
ff64aaea 2582 * Gets a list of roles that this user can override in this context
945f88ca 2583 * @param object $context
2584 * @return array
2585 */
2586function get_overridable_roles ($context) {
2587
945f88ca 2588 $options = array();
ff64aaea 2589
ece4945b 2590 if ($roles = get_all_roles()) {
ff64aaea 2591 foreach ($roles as $role) {
2592 if (user_can_override($context, $role->id)) {
65b0c132 2593 $options[$role->id] = strip_tags(format_string($role->name, true));
ff64aaea 2594 }
945f88ca 2595 }
ff64aaea 2596 }
eef868d1 2597
2598 return $options;
945f88ca 2599}
1648afb2 2600
b963384f 2601/*
2602 * Returns a role object that is the default role for new enrolments
2603 * in a given course
2604 *
eef868d1 2605 * @param object $course
b963384f 2606 * @return object $role
2607 */
2608function get_default_course_role($course) {
2609 global $CFG;
2610
2611/// First let's take the default role the course may have
2612 if (!empty($course->defaultrole)) {
2613 if ($role = get_record('role', 'id', $course->defaultrole)) {
2614 return $role;
2615 }
2616 }
2617
2618/// Otherwise the site setting should tell us
2619 if ($CFG->defaultcourseroleid) {
2620 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid)) {
2621 return $role;
2622 }
2623 }
2624
2625/// It's unlikely we'll get here, but just in case, try and find a student role
2626 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
2627 return array_shift($studentroles); /// Take the first one
2628 }
2629
2630 return NULL;
2631}
2632
1648afb2 2633
2634/**
2635 * who has this capability in this context
2636 * does not handling user level resolving!!!
2637 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
2638 * @param $context - object
2639 * @param $capability - string capability
2640 * @param $fields - fields to be pulled
2641 * @param $sort - the sort order
04417640 2642 * @param $limitfrom - number of records to skip (offset)
eef868d1 2643 * @param $limitnum - number of records to fetch
1c45e42e 2644 * @param $groups - single group or array of groups - group(s) user is in
71dea306 2645 * @param $exceptions - list of users to exclude
1648afb2 2646 */
eef868d1 2647function get_users_by_capability($context, $capability, $fields='', $sort='',
1d546bb1 2648 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true) {
1648afb2 2649 global $CFG;
eef868d1 2650
64026e8c 2651/// Sorting out groups
1c45e42e 2652 if ($groups) {
71dea306 2653 $groupjoin = 'INNER JOIN '.$CFG->prefix.'groups_members gm ON gm.userid = ra.userid';
eef868d1 2654
1c45e42e 2655 if (is_array($groups)) {
a05708ad 2656 $groupsql = 'AND gm.groupid IN ('.implode(',', $groups).')';
1c45e42e 2657 } else {
eef868d1 2658 $groupsql = 'AND gm.groupid = '.$groups;
1c45e42e 2659 }
2660 } else {
2661 $groupjoin = '';
eef868d1 2662 $groupsql = '';
1c45e42e 2663 }
eef868d1 2664
64026e8c 2665/// Sorting out exceptions
5081e786 2666 $exceptionsql = $exceptions ? "AND u.id NOT IN ($exceptions)" : '';
64026e8c 2667
2668/// Set up default fields
2669 if (empty($fields)) {
5b630667 2670 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
64026e8c 2671 }
2672
2673/// Set up default sort
2674 if (empty($sort)) {
2675 $sort = 'ul.timeaccess';
2676 }
2677
eef868d1 2678 $sortby = $sort ? " ORDER BY $sort " : '';
2679
64026e8c 2680/// If context is a course, then construct sql for ul
aad2ba95 2681 if ($context->contextlevel == CONTEXT_COURSE) {
71dea306 2682 $courseid = $context->instanceid;
f00b7f8d 2683 $coursesql = "AND (ul.courseid = $courseid OR ul.courseid IS NULL)";
5081e786 2684 } else {
2685 $coursesql = '';
71dea306 2686 }
64026e8c 2687
2688/// Sorting out roles with this capability set
9d829c68 2689 if ($possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context)) {
1d546bb1 2690 if (!$doanything) {
3ca2dea5 2691 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
1d546bb1 2692 return false; // Something is seriously wrong
2693 }
2694 $doanythingroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $sitecontext);
e836a7dd 2695 }
e836a7dd 2696
9d829c68 2697 $validroleids = array();
e836a7dd 2698 foreach ($possibleroles as $possiblerole) {
1d546bb1 2699 if (!$doanything) {
2700 if (isset($doanythingroles[$possiblerole->id])) { // We don't want these included
2701 continue;
2702 }
e836a7dd 2703 }
bccdf227 2704 if ($caps = role_context_capabilities($possiblerole->id, $context, $capability)) { // resolved list
2705 if (isset($caps[$capability]) && $caps[$capability] > 0) { // resolved capability > 0
2706 $validroleids[] = $possiblerole->id;
2707 }
9d829c68 2708 }
1648afb2 2709 }
1d546bb1 2710 if (empty($validroleids)) {
2711 return false;
2712 }
9d829c68 2713 $roleids = '('.implode(',', $validroleids).')';
2714 } else {
2715 return false; // No need to continue, since no roles have this capability set
eef868d1 2716 }
64026e8c 2717
2718/// Construct the main SQL
71dea306 2719 $select = " SELECT $fields";
eef868d1 2720 $from = " FROM {$CFG->prefix}user u
2721 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
0a3e9703 2722 INNER JOIN {$CFG->prefix}role r ON r.id = ra.roleid
71dea306 2723 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON ul.userid = u.id
2724 $groupjoin";
eef868d1 2725 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
2726 AND u.deleted = 0
2727 AND ra.roleid in $roleids
71dea306 2728 $exceptionsql
2729 $coursesql
2730 $groupsql";
2731
eef868d1 2732 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
1648afb2 2733}
7700027f 2734
ab5c9044 2735/**
2736 * gets all the users assigned this role in this context or higher
2737 * @param int roleid
2738 * @param int contextid
2739 * @param bool parent if true, get list of users assigned in higher context too
2740 * @return array()
2741 */
2742function get_role_users($roleid, $context, $parent=false) {
2743 global $CFG;
eef868d1 2744
ab5c9044 2745 if ($parent) {
2746 if ($contexts = get_parent_contexts($context)) {
2747 $parentcontexts = 'r.contextid IN ('.implode(',', $contexts).')';
2748 } else {
eef868d1 2749 $parentcontexts = '';
ab5c9044 2750 }
2751 } else {
eef868d1 2752 $parentcontexts = '';
2753 }
2754
2755 $SQL = "select u.*
2756 from {$CFG->prefix}role_assignments r,
2757 {$CFG->prefix}user u
2758 where (r.contextid = $context->id $parentcontexts)
2759 and r.roleid = $roleid
ab5c9044 2760 and u.id = r.userid"; // join now so that we can just use fullname() later
eef868d1 2761
ab5c9044 2762 return get_records_sql($SQL);
2763}
2764
eef868d1 2765/**
d76a5a7f 2766 * This function gets the list of courses that this user has a particular capability in
2767 * This is not the most efficient way of doing this
2768 * @param string capability
2769 * @param int $userid
2770 * @return array
2771 */
2772function get_user_capability_course($capability, $userid='') {
eef868d1 2773
d76a5a7f 2774 global $USER;
2775 if (!$userid) {
eef868d1 2776 $userid = $USER->id;
d76a5a7f 2777 }
eef868d1 2778
d76a5a7f 2779 $usercourses = array();
2780 $courses = get_records_select('course', '', '', 'id, id');
eef868d1 2781
d76a5a7f 2782 foreach ($courses as $course) {
2783 if (has_capability($capability, get_context_capability(CONTEXT_COURSE, $course->id))) {
2784 $usercourses[] = $course;
2785 }
2786 }
eef868d1 2787 return $usercourses;
e38f38c3 2788}
2789
2790
2791/** This function finds the roles assigned directly to this context only
2792 * i.e. no parents role
2793 * @param object $context
2794 * @return array
2795 */
2796function get_roles_on_exact_context($context) {
b5959f30 2797
e38f38c3 2798 global $CFG;
49293027 2799
b5959f30 2800 return get_records_sql("SELECT DISTINCT r.*
e38f38c3 2801 FROM {$CFG->prefix}role_assignments ra,
2802 {$CFG->prefix}role r
2803 WHERE ra.roleid = r.id
2804 AND ra.contextid = $context->id");
b5959f30 2805
49293027 2806}
2807
b5959f30 2808/*
3a52e764 2809 * Switches the current user to another role for the current session and only
b5959f30 2810 * in the given context. If roleid is not valid (eg 0) or the current user
2811 * doesn't have permissions to be switching roles then the user's session
3a52e764 2812 * is compltely reset to have their normal roles.
2813 * @param integer $roleid
2814 * @param object $context
2815 * @return bool
2816 */
2817function role_switch($roleid, $context) {
2818 global $USER;
2819
2820 global $db;
2821
2822/// If we can't use this or are already using it or no role was specified then bail completely and reset
b5959f30 2823 if (empty($roleid) || !has_capability('moodle/role:switchroles', $context)
2d07587b 2824 || !empty($USER->switchrole[$context->id]) || !confirm_sesskey()) {
2825 load_user_capability('', $context); // Reset all permissions for this context to normal
2826 unset($USER->switchrole[$context->id]); // Delete old capabilities
3a52e764 2827 return true;
2828 }
2829
2830/// We're allowed to switch but can we switch to the specified role? Use assignable roles to check.
2831 if (!$roles = get_assignable_roles($context)) {
2832 return false;
2833 }
2834
2835 if (empty($roles[$roleid])) { /// We can't switch to this particular role
2836 return false;
2837 }
2838
2839 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
2840 return false;
2841 }
2842
2843/// We have a valid roleid that this user can switch to, so let's set up the session
2844
2d07587b 2845 $USER->switchrole[$context->id] = $roleid; // So we know later what state we are in
3a52e764 2846
2847 unset($USER->capabilities[$context->id]); // Delete old capabilities
2848
2849 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $sitecontext->id")) {
2850 foreach ($capabilities as $capability) {
2851 $USER->capabilities[$context->id][$capability->capability] = $capability->permission;
2852 }
2853 }
2854
2d07587b 2855/// Add some permissions we are really going to always need, even if the role doesn't have them!
3a52e764 2856
2857 $USER->capabilities[$context->id]['moodle/course:view'] = CAP_ALLOW;
2858
2859 return true;
2860
2861}
2862
2863
49293027 2864// get any role that has an override on exact context
2865function get_roles_with_override_on_context($context) {
b5959f30 2866
49293027 2867 global $CFG;
b5959f30 2868
49293027 2869 return get_records_sql("SELECT DISTINCT r.*
2870 FROM {$CFG->prefix}role_capabilities rc,
2871 {$CFG->prefix}role r
2872 WHERE rc.roleid = r.id
2873 AND rc.contextid = $context->id");
2874}
2875
2876// get all capabilities for this role on this context (overrids)
2877function get_capabilities_from_role_on_context($role, $context) {
b5959f30 2878
49293027 2879 global $CFG;
b5959f30 2880
2881 return get_records_sql("SELECT *
49293027 2882 FROM {$CFG->prefix}role_capabilities
2883 WHERE contextid = $context->id
2884 AND roleid = $role->id");
01e52ac7 2885}
2886
5b5781f4 2887// find out which roles has assignment on this context
2888function get_roles_with_assignment_on_context($context) {
ece4945b 2889
5b5781f4 2890 global $CFG;
ece4945b 2891
5b5781f4 2892 return get_records_sql("SELECT DISTINCT r.*
2893 FROM {$CFG->prefix}role_assignments ra,
2894 {$CFG->prefix}role r
2895 WHERE ra.roleid = r.id
2896 AND ra.contextid = $context->id");
2897}
2898
2899
2900
01e52ac7 2901/* find all user assignemnt of users for this role, on this context
2902 */
2903function get_users_from_role_on_context($role, $context) {
b5959f30 2904
01e52ac7 2905 global $CFG;
b5959f30 2906
01e52ac7 2907 return get_records_sql("SELECT *
2908 FROM {$CFG->prefix}role_assignments
2909 WHERE contextid = $context->id
b5959f30 2910 AND roleid = $role->id");
01e52ac7 2911}
3a52e764 2912
f3652521 2913?>