role assignment and unassignment now propagates to metacourses
[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).
bbbf2d40 890 $adminrole = create_role(get_string('administrator'), 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 }
894 $coursecreatorrole = create_role(get_string('coursecreators'), get_string('coursecreatorsdescription'), 'moodle/legacy:coursecreator');
98882637 895 $noneditteacherrole = create_role(get_string('noneditingteacher'), get_string('noneditingteacherdescription'), 'moodle/legacy:teacher');
896 $editteacherrole = create_role(get_string('defaultcourseteacher'), get_string('defaultcourseteacherdescription'), 'moodle/legacy:editingteacher');
897 $studentrole = create_role(get_string('defaultcoursestudent'), get_string('defaultcoursestudentdescription'), 'moodle/legacy:student');
bbbf2d40 898 $guestrole = create_role(get_string('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
1013 /// Upgrade course table with defaultrole values
1014 execute_sql('UPDATE '.$CFG->prefix.'course SET defaultrole = '.$studentrole);
1015
1016
1afecc03 1017 // Should we delete the tables after we are done? Not yet.
bbbf2d40 1018}
1019
bbbf2d40 1020/**
1021 * Assign the defaults found in this capabality definition to roles that have
1022 * the corresponding legacy capabilities assigned to them.
1023 * @param $legacyperms - an array in the format (example):
1024 * 'guest' => CAP_PREVENT,
1025 * 'student' => CAP_ALLOW,
1026 * 'teacher' => CAP_ALLOW,
1027 * 'editingteacher' => CAP_ALLOW,
1028 * 'coursecreator' => CAP_ALLOW,
1029 * 'admin' => CAP_ALLOW
1030 * @return boolean - success or failure.
1031 */
1032function assign_legacy_capabilities($capability, $legacyperms) {
1033
1034 foreach ($legacyperms as $type => $perm) {
1035
1036 $systemcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
1037
1038 // The legacy capabilities are:
1039 // 'moodle/legacy:guest'
1040 // 'moodle/legacy:student'
1041 // 'moodle/legacy:teacher'
1042 // 'moodle/legacy:editingteacher'
1043 // 'moodle/legacy:coursecreator'
1044 // 'moodle/legacy:admin'
1045
2e85fffe 1046 if ($roles = get_roles_with_capability('moodle/legacy:'.$type, CAP_ALLOW)) {
1047 foreach ($roles as $role) {
1048 // Assign a site level capability.
1049 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1050 return false;
1051 }
bbbf2d40 1052 }
1053 }
1054 }
1055 return true;
1056}
1057
1058
cee0901c 1059/**
1060 * Checks to see if a capability is a legacy capability.
1061 * @param $capabilityname
1062 * @return boolean
1063 */
bbbf2d40 1064function islegacy($capabilityname) {
98882637 1065 if (strstr($capabilityname, 'legacy') === false) {
1066 return false;
1067 } else {
1068 return true;
1069 }
bbbf2d40 1070}
1071
cee0901c 1072
1073
1074/**********************************
bbbf2d40 1075 * Context Manipulation functions *
1076 **********************************/
1077
bbbf2d40 1078/**
1079 * This should be called prolly everytime a user, group, module, course,
1080 * coursecat or site is set up maybe?
1081 * @param $level
1082 * @param $instanceid
1083 */
d140ad3f 1084function create_context($aggregatelevel, $instanceid) {
1085 if (!get_record('context','aggregatelevel',$aggregatelevel,'instanceid',$instanceid)) {
bbbf2d40 1086 $context = new object;
d140ad3f 1087 $context->aggregatelevel = $aggregatelevel;
bbbf2d40 1088 $context->instanceid = $instanceid;
1089 return insert_record('context',$context);
1090 }
1091}
1092
1093
1094/**
1095 * Get the context instance as an object. This function will create the
1096 * context instance if it does not exist yet.
1097 * @param $level
1098 * @param $instance
1099 */
d140ad3f 1100function get_context_instance($aggregatelevel=NULL, $instance=SITEID) {
e5605780 1101
51195e6f 1102 global $context_cache, $context_cache_id, $CONTEXT;
d9a35e12 1103
340ea4e8 1104/// If no level is supplied then return the current global context if there is one
d140ad3f 1105 if (empty($aggregatelevel)) {
340ea4e8 1106 if (empty($CONTEXT)) {
ea82d6b6 1107 debugging("Error: get_context_instance() called without a context");
340ea4e8 1108 } else {
1109 return $CONTEXT;
1110 }
e5605780 1111 }
1112
340ea4e8 1113/// Check the cache
d140ad3f 1114 if (isset($context_cache[$aggregatelevel][$instance])) { // Already cached
1115 return $context_cache[$aggregatelevel][$instance];
e5605780 1116 }
1117
340ea4e8 1118/// Get it from the database, or create it
d140ad3f 1119 if (!$context = get_record('context', 'aggregatelevel', $aggregatelevel, 'instanceid', $instance)) {
1120 create_context($aggregatelevel, $instance);
1121 $context = get_record('context', 'aggregatelevel', $aggregatelevel, 'instanceid', $instance);
e5605780 1122 }
1123
ccfc5ecc 1124/// Only add to cache if context isn't empty.
1125 if (!empty($context)) {
1126 $context_cache[$aggregatelevel][$instance] = $context; // Cache it for later
1127 $context_cache_id[$context->id] = $context; // Cache it for later
1128 }
0468976c 1129
bbbf2d40 1130 return $context;
1131}
1132
cee0901c 1133
340ea4e8 1134/**
1135 * Get a context instance as an object, from a given id.
1136 * @param $id
1137 */
1138function get_context_instance_by_id($id) {
1139
d9a35e12 1140 global $context_cache, $context_cache_id;
1141
340ea4e8 1142 if (isset($context_cache_id[$id])) { // Already cached
75e84883 1143 return $context_cache_id[$id];
340ea4e8 1144 }
1145
1146 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
d140ad3f 1147 $context_cache[$context->aggregatelevel][$context->instanceid] = $context;
340ea4e8 1148 $context_cache_id[$context->id] = $context;
1149 return $context;
1150 }
1151
1152 return false;
1153}
1154
bbbf2d40 1155
8737be58 1156/**
1157 * Get the local override (if any) for a given capability in a role in a context
1158 * @param $roleid
0468976c 1159 * @param $contextid
1160 * @param $capability
8737be58 1161 */
1162function get_local_override($roleid, $contextid, $capability) {
1163 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1164}
1165
1166
bbbf2d40 1167
1168/************************************
1169 * DB TABLE RELATED FUNCTIONS *
1170 ************************************/
1171
cee0901c 1172/**
bbbf2d40 1173 * function that creates a role
1174 * @param name - role name
1175 * @param description - role description
1176 * @param legacy - optional legacy capability
1177 * @return id or false
1178 */
1179function create_role($name, $description, $legacy='') {
98882637 1180
1181 // check for duplicate role name
1182
1183 if ($role = get_record('role','name', $name)) {
98882637 1184 error('there is already a role with this name!');
1185 }
1186
1187 $role->name = $name;
1188 $role->description = $description;
ec7a8b79 1189
1190 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
1191
98882637 1192 if ($id = insert_record('role', $role)) {
ec7a8b79 1193 if ($legacy) {
1afecc03 1194 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
98882637 1195 }
ec7a8b79 1196
1197 /// By default, users with role:manage at site level
1198 /// should be able to assign users to this new role, and override this new role's capabilities
1199
1200 // find all admin roles
e46c0987 1201 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
1202 // foreach admin role
1203 foreach ($adminroles as $arole) {
1204 // write allow_assign and allow_overrid
1205 allow_assign($arole->id, $id);
1206 allow_override($arole->id, $id);
1207 }
ec7a8b79 1208 }
1209
98882637 1210 return $id;
1211 } else {
1212 return false;
1213 }
bbbf2d40 1214
1215}
1216
1217/**
1218 * Function to write context specific overrides, or default capabilities.
1219 * @param module - string name
1220 * @param capability - string name
1221 * @param contextid - context id
1222 * @param roleid - role id
1223 * @param permission - int 1,-1 or -1000
1224 */
e7876c1e 1225function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
98882637 1226
1227 global $USER;
1228
1229 if (empty($permission) || $permission == 0) { // if permission is not set
1230 unassign_capability($capability, $roleid, $contextid);
1231 }
bbbf2d40 1232
2e85fffe 1233 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
e7876c1e 1234
1235 if ($existing and !$overwrite) { // We want to keep whatever is there already
1236 return true;
1237 }
1238
bbbf2d40 1239 $cap = new object;
1240 $cap->contextid = $contextid;
1241 $cap->roleid = $roleid;
1242 $cap->capability = $capability;
1243 $cap->permission = $permission;
1244 $cap->timemodified = time();
9db12da7 1245 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
e7876c1e 1246
1247 if ($existing) {
1248 $cap->id = $existing->id;
1249 return update_record('role_capabilities', $cap);
1250 } else {
1251 return insert_record('role_capabilities', $cap);
1252 }
bbbf2d40 1253}
1254
1255
1256/**
1257 * Unassign a capability from a role.
1258 * @param $roleid - the role id
1259 * @param $capability - the name of the capability
1260 * @return boolean - success or failure
1261 */
1262function unassign_capability($capability, $roleid, $contextid=NULL) {
98882637 1263
1264 if (isset($contextid)) {
1265 $status = delete_records('role_capabilities', 'capability', $capability,
1266 'roleid', $roleid, 'contextid', $contextid);
1267 } else {
1268 $status = delete_records('role_capabilities', 'capability', $capability,
1269 'roleid', $roleid);
1270 }
1271 return $status;
bbbf2d40 1272}
1273
1274
1275/**
1276 * Get the roles that have a given capability.
1277 * @param $capability - capability name (string)
1278 * @param $permission - optional, the permission defined for this capability
1279 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
1280 * @return array or role objects
1281 */
ec7a8b79 1282function get_roles_with_capability($capability, $permission=NULL, $context='') {
1283
bbbf2d40 1284 global $CFG;
1285
ec7a8b79 1286 if ($context) {
1287 if ($contexts = get_parent_contexts($context)) {
1288 $listofcontexts = '('.implode(',', $contexts).')';
1289 } else {
1290 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
1291 $listofcontexts = '('.$sitecontext->id.')'; // must be site
1292 }
42ac3ecf 1293 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
ec7a8b79 1294 } else {
1295 $contextstr = '';
1296 }
1297
bbbf2d40 1298 $selectroles = "SELECT r.*
42ac3ecf 1299 FROM {$CFG->prefix}role r,
1300 {$CFG->prefix}role_capabilities rc
bbbf2d40 1301 WHERE rc.capability = '$capability'
ec7a8b79 1302 AND rc.roleid = r.id $contextstr";
bbbf2d40 1303
1304 if (isset($permission)) {
1305 $selectroles .= " AND rc.permission = '$permission'";
1306 }
1307 return get_records_sql($selectroles);
1308}
1309
1310
1311/**
a9e1c058 1312 * This function makes a role-assignment (a role for a user or group in a particular context)
bbbf2d40 1313 * @param $roleid - the role of the id
1314 * @param $userid - userid
1315 * @param $groupid - group id
1316 * @param $contextid - id of the context
1317 * @param $timestart - time this assignment becomes effective
1318 * @param $timeend - time this assignemnt ceases to be effective
1319 * @uses $USER
1320 * @return id - new id of the assigment
1321 */
f44152f4 1322function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual') {
aa311411 1323 global $USER, $CFG;
bbbf2d40 1324
ea82d6b6 1325 debugging("Assign roleid $roleid userid $userid contextid $contextid", E_ALL);
bbbf2d40 1326
a9e1c058 1327/// Do some data validation
1328
bbbf2d40 1329 if (empty($roleid)) {
a9e1c058 1330 notify('Role ID not provided');
1331 return false;
bbbf2d40 1332 }
1333
1334 if (empty($userid) && empty($groupid)) {
a9e1c058 1335 notify('Either userid or groupid must be provided');
1336 return false;
bbbf2d40 1337 }
7700027f 1338
1339 if ($userid && !record_exists('user', 'id', $userid)) {
1340 notify('User does not exist!');
1341 return false;
1342 }
bbbf2d40 1343
dc411d1b 1344 if ($groupid && !record_exists('groups', 'id', $groupid)) {
1345 notify('Group does not exist!');
1346 return false;
1347 }
1348
7700027f 1349 if (!$context = get_context_instance_by_id($contextid)) {
a9e1c058 1350 notify('A valid context must be provided');
1351 return false;
bbbf2d40 1352 }
1353
a9e1c058 1354 if (($timestart and $timeend) and ($timestart > $timeend)) {
7700027f 1355 notify('The end time can not be earlier than the start time');
a9e1c058 1356 return false;
1357 }
1358
7700027f 1359
a9e1c058 1360/// Check for existing entry
1361 if ($userid) {
7700027f 1362 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
a9e1c058 1363 } else {
7700027f 1364 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
a9e1c058 1365 }
1366
9ebcb4d2 1367
a9e1c058 1368 $newra = new object;
bbbf2d40 1369
a9e1c058 1370 if (empty($ra)) { // Create a new entry
1371 $newra->roleid = $roleid;
7700027f 1372 $newra->contextid = $context->id;
a9e1c058 1373 $newra->userid = $userid;
1374 $newra->groupid = $groupid;
1375
1376 $newra->hidden = $hidden;
f44152f4 1377 $newra->enrol = $enrol;
a9e1c058 1378 $newra->timestart = $timestart;
1379 $newra->timeend = $timeend;
1380 $newra->timemodified = time();
1381 $newra->modifier = empty($USER->id) ? 0 : $USER->id;
1382
9ebcb4d2 1383 $success = insert_record('role_assignments', $newra);
a9e1c058 1384
1385 } else { // We already have one, just update it
1386
1387 $newra->id = $ra->id;
1388 $newra->hidden = $hidden;
f44152f4 1389 $newra->enrol = $enrol;
a9e1c058 1390 $newra->timestart = $timestart;
1391 $newra->timeend = $timeend;
1392 $newra->timemodified = time();
1393 $newra->modifier = empty($USER->id) ? 0 : $USER->id;
1394
9ebcb4d2 1395 $success = update_record('role_assignments', $newra);
1396 }
1397
7700027f 1398 if ($success) { /// Role was assigned, so do some other things
1399
1400 /// If the user is the current user, then reload the capabilities too.
1401 if (!empty($USER->id) && $USER->id == $userid) {
1402 load_user_capability();
1403 }
1404
0f161e1f 1405 /// Ask all the modules if anything needs to be done for this user
1406 if ($mods = get_list_of_plugins('mod')) {
1407 foreach ($mods as $mod) {
1408 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
1409 $functionname = $mod.'_role_assign';
1410 if (function_exists($functionname)) {
1411 $functionname($userid, $context);
1412 }
1413 }
1414 }
1415
1416 /// Make sure they have an entry in user_lastaccess for courses they can access
1417 // role_add_lastaccess_entries($userid, $context);
a9e1c058 1418 }
4e5f3064 1419
1420 /// now handle metacourse role assignments if in course context
1421 if ($success and $context->aggregatelevel == CONTEXT_COURSE) {
1422 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
1423 foreach ($parents as $parent) {
1424 if ($metacontext = get_context_instance(CONTEXT_COURSE, $parent->parent_course)) {
1425 // try it even when something failed
1426 $success = $success and role_assign($roleid, $userid, $groupid, $metacontext->id, $timestart, $timeend, $hidden, $enrol);
1427 }
1428 }
1429 }
1430 }
6eb4f823 1431
1432 return $success;
bbbf2d40 1433}
1434
1435
1436/**
1dc1f037 1437 * Deletes one or more role assignments. You must specify at least one parameter.
bbbf2d40 1438 * @param $roleid
1439 * @param $userid
1440 * @param $groupid
1441 * @param $contextid
1442 * @return boolean - success or failure
1443 */
1dc1f037 1444function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0) {
d74067e8 1445
1446 global $USER, $CFG;
4e5f3064 1447
1448 $success = true;
d74067e8 1449
1dc1f037 1450 $args = array('roleid', 'userid', 'groupid', 'contextid');
1451 $select = array();
1452 foreach ($args as $arg) {
1453 if ($$arg) {
1454 $select[] = $arg.' = '.$$arg;
1455 }
1456 }
d74067e8 1457
1dc1f037 1458 if ($select) {
4e5f3064 1459 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
1460 $mods = get_list_of_plugins('mod');
1461 foreach($ras as $ra) {
1462 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
1463 /// If the user is the current user, then reload the capabilities too.
1464 if (!empty($USER->id) && $USER->id == $ra->userid) {
1465 load_user_capability();
1466 }
1467 $context = get_record('context', 'id', $ra->contextid);
0f161e1f 1468
1469 /// Ask all the modules if anything needs to be done for this user
4e5f3064 1470 foreach ($mods as $mod) {
1471 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
1472 $functionname = $mod.'_role_unassign';
1473 if (function_exists($functionname)) {
1474 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
1475 }
1476 }
1477
1478 /// now handle metacourse role unassigment and removing from goups if in course context
1479 if (!empty($context) and $context->aggregatelevel == CONTEXT_COURSE) {
1480 //remove from groups when user has no role
1481 $roles = get_user_roles($context, $ra->userid, true);
1482 if (empty($roles)) {
1483 if ($groups = get_groups($context->instanceid, $ra->userid)) {
1484 foreach ($groups as $group) {
1485 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
1486 }
1487 }
1488 }
1489 //unassign roles in metacourses too
1490 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
1491 foreach ($parents as $parent) {
1492 if ($metacontext = get_context_instance(CONTEXT_COURSE, $parent->parent_course)) {
1493 // ignore errors in metacourses in case they are not properly synchronized
1494 role_unassign($roleid, $userid, $groupid, $metacontext->id);
0f161e1f 1495 }
1496 }
1497 }
0f161e1f 1498 }
1499 }
d74067e8 1500 }
1dc1f037 1501 }
4e5f3064 1502
1503 return $success;
bbbf2d40 1504}
1505
0f161e1f 1506/**
1507 * Add last access times to user_lastaccess as required
1508 * @param $userid
1509 * @param $context
1510 * @return boolean - success or failure
1511 */
1512function role_add_lastaccess_entries($userid, $context) {
1513
1514 global $USER, $CFG;
1515
1516 if (empty($context->aggregatelevel)) {
1517 return false;
1518 }
1519
1520 $lastaccess = new object; // Reusable object below
1521 $lastaccess->userid = $userid;
1522 $lastaccess->timeaccess = 0;
1523
1524 switch ($context->aggregatelevel) {
1525
1526 case CONTEXT_SYSTEM: // For the whole site
1527 if ($courses = get_record('course')) {
1528 foreach ($courses as $course) {
1529 $lastaccess->courseid = $course->id;
1530 role_set_lastaccess($lastaccess);
1531 }
1532 }
1533 break;
1534
1535 case CONTEXT_CATEGORY: // For a whole category
1536 if ($courses = get_record('course', 'category', $context->instanceid)) {
1537 foreach ($courses as $course) {
1538 $lastaccess->courseid = $course->id;
1539 role_set_lastaccess($lastaccess);
1540 }
1541 }
1542 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
1543 foreach ($categories as $category) {
1544 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
1545 role_add_lastaccess_entries($userid, $subcontext);
1546 }
1547 }
1548 break;
1549
1550
1551 case CONTEXT_COURSE: // For a whole course
1552 if ($course = get_record('course', 'id', $context->instanceid)) {
1553 $lastaccess->courseid = $course->id;
1554 role_set_lastaccess($lastaccess);
1555 }
1556 break;
1557 }
1558}
1559
1560/**
1561 * Delete last access times from user_lastaccess as required
1562 * @param $userid
1563 * @param $context
1564 * @return boolean - success or failure
1565 */
1566function role_remove_lastaccess_entries($userid, $context) {
1567
1568 global $USER, $CFG;
1569
1570}
1571
bbbf2d40 1572
1573/**
1574 * Loads the capability definitions for the component (from file). If no
1575 * capabilities are defined for the component, we simply return an empty array.
1576 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1577 * @return array of capabilities
1578 */
1579function load_capability_def($component) {
1580 global $CFG;
1581
1582 if ($component == 'moodle') {
1583 $defpath = $CFG->libdir.'/db/access.php';
1584 $varprefix = 'moodle';
1585 } else {
0c4d9f49 1586 $compparts = explode('/', $component);
1587
1588 if ($compparts[0] == 'block') {
1589 // Blocks are an exception. Blocks directory is 'blocks', and not
1590 // 'block'. So we need to jump through hoops.
1591 $defpath = $CFG->dirroot.'/'.$compparts[0].
1592 's/'.$compparts[1].'/db/access.php';
1593 $varprefix = $compparts[0].'_'.$compparts[1];
1594 } else {
1595 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
1596 $varprefix = str_replace('/', '_', $component);
1597 }
bbbf2d40 1598 }
1599 $capabilities = array();
1600
1601 if (file_exists($defpath)) {
1602 require_once($defpath);
1603 $capabilities = ${$varprefix.'_capabilities'};
1604 }
1605 return $capabilities;
1606}
1607
1608
1609/**
1610 * Gets the capabilities that have been cached in the database for this
1611 * component.
1612 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1613 * @return array of capabilities
1614 */
1615function get_cached_capabilities($component='moodle') {
1616 if ($component == 'moodle') {
1617 $storedcaps = get_records_select('capabilities',
1618 "name LIKE 'moodle/%:%'");
1619 } else {
1620 $storedcaps = get_records_select('capabilities',
1621 "name LIKE '$component:%'");
1622 }
1623 return $storedcaps;
1624}
1625
1626
1627/**
1628 * Updates the capabilities table with the component capability definitions.
1629 * If no parameters are given, the function updates the core moodle
1630 * capabilities.
1631 *
1632 * Note that the absence of the db/access.php capabilities definition file
1633 * will cause any stored capabilities for the component to be removed from
1634 * the database.
1635 *
1636 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1637 * @return boolean
1638 */
1639function update_capabilities($component='moodle') {
1640
1641 $storedcaps = array();
be4486da 1642
1643 $filecaps = load_capability_def($component);
bbbf2d40 1644 $cachedcaps = get_cached_capabilities($component);
1645 if ($cachedcaps) {
1646 foreach ($cachedcaps as $cachedcap) {
1647 array_push($storedcaps, $cachedcap->name);
be4486da 1648 // update risk bitmasks in existing capabilitites if needed
1649 if (array_key_exists($cachedcap->name, $filecaps)) {
1650 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2b531945 1651 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
be4486da 1652 }
1653 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
1654 $updatecap = new object;
1655 $updatecap->id = $cachedcap->id;
1656 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
1657 if (!update_record('capabilities', $updatecap)) {
1658 return false;
1659 }
1660 }
1661 }
bbbf2d40 1662 }
1663 }
be4486da 1664
bbbf2d40 1665 // Are there new capabilities in the file definition?
1666 $newcaps = array();
1667
1668 foreach ($filecaps as $filecap => $def) {
1669 if (!$storedcaps ||
1670 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2b531945 1671 if (!array_key_exists('riskbitmask', $def)) {
1672 $def['riskbitmask'] = 0; // no risk if not specified
1673 }
bbbf2d40 1674 $newcaps[$filecap] = $def;
1675 }
1676 }
1677 // Add new capabilities to the stored definition.
1678 foreach ($newcaps as $capname => $capdef) {
1679 $capability = new object;
1680 $capability->name = $capname;
1681 $capability->captype = $capdef['captype'];
1682 $capability->contextlevel = $capdef['contextlevel'];
1683 $capability->component = $component;
be4486da 1684 $capability->riskbitmask = $capdef['riskbitmask'];
bbbf2d40 1685
1686 if (!insert_record('capabilities', $capability, false, 'id')) {
1687 return false;
1688 }
ab5c9044 1689
1690 global $db;
1691 $db->debug= 999;
bbbf2d40 1692 // Do we need to assign the new capabilities to roles that have the
1693 // legacy capabilities moodle/legacy:* as well?
1694 if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
1695 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2e85fffe 1696 notify('Could not assign legacy capabilities for '.$capname);
bbbf2d40 1697 }
1698 }
1699 // Are there any capabilities that have been removed from the file
1700 // definition that we need to delete from the stored capabilities and
1701 // role assignments?
1702 capabilities_cleanup($component, $filecaps);
1703
1704 return true;
1705}
1706
1707
1708/**
1709 * Deletes cached capabilities that are no longer needed by the component.
1710 * Also unassigns these capabilities from any roles that have them.
1711 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1712 * @param $newcapdef - array of the new capability definitions that will be
1713 * compared with the cached capabilities
1714 * @return int - number of deprecated capabilities that have been removed
1715 */
1716function capabilities_cleanup($component, $newcapdef=NULL) {
1717
1718 $removedcount = 0;
1719
1720 if ($cachedcaps = get_cached_capabilities($component)) {
1721 foreach ($cachedcaps as $cachedcap) {
1722 if (empty($newcapdef) ||
1723 array_key_exists($cachedcap->name, $newcapdef) === false) {
1724
1725 // Remove from capabilities cache.
1726 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
1727 error('Could not delete deprecated capability '.$cachedcap->name);
1728 } else {
1729 $removedcount++;
1730 }
1731 // Delete from roles.
1732 if($roles = get_roles_with_capability($cachedcap->name)) {
1733 foreach($roles as $role) {
46943f7b 1734 if (!unassign_capability($cachedcap->name, $role->id)) {
bbbf2d40 1735 error('Could not unassign deprecated capability '.
1736 $cachedcap->name.' from role '.$role->name);
1737 }
1738 }
1739 }
1740 } // End if.
1741 }
1742 }
1743 return $removedcount;
1744}
1745
1746
1747
cee0901c 1748/****************
1749 * UI FUNCTIONS *
1750 ****************/
bbbf2d40 1751
1752
1753/**
1754 * prints human readable context identifier.
1755 */
0468976c 1756function print_context_name($context) {
340ea4e8 1757
ec0810ee 1758 $name = '';
d140ad3f 1759 switch ($context->aggregatelevel) {
ec0810ee 1760
bbbf2d40 1761 case CONTEXT_SYSTEM: // by now it's a definite an inherit
ec0810ee 1762 $name = get_string('site');
340ea4e8 1763 break;
bbbf2d40 1764
1765 case CONTEXT_PERSONAL:
ec0810ee 1766 $name = get_string('personal');
340ea4e8 1767 break;
1768
4b10f08b 1769 case CONTEXT_USER:
ec0810ee 1770 if ($user = get_record('user', 'id', $context->instanceid)) {
1771 $name = get_string('user').': '.fullname($user);
1772 }
340ea4e8 1773 break;
1774
bbbf2d40 1775 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
ec0810ee 1776 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
1777 $name = get_string('category').': '.$category->name;
1778 }
340ea4e8 1779 break;
bbbf2d40 1780
1781 case CONTEXT_COURSE: // 1 to 1 to course cat
ec0810ee 1782 if ($course = get_record('course', 'id', $context->instanceid)) {
1783 $name = get_string('course').': '.$course->fullname;
1784 }
340ea4e8 1785 break;
bbbf2d40 1786
1787 case CONTEXT_GROUP: // 1 to 1 to course
ec0810ee 1788 if ($group = get_record('groups', 'id', $context->instanceid)) {
1789 $name = get_string('group').': '.$group->name;
1790 }
340ea4e8 1791 break;
bbbf2d40 1792
1793 case CONTEXT_MODULE: // 1 to 1 to course
98882637 1794 if ($cm = get_record('course_modules','id',$context->instanceid)) {
1795 if ($module = get_record('modules','id',$cm->module)) {
1796 if ($mod = get_record($module->name, 'id', $cm->instance)) {
ec0810ee 1797 $name = get_string('activitymodule').': '.$mod->name;
98882637 1798 }
ec0810ee 1799 }
1800 }
340ea4e8 1801 break;
bbbf2d40 1802
1803 case CONTEXT_BLOCK: // 1 to 1 to course
98882637 1804 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
1805 if ($block = get_record('block','id',$blockinstance->blockid)) {
91be52d7 1806 global $CFG;
1807 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
1808 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
1809 $blockname = "block_$block->name";
1810 if ($blockobject = new $blockname()) {
1811 $name = $blockobject->title.' ('.get_string('block').')';
1812 }
ec0810ee 1813 }
1814 }
340ea4e8 1815 break;
bbbf2d40 1816
1817 default:
1818 error ('This is an unknown context!');
340ea4e8 1819 return false;
1820
1821 }
340ea4e8 1822 return $name;
bbbf2d40 1823}
1824
1825
1826/**
1827 * Extracts the relevant capabilities given a contextid.
1828 * All case based, example an instance of forum context.
1829 * Will fetch all forum related capabilities, while course contexts
1830 * Will fetch all capabilities
0468976c 1831 * @param object context
bbbf2d40 1832 * @return array();
1833 *
1834 * capabilities
1835 * `name` varchar(150) NOT NULL,
1836 * `captype` varchar(50) NOT NULL,
1837 * `contextlevel` int(10) NOT NULL,
1838 * `component` varchar(100) NOT NULL,
1839 */
0468976c 1840function fetch_context_capabilities($context) {
98882637 1841
1842 global $CFG;
bbbf2d40 1843
1844 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
98882637 1845
d140ad3f 1846 switch ($context->aggregatelevel) {
bbbf2d40 1847
98882637 1848 case CONTEXT_SYSTEM: // all
1849 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1850 break;
1851
1852 case CONTEXT_PERSONAL:
0a8a95c9 1853 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
bbbf2d40 1854 break;
1855
4b10f08b 1856 case CONTEXT_USER:
1857 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_USER;
bbbf2d40 1858 break;
1859
1860 case CONTEXT_COURSECAT: // all
98882637 1861 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1862 break;
1863
1864 case CONTEXT_COURSE: // all
98882637 1865 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1866 break;
1867
1868 case CONTEXT_GROUP: // group caps
1869 break;
1870
1871 case CONTEXT_MODULE: // mod caps
98882637 1872 $cm = get_record('course_modules', 'id', $context->instanceid);
1873 $module = get_record('modules', 'id', $cm->module);
bbbf2d40 1874
98882637 1875 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
1876 and component = 'mod/$module->name'";
bbbf2d40 1877 break;
1878
1879 case CONTEXT_BLOCK: // block caps
98882637 1880 $cb = get_record('block_instance', 'id', $context->instanceid);
1881 $block = get_record('block', 'id', $cb->blockid);
bbbf2d40 1882
98882637 1883 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
1884 and component = 'block/$block->name'";
bbbf2d40 1885 break;
1886
1887 default:
1888 return false;
1889 }
1890
1891 $records = get_records_sql($SQL.' '.$sort);
69eb59f2 1892
1893 // special sorting of core system capabiltites and enrollments
1894 if ($context->aggregatelevel == CONTEXT_SYSTEM) {
1895 $first = array();
1896 foreach ($records as $key=>$record) {
1897 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
1898 $first[$key] = $record;
1899 unset($records[$key]);
1900 } else if (count($first)){
1901 break;
1902 }
1903 }
1904 if (count($first)) {
1905 $records = $first + $records; // merge the two arrays keeping the keys
1906 }
1907 }
1908 // end of special sorting
1909
bbbf2d40 1910 return $records;
1911
1912}
1913
1914
1915/**
1916 * This function pulls out all the resolved capabilities (overrides and
1917 * defaults) of a role used in capability overrieds in contexts at a given
1918 * context.
0a8a95c9 1919 * @param obj $context
bbbf2d40 1920 * @param int $roleid
1921 * @return array
1922 */
1648afb2 1923function role_context_capabilities($roleid, $context, $cap='') {
98882637 1924 global $CFG;
1925
1926 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
0468976c 1927 if ($sitecontext->id == $context->id) {
20aeb4b8 1928 $contexts = array($sitecontext->id);
1929 } else {
1930 // first of all, figure out all parental contexts
1931 $contexts = array_reverse(get_parent_contexts($context));
98882637 1932 }
98882637 1933 $contexts = '('.implode(',', $contexts).')';
1934
1648afb2 1935 if ($cap) {
e4697bf7 1936 $search = " AND rc.capability = '$cap' ";
1648afb2 1937 } else {
1938 $search = '';
1939 }
1940
98882637 1941 $SQL = "SELECT rc.* FROM {$CFG->prefix}role_capabilities rc, {$CFG->prefix}context c
1942 where rc.contextid in $contexts
1943 and rc.roleid = $roleid
1648afb2 1944 and rc.contextid = c.id $search
d140ad3f 1945 ORDER BY c.aggregatelevel DESC, rc.capability DESC";
1648afb2 1946
98882637 1947 $capabilities = array();
1948
4729012f 1949 if ($records = get_records_sql($SQL)) {
1950 // We are traversing via reverse order.
1951 foreach ($records as $record) {
1952 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
1953 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
1954 $capabilities[$record->capability] = $record->permission;
1955 }
1956 }
98882637 1957 }
1958 return $capabilities;
bbbf2d40 1959}
1960
bbbf2d40 1961/**
0468976c 1962 * Recursive function which, given a context, find all parent context ids,
bbbf2d40 1963 * and return the array in reverse order, i.e. parent first, then grand
1964 * parent, etc.
1965 * @param object $context
1966 * @return array()
1967 */
bbbf2d40 1968function get_parent_contexts($context) {
1969
d140ad3f 1970 switch ($context->aggregatelevel) {
bbbf2d40 1971
1972 case CONTEXT_SYSTEM: // no parent
957861f7 1973 return array();
bbbf2d40 1974 break;
1975
1976 case CONTEXT_PERSONAL:
957861f7 1977 if (!$parent = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
1978 return array();
1979 } else {
1980 return array($parent->id);
1981 }
bbbf2d40 1982 break;
1983
4b10f08b 1984 case CONTEXT_USER:
957861f7 1985 if (!$parent = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
1986 return array();
1987 } else {
1988 return array($parent->id);
1989 }
bbbf2d40 1990 break;
1991
1992 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
957861f7 1993 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
1994 return array();
1995 }
c5ddc3fd 1996 if (!empty($coursecat->parent)) { // return parent value if exist
bbbf2d40 1997 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1998 return array_merge(array($parent->id), get_parent_contexts($parent));
1999 } else { // else return site value
2000 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
2001 return array($parent->id);
2002 }
2003 break;
2004
2005 case CONTEXT_COURSE: // 1 to 1 to course cat
957861f7 2006 if (!$course = get_record('course','id',$context->instanceid)) {
2007 return array();
2008 }
2009 if (!empty($course->category)) {
2010 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2011 return array_merge(array($parent->id), get_parent_contexts($parent));
2012 } else {
2013 return array();
2014 }
bbbf2d40 2015 break;
2016
2017 case CONTEXT_GROUP: // 1 to 1 to course
957861f7 2018 if (!$group = get_record('groups','id',$context->instanceid)) {
2019 return array();
2020 }
2021 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
2022 return array_merge(array($parent->id), get_parent_contexts($parent));
2023 } else {
2024 return array();
2025 }
bbbf2d40 2026 break;
2027
2028 case CONTEXT_MODULE: // 1 to 1 to course
957861f7 2029 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
2030 return array();
2031 }
2032 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
2033 return array_merge(array($parent->id), get_parent_contexts($parent));
2034 } else {
2035 return array();
2036 }
bbbf2d40 2037 break;
2038
2039 case CONTEXT_BLOCK: // 1 to 1 to course
957861f7 2040 if (!$block = get_record('block_instance','id',$context->instanceid)) {
2041 return array();
2042 }
2043 if ($parent = get_context_instance(CONTEXT_COURSE, $block->pageid)) {
2044 return array_merge(array($parent->id), get_parent_contexts($parent));
2045 } else {
2046 return array();
2047 }
bbbf2d40 2048 break;
2049
2050 default:
957861f7 2051 error('This is an unknown context!');
bbbf2d40 2052 return false;
2053 }
bbbf2d40 2054}
2055
ea8158c1 2056/** gets a string for sql calls, searching for stuff
2057 * in this context or above
2058 * @param object $context
2059 * @return string
2060 */
2061function get_related_contexts_string($context) {
2062 if ($parents = get_parent_contexts($context)) {
2063 return (' IN ('.$context->id.','.implode(',', $parents).')');
2064 } else {
2065 return (' ='.$context->id);
2066 }
2067}
bbbf2d40 2068/**
2069 * This function gets the capability of a role in a given context.
2070 * It is needed when printing override forms.
2071 * @param int $contextid
bbbf2d40 2072 * @param string $capability
2073 * @param array $capabilities - array loaded using role_context_capabilities
2074 * @return int (allow, prevent, prohibit, inherit)
2075 */
bbbf2d40 2076function get_role_context_capability($contextid, $capability, $capabilities) {
98882637 2077 return $capabilities[$contextid][$capability];
bbbf2d40 2078}
2079
2080
cee0901c 2081/**
2082 * Returns the human-readable, translated version of the capability.
2083 * Basically a big switch statement.
2084 * @param $capabilityname - e.g. mod/choice:readresponses
2085 */
ceb83c70 2086function get_capability_string($capabilityname) {
ae9e4c06 2087
cee0901c 2088 // Typical capabilityname is mod/choice:readresponses
ceb83c70 2089
2090 $names = split('/', $capabilityname);
2091 $stringname = $names[1]; // choice:readresponses
2092 $components = split(':', $stringname);
2093 $componentname = $components[0]; // choice
98882637 2094
2095 switch ($names[0]) {
2096 case 'mod':
ceb83c70 2097 $string = get_string($stringname, $componentname);
98882637 2098 break;
2099
2100 case 'block':
ceb83c70 2101 $string = get_string($stringname, 'block_'.$componentname);
98882637 2102 break;
ceb83c70 2103
98882637 2104 case 'moodle':
ceb83c70 2105 $string = get_string($stringname, 'role');
98882637 2106 break;
2107
2108 case 'enrol':
ceb83c70 2109 $string = get_string($stringname, 'enrol_'.$componentname);
2110 break;
98882637 2111
2112 default:
ceb83c70 2113 $string = get_string($stringname);
98882637 2114 break;
98882637 2115
2116 }
ceb83c70 2117 return $string;
bbbf2d40 2118}
2119
2120
cee0901c 2121/**
2122 * This gets the mod/block/course/core etc strings.
2123 * @param $component
2124 * @param $contextlevel
2125 */
bbbf2d40 2126function get_component_string($component, $contextlevel) {
2127
98882637 2128 switch ($contextlevel) {
bbbf2d40 2129
98882637 2130 case CONTEXT_SYSTEM:
be382aaf 2131 if (preg_match('|^enrol/|', $component)) {
2132 $langname = str_replace('/', '_', $component);
2133 $string = get_string('enrolname', $langname);
69eb59f2 2134 } else {
2135 $string = get_string('coresystem');
2136 }
bbbf2d40 2137 break;
2138
2139 case CONTEXT_PERSONAL:
98882637 2140 $string = get_string('personal');
bbbf2d40 2141 break;
2142
4b10f08b 2143 case CONTEXT_USER:
98882637 2144 $string = get_string('users');
bbbf2d40 2145 break;
2146
2147 case CONTEXT_COURSECAT:
98882637 2148 $string = get_string('categories');
bbbf2d40 2149 break;
2150
2151 case CONTEXT_COURSE:
98882637 2152 $string = get_string('course');
bbbf2d40 2153 break;
2154
2155 case CONTEXT_GROUP:
98882637 2156 $string = get_string('group');
bbbf2d40 2157 break;
2158
2159 case CONTEXT_MODULE:
98882637 2160 $string = get_string('modulename', basename($component));
bbbf2d40 2161 break;
2162
2163 case CONTEXT_BLOCK:
98882637 2164 $string = get_string('blockname', 'block_'.$component.'.php');
bbbf2d40 2165 break;
2166
2167 default:
2168 error ('This is an unknown context!');
2169 return false;
98882637 2170
2171 }
98882637 2172 return $string;
bbbf2d40 2173}
cee0901c 2174
945f88ca 2175/** gets the list of roles assigned to this context
2176 * @param object $context
2177 * @return array
2178 */
e4dd3222 2179function get_roles_used_in_context($context) {
2180
2181 global $CFG;
2182
2183 return get_records_sql('SELECT distinct r.id, r.name
2184 FROM '.$CFG->prefix.'role_assignments ra,
2185 '.$CFG->prefix.'role r
2186 WHERE r.id = ra.roleid
2187 AND ra.contextid = '.$context->id.'
2188 ORDER BY r.sortorder ASC');
2189}
2190
945f88ca 2191/** this function is used to print roles column in user profile page.
2192 * @param int userid
2193 * @param int contextid
2194 * @return string
2195 */
0a8a95c9 2196function get_user_roles_in_context($userid, $contextid){
2197 global $CFG;
2198
2199 $rolestring = '';
2200 $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';
2201 if ($roles = get_records_sql($SQL)) {
2202 foreach ($roles as $userrole) {
2203 $rolestring .= '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$userrole->contextid.'&amp;roleid='.$userrole->roleid.'">'.$userrole->name.'</a>, ';
2204 }
2205
2206 }
2207 return rtrim($rolestring, ', ');
2208}
68c52526 2209
2210
945f88ca 2211/**
2212 * Checks if a user can override capabilities of a particular role in this context
2213 * @param object $context
2214 * @param int targetroleid - the id of the role you want to override
2215 * @return boolean
2216 */
68c52526 2217function user_can_override($context, $targetroleid) {
2218 // first check if user has override capability
2219 // if not return false;
2220 if (!has_capability('moodle/role:override', $context)) {
2221 return false;
2222 }
2223 // pull out all active roles of this user from this context(or above)
c0614051 2224 if ($userroles = get_user_roles($context)) {
2225 foreach ($userroles as $userrole) {
2226 // if any in the role_allow_override table, then it's ok
2227 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
2228 return true;
2229 }
68c52526 2230 }
2231 }
2232
2233 return false;
2234
2235}
2236
945f88ca 2237/**
2238 * Checks if a user can assign users to a particular role in this context
2239 * @param object $context
2240 * @param int targetroleid - the id of the role you want to assign users to
2241 * @return boolean
2242 */
68c52526 2243function user_can_assign($context, $targetroleid) {
2244
2245 // first check if user has override capability
2246 // if not return false;
2247 if (!has_capability('moodle/role:assign', $context)) {
2248 return false;
2249 }
2250 // pull out all active roles of this user from this context(or above)
c0614051 2251 if ($userroles = get_user_roles($context)) {
2252 foreach ($userroles as $userrole) {
2253 // if any in the role_allow_override table, then it's ok
2254 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
2255 return true;
2256 }
68c52526 2257 }
2258 }
2259
2260 return false;
2261}
2262
945f88ca 2263/**
2264 * gets all the user roles assigned in this context, or higher contexts
2265 * this is mainly used when checking if a user can assign a role, or overriding a role
2266 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2267 * allow_override tables
2268 * @param object $context
2269 * @param int $userid
2270 * @return array
2271 */
5b630667 2272function get_user_roles($context, $userid=0, $checkparentcontexts=true) {
68c52526 2273
2274 global $USER, $CFG, $db;
c0614051 2275
2276 if (empty($userid)) {
2277 if (empty($USER->id)) {
2278 return array();
2279 }
2280 $userid = $USER->id;
2281 }
2282
5b630667 2283 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
2284 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id.')';
c0614051 2285 } else {
5b630667 2286 $contexts = ' ra.contextid = \''.$context->id.'\'';
c0614051 2287 }
2288
5b630667 2289 return get_records_sql('SELECT ra.*, r.name
2290 FROM '.$CFG->prefix.'role_assignments ra,
ec6eb110 2291 '.$CFG->prefix.'role r,
2292 '.$CFG->prefix.'context c
c0614051 2293 WHERE ra.userid = '.$userid.
5b630667 2294 ' AND ra.roleid = r.id
ec6eb110 2295 AND ra.contextid = c.id
5b630667 2296 AND '.$contexts.
ec6eb110 2297 ' ORDER BY c.aggregatelevel DESC');
68c52526 2298}
2299
945f88ca 2300/**
2301 * Creates a record in the allow_override table
2302 * @param int sroleid - source roleid
2303 * @param int troleid - target roleid
2304 * @return int - id or false
2305 */
2306function allow_override($sroleid, $troleid) {
2307 $record->roleid = $sroleid;
2308 $record->allowoverride = $troleid;
2309 return insert_record('role_allow_override', $record);
2310}
2311
2312/**
2313 * Creates a record in the allow_assign table
2314 * @param int sroleid - source roleid
2315 * @param int troleid - target roleid
2316 * @return int - id or false
2317 */
2318function allow_assign($sroleid, $troleid) {
ff64aaea 2319 $record = new object;
945f88ca 2320 $record->roleid = $sroleid;
2321 $record->allowassign = $troleid;
2322 return insert_record('role_allow_assign', $record);
2323}
2324
2325/**
ff64aaea 2326 * Gets a list of roles that this user can assign in this context
945f88ca 2327 * @param object $context
2328 * @return array
2329 */
2330function get_assignable_roles ($context) {
2331
945f88ca 2332 $options = array();
ff64aaea 2333
2334 if ($roles = get_records('role')) {
2335 foreach ($roles as $role) {
2336 if (user_can_assign($context, $role->id)) {
2337 $options[$role->id] = $role->name;
2338 }
945f88ca 2339 }
2340 }
2341 return $options;
2342}
2343
2344/**
ff64aaea 2345 * Gets a list of roles that this user can override in this context
945f88ca 2346 * @param object $context
2347 * @return array
2348 */
2349function get_overridable_roles ($context) {
2350
945f88ca 2351 $options = array();
ff64aaea 2352
2353 if ($roles = get_records('role')) {
2354 foreach ($roles as $role) {
2355 if (user_can_override($context, $role->id)) {
2356 $options[$role->id] = $role->name;
2357 }
945f88ca 2358 }
ff64aaea 2359 }
945f88ca 2360
2361 return $options;
945f88ca 2362}
1648afb2 2363
2364
2365/**
2366 * who has this capability in this context
2367 * does not handling user level resolving!!!
2368 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
2369 * @param $context - object
2370 * @param $capability - string capability
2371 * @param $fields - fields to be pulled
2372 * @param $sort - the sort order
04417640 2373 * @param $limitfrom - number of records to skip (offset)
2374 * @param $limitnum - number of records to fetch
1c45e42e 2375 * @param $groups - single group or array of groups - group(s) user is in
71dea306 2376 * @param $exceptions - list of users to exclude
1648afb2 2377 */
64026e8c 2378function get_users_by_capability($context, $capability, $fields='', $sort='',
2379 $limitfrom='', $limitnum='', $groups='', $exceptions='') {
1648afb2 2380 global $CFG;
2381
64026e8c 2382/// Sorting out groups
1c45e42e 2383 if ($groups) {
71dea306 2384 $groupjoin = 'INNER JOIN '.$CFG->prefix.'groups_members gm ON gm.userid = ra.userid';
1c45e42e 2385
2386 if (is_array($groups)) {
a05708ad 2387 $groupsql = 'AND gm.groupid IN ('.implode(',', $groups).')';
1c45e42e 2388 } else {
a05708ad 2389 $groupsql = 'AND gm.groupid = '.$groups;
1c45e42e 2390 }
2391 } else {
2392 $groupjoin = '';
2393 $groupsql = '';
2394 }
2395
64026e8c 2396/// Sorting out exceptions
5081e786 2397 $exceptionsql = $exceptions ? "AND u.id NOT IN ($exceptions)" : '';
64026e8c 2398
2399/// Set up default fields
2400 if (empty($fields)) {
5b630667 2401 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
64026e8c 2402 }
2403
2404/// Set up default sort
2405 if (empty($sort)) {
2406 $sort = 'ul.timeaccess';
2407 }
2408
2409 $sortby = $sort ? " ORDER BY $sort " : '';
71dea306 2410
64026e8c 2411/// If context is a course, then construct sql for ul
4e5a0168 2412 if ($context->aggregatelevel == CONTEXT_COURSE) {
71dea306 2413 $courseid = $context->instanceid;
f00b7f8d 2414 $coursesql = "AND (ul.courseid = $courseid OR ul.courseid IS NULL)";
5081e786 2415 } else {
2416 $coursesql = '';
71dea306 2417 }
64026e8c 2418
2419/// Sorting out roles with this capability set
ec7a8b79 2420 $possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context);
1648afb2 2421 $validroleids = array();
2422 foreach ($possibleroles as $prole) {
2423 $caps = role_context_capabilities($prole->id, $context, $capability); // resolved list
2424 if ($caps[$capability] > 0) { // resolved capability > 0
2425 $validroleids[] = $prole->id;
2426 }
71dea306 2427 }
2428 $roleids = '('.implode(',', $validroleids).')';
64026e8c 2429
2430/// Construct the main SQL
71dea306 2431 $select = " SELECT $fields";
2432 $from = " FROM {$CFG->prefix}user u
2433 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
2434 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON ul.userid = u.id
2435 $groupjoin";
2436 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
64026e8c 2437 AND u.deleted = 0
2438 AND ra.roleid in $roleids
71dea306 2439 $exceptionsql
2440 $coursesql
2441 $groupsql";
2442
2443 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
1648afb2 2444}
7700027f 2445
ab5c9044 2446/**
2447 * gets all the users assigned this role in this context or higher
2448 * @param int roleid
2449 * @param int contextid
2450 * @param bool parent if true, get list of users assigned in higher context too
2451 * @return array()
2452 */
2453function get_role_users($roleid, $context, $parent=false) {
2454 global $CFG;
2455
2456 if ($parent) {
2457 if ($contexts = get_parent_contexts($context)) {
2458 $parentcontexts = 'r.contextid IN ('.implode(',', $contexts).')';
2459 } else {
2460 $parentcontexts = '';
2461 }
2462 } else {
2463 $parentcontexts = '';
2464 }
2465
2466 $SQL = "select u.*
2467 from {$CFG->prefix}role_assignments r,
2468 {$CFG->prefix}user u
2469 where (r.contextid = $context->id $parentcontexts)
2470 and r.roleid = $roleid
2471 and u.id = r.userid"; // join now so that we can just use fullname() later
2472
2473 return get_records_sql($SQL);
2474}
2475
4e5f3064 2476?>