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