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