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