backupdata folder is no longer displayed in list of directories when setting up Direc...
[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 }
6eb4f823 1419
1420 return $success;
bbbf2d40 1421}
1422
1423
1424/**
1dc1f037 1425 * Deletes one or more role assignments. You must specify at least one parameter.
bbbf2d40 1426 * @param $roleid
1427 * @param $userid
1428 * @param $groupid
1429 * @param $contextid
1430 * @return boolean - success or failure
1431 */
1dc1f037 1432function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0) {
d74067e8 1433
1434 global $USER, $CFG;
1435
1dc1f037 1436 $args = array('roleid', 'userid', 'groupid', 'contextid');
1437 $select = array();
1438 foreach ($args as $arg) {
1439 if ($$arg) {
1440 $select[] = $arg.' = '.$$arg;
1441 }
1442 }
d74067e8 1443
1dc1f037 1444 if ($select) {
d74067e8 1445 if (delete_records_select('role_assignments', implode(' AND ', $select))) {
1446
1447 /// If the user is the current user, then reload the capabilities too.
1448 if (!empty($USER->id) && $USER->id == $userid) {
1449 load_user_capability();
1450 }
1451
0f161e1f 1452 if ($contextid) {
1453 if ($context = get_record('context', 'id', $contextid)) {
1454
1455 /// Ask all the modules if anything needs to be done for this user
1456 if ($mods = get_list_of_plugins('mod')) {
1457 foreach ($mods as $mod) {
1458 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
1459 $functionname = $mod.'_role_unassign';
1460 if (function_exists($functionname)) {
1461 $functionname($userid, $context);
1462 }
1463 }
1464 }
1465
1466 /// Remove entries from user_lastaccess for courses they can no longer access
1467 //role_add_lastaccess_entries($userid, $context);
1468 }
1469 }
d74067e8 1470
1471 return true;
1472 }
1473 return false;
1dc1f037 1474 }
d74067e8 1475 return true;
bbbf2d40 1476}
1477
0f161e1f 1478/**
1479 * Add last access times to user_lastaccess as required
1480 * @param $userid
1481 * @param $context
1482 * @return boolean - success or failure
1483 */
1484function role_add_lastaccess_entries($userid, $context) {
1485
1486 global $USER, $CFG;
1487
1488 if (empty($context->aggregatelevel)) {
1489 return false;
1490 }
1491
1492 $lastaccess = new object; // Reusable object below
1493 $lastaccess->userid = $userid;
1494 $lastaccess->timeaccess = 0;
1495
1496 switch ($context->aggregatelevel) {
1497
1498 case CONTEXT_SYSTEM: // For the whole site
1499 if ($courses = get_record('course')) {
1500 foreach ($courses as $course) {
1501 $lastaccess->courseid = $course->id;
1502 role_set_lastaccess($lastaccess);
1503 }
1504 }
1505 break;
1506
1507 case CONTEXT_CATEGORY: // For a whole category
1508 if ($courses = get_record('course', 'category', $context->instanceid)) {
1509 foreach ($courses as $course) {
1510 $lastaccess->courseid = $course->id;
1511 role_set_lastaccess($lastaccess);
1512 }
1513 }
1514 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
1515 foreach ($categories as $category) {
1516 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
1517 role_add_lastaccess_entries($userid, $subcontext);
1518 }
1519 }
1520 break;
1521
1522
1523 case CONTEXT_COURSE: // For a whole course
1524 if ($course = get_record('course', 'id', $context->instanceid)) {
1525 $lastaccess->courseid = $course->id;
1526 role_set_lastaccess($lastaccess);
1527 }
1528 break;
1529 }
1530}
1531
1532/**
1533 * Delete last access times from user_lastaccess as required
1534 * @param $userid
1535 * @param $context
1536 * @return boolean - success or failure
1537 */
1538function role_remove_lastaccess_entries($userid, $context) {
1539
1540 global $USER, $CFG;
1541
1542}
1543
bbbf2d40 1544
1545/**
1546 * Loads the capability definitions for the component (from file). If no
1547 * capabilities are defined for the component, we simply return an empty array.
1548 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1549 * @return array of capabilities
1550 */
1551function load_capability_def($component) {
1552 global $CFG;
1553
1554 if ($component == 'moodle') {
1555 $defpath = $CFG->libdir.'/db/access.php';
1556 $varprefix = 'moodle';
1557 } else {
0c4d9f49 1558 $compparts = explode('/', $component);
1559
1560 if ($compparts[0] == 'block') {
1561 // Blocks are an exception. Blocks directory is 'blocks', and not
1562 // 'block'. So we need to jump through hoops.
1563 $defpath = $CFG->dirroot.'/'.$compparts[0].
1564 's/'.$compparts[1].'/db/access.php';
1565 $varprefix = $compparts[0].'_'.$compparts[1];
1566 } else {
1567 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
1568 $varprefix = str_replace('/', '_', $component);
1569 }
bbbf2d40 1570 }
1571 $capabilities = array();
1572
1573 if (file_exists($defpath)) {
1574 require_once($defpath);
1575 $capabilities = ${$varprefix.'_capabilities'};
1576 }
1577 return $capabilities;
1578}
1579
1580
1581/**
1582 * Gets the capabilities that have been cached in the database for this
1583 * component.
1584 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1585 * @return array of capabilities
1586 */
1587function get_cached_capabilities($component='moodle') {
1588 if ($component == 'moodle') {
1589 $storedcaps = get_records_select('capabilities',
1590 "name LIKE 'moodle/%:%'");
1591 } else {
1592 $storedcaps = get_records_select('capabilities',
1593 "name LIKE '$component:%'");
1594 }
1595 return $storedcaps;
1596}
1597
1598
1599/**
1600 * Updates the capabilities table with the component capability definitions.
1601 * If no parameters are given, the function updates the core moodle
1602 * capabilities.
1603 *
1604 * Note that the absence of the db/access.php capabilities definition file
1605 * will cause any stored capabilities for the component to be removed from
1606 * the database.
1607 *
1608 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1609 * @return boolean
1610 */
1611function update_capabilities($component='moodle') {
1612
1613 $storedcaps = array();
be4486da 1614
1615 $filecaps = load_capability_def($component);
bbbf2d40 1616 $cachedcaps = get_cached_capabilities($component);
1617 if ($cachedcaps) {
1618 foreach ($cachedcaps as $cachedcap) {
1619 array_push($storedcaps, $cachedcap->name);
be4486da 1620 // update risk bitmasks in existing capabilitites if needed
1621 if (array_key_exists($cachedcap->name, $filecaps)) {
1622 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2b531945 1623 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
be4486da 1624 }
1625 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
1626 $updatecap = new object;
1627 $updatecap->id = $cachedcap->id;
1628 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
1629 if (!update_record('capabilities', $updatecap)) {
1630 return false;
1631 }
1632 }
1633 }
bbbf2d40 1634 }
1635 }
be4486da 1636
bbbf2d40 1637 // Are there new capabilities in the file definition?
1638 $newcaps = array();
1639
1640 foreach ($filecaps as $filecap => $def) {
1641 if (!$storedcaps ||
1642 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2b531945 1643 if (!array_key_exists('riskbitmask', $def)) {
1644 $def['riskbitmask'] = 0; // no risk if not specified
1645 }
bbbf2d40 1646 $newcaps[$filecap] = $def;
1647 }
1648 }
1649 // Add new capabilities to the stored definition.
1650 foreach ($newcaps as $capname => $capdef) {
1651 $capability = new object;
1652 $capability->name = $capname;
1653 $capability->captype = $capdef['captype'];
1654 $capability->contextlevel = $capdef['contextlevel'];
1655 $capability->component = $component;
be4486da 1656 $capability->riskbitmask = $capdef['riskbitmask'];
bbbf2d40 1657
1658 if (!insert_record('capabilities', $capability, false, 'id')) {
1659 return false;
1660 }
ab5c9044 1661
1662 global $db;
1663 $db->debug= 999;
bbbf2d40 1664 // Do we need to assign the new capabilities to roles that have the
1665 // legacy capabilities moodle/legacy:* as well?
1666 if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
1667 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2e85fffe 1668 notify('Could not assign legacy capabilities for '.$capname);
bbbf2d40 1669 }
1670 }
1671 // Are there any capabilities that have been removed from the file
1672 // definition that we need to delete from the stored capabilities and
1673 // role assignments?
1674 capabilities_cleanup($component, $filecaps);
1675
1676 return true;
1677}
1678
1679
1680/**
1681 * Deletes cached capabilities that are no longer needed by the component.
1682 * Also unassigns these capabilities from any roles that have them.
1683 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1684 * @param $newcapdef - array of the new capability definitions that will be
1685 * compared with the cached capabilities
1686 * @return int - number of deprecated capabilities that have been removed
1687 */
1688function capabilities_cleanup($component, $newcapdef=NULL) {
1689
1690 $removedcount = 0;
1691
1692 if ($cachedcaps = get_cached_capabilities($component)) {
1693 foreach ($cachedcaps as $cachedcap) {
1694 if (empty($newcapdef) ||
1695 array_key_exists($cachedcap->name, $newcapdef) === false) {
1696
1697 // Remove from capabilities cache.
1698 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
1699 error('Could not delete deprecated capability '.$cachedcap->name);
1700 } else {
1701 $removedcount++;
1702 }
1703 // Delete from roles.
1704 if($roles = get_roles_with_capability($cachedcap->name)) {
1705 foreach($roles as $role) {
46943f7b 1706 if (!unassign_capability($cachedcap->name, $role->id)) {
bbbf2d40 1707 error('Could not unassign deprecated capability '.
1708 $cachedcap->name.' from role '.$role->name);
1709 }
1710 }
1711 }
1712 } // End if.
1713 }
1714 }
1715 return $removedcount;
1716}
1717
1718
1719
cee0901c 1720/****************
1721 * UI FUNCTIONS *
1722 ****************/
bbbf2d40 1723
1724
1725/**
1726 * prints human readable context identifier.
1727 */
0468976c 1728function print_context_name($context) {
340ea4e8 1729
ec0810ee 1730 $name = '';
d140ad3f 1731 switch ($context->aggregatelevel) {
ec0810ee 1732
bbbf2d40 1733 case CONTEXT_SYSTEM: // by now it's a definite an inherit
ec0810ee 1734 $name = get_string('site');
340ea4e8 1735 break;
bbbf2d40 1736
1737 case CONTEXT_PERSONAL:
ec0810ee 1738 $name = get_string('personal');
340ea4e8 1739 break;
1740
4b10f08b 1741 case CONTEXT_USER:
ec0810ee 1742 if ($user = get_record('user', 'id', $context->instanceid)) {
1743 $name = get_string('user').': '.fullname($user);
1744 }
340ea4e8 1745 break;
1746
bbbf2d40 1747 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
ec0810ee 1748 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
1749 $name = get_string('category').': '.$category->name;
1750 }
340ea4e8 1751 break;
bbbf2d40 1752
1753 case CONTEXT_COURSE: // 1 to 1 to course cat
ec0810ee 1754 if ($course = get_record('course', 'id', $context->instanceid)) {
1755 $name = get_string('course').': '.$course->fullname;
1756 }
340ea4e8 1757 break;
bbbf2d40 1758
1759 case CONTEXT_GROUP: // 1 to 1 to course
ec0810ee 1760 if ($group = get_record('groups', 'id', $context->instanceid)) {
1761 $name = get_string('group').': '.$group->name;
1762 }
340ea4e8 1763 break;
bbbf2d40 1764
1765 case CONTEXT_MODULE: // 1 to 1 to course
98882637 1766 if ($cm = get_record('course_modules','id',$context->instanceid)) {
1767 if ($module = get_record('modules','id',$cm->module)) {
1768 if ($mod = get_record($module->name, 'id', $cm->instance)) {
ec0810ee 1769 $name = get_string('activitymodule').': '.$mod->name;
98882637 1770 }
ec0810ee 1771 }
1772 }
340ea4e8 1773 break;
bbbf2d40 1774
1775 case CONTEXT_BLOCK: // 1 to 1 to course
98882637 1776 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
1777 if ($block = get_record('block','id',$blockinstance->blockid)) {
91be52d7 1778 global $CFG;
1779 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
1780 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
1781 $blockname = "block_$block->name";
1782 if ($blockobject = new $blockname()) {
1783 $name = $blockobject->title.' ('.get_string('block').')';
1784 }
ec0810ee 1785 }
1786 }
340ea4e8 1787 break;
bbbf2d40 1788
1789 default:
1790 error ('This is an unknown context!');
340ea4e8 1791 return false;
1792
1793 }
340ea4e8 1794 return $name;
bbbf2d40 1795}
1796
1797
1798/**
1799 * Extracts the relevant capabilities given a contextid.
1800 * All case based, example an instance of forum context.
1801 * Will fetch all forum related capabilities, while course contexts
1802 * Will fetch all capabilities
0468976c 1803 * @param object context
bbbf2d40 1804 * @return array();
1805 *
1806 * capabilities
1807 * `name` varchar(150) NOT NULL,
1808 * `captype` varchar(50) NOT NULL,
1809 * `contextlevel` int(10) NOT NULL,
1810 * `component` varchar(100) NOT NULL,
1811 */
0468976c 1812function fetch_context_capabilities($context) {
98882637 1813
1814 global $CFG;
bbbf2d40 1815
1816 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
98882637 1817
d140ad3f 1818 switch ($context->aggregatelevel) {
bbbf2d40 1819
98882637 1820 case CONTEXT_SYSTEM: // all
1821 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1822 break;
1823
1824 case CONTEXT_PERSONAL:
0a8a95c9 1825 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
bbbf2d40 1826 break;
1827
4b10f08b 1828 case CONTEXT_USER:
1829 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_USER;
bbbf2d40 1830 break;
1831
1832 case CONTEXT_COURSECAT: // all
98882637 1833 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1834 break;
1835
1836 case CONTEXT_COURSE: // all
98882637 1837 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1838 break;
1839
1840 case CONTEXT_GROUP: // group caps
1841 break;
1842
1843 case CONTEXT_MODULE: // mod caps
98882637 1844 $cm = get_record('course_modules', 'id', $context->instanceid);
1845 $module = get_record('modules', 'id', $cm->module);
bbbf2d40 1846
98882637 1847 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
1848 and component = 'mod/$module->name'";
bbbf2d40 1849 break;
1850
1851 case CONTEXT_BLOCK: // block caps
98882637 1852 $cb = get_record('block_instance', 'id', $context->instanceid);
1853 $block = get_record('block', 'id', $cb->blockid);
bbbf2d40 1854
98882637 1855 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
1856 and component = 'block/$block->name'";
bbbf2d40 1857 break;
1858
1859 default:
1860 return false;
1861 }
1862
1863 $records = get_records_sql($SQL.' '.$sort);
69eb59f2 1864
1865 // special sorting of core system capabiltites and enrollments
1866 if ($context->aggregatelevel == CONTEXT_SYSTEM) {
1867 $first = array();
1868 foreach ($records as $key=>$record) {
1869 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
1870 $first[$key] = $record;
1871 unset($records[$key]);
1872 } else if (count($first)){
1873 break;
1874 }
1875 }
1876 if (count($first)) {
1877 $records = $first + $records; // merge the two arrays keeping the keys
1878 }
1879 }
1880 // end of special sorting
1881
bbbf2d40 1882 return $records;
1883
1884}
1885
1886
1887/**
1888 * This function pulls out all the resolved capabilities (overrides and
1889 * defaults) of a role used in capability overrieds in contexts at a given
1890 * context.
0a8a95c9 1891 * @param obj $context
bbbf2d40 1892 * @param int $roleid
1893 * @return array
1894 */
1648afb2 1895function role_context_capabilities($roleid, $context, $cap='') {
98882637 1896 global $CFG;
1897
1898 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
0468976c 1899 if ($sitecontext->id == $context->id) {
20aeb4b8 1900 $contexts = array($sitecontext->id);
1901 } else {
1902 // first of all, figure out all parental contexts
1903 $contexts = array_reverse(get_parent_contexts($context));
98882637 1904 }
98882637 1905 $contexts = '('.implode(',', $contexts).')';
1906
1648afb2 1907 if ($cap) {
e4697bf7 1908 $search = " AND rc.capability = '$cap' ";
1648afb2 1909 } else {
1910 $search = '';
1911 }
1912
98882637 1913 $SQL = "SELECT rc.* FROM {$CFG->prefix}role_capabilities rc, {$CFG->prefix}context c
1914 where rc.contextid in $contexts
1915 and rc.roleid = $roleid
1648afb2 1916 and rc.contextid = c.id $search
d140ad3f 1917 ORDER BY c.aggregatelevel DESC, rc.capability DESC";
1648afb2 1918
98882637 1919 $capabilities = array();
1920
4729012f 1921 if ($records = get_records_sql($SQL)) {
1922 // We are traversing via reverse order.
1923 foreach ($records as $record) {
1924 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
1925 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
1926 $capabilities[$record->capability] = $record->permission;
1927 }
1928 }
98882637 1929 }
1930 return $capabilities;
bbbf2d40 1931}
1932
bbbf2d40 1933/**
0468976c 1934 * Recursive function which, given a context, find all parent context ids,
bbbf2d40 1935 * and return the array in reverse order, i.e. parent first, then grand
1936 * parent, etc.
1937 * @param object $context
1938 * @return array()
1939 */
bbbf2d40 1940function get_parent_contexts($context) {
1941
d140ad3f 1942 switch ($context->aggregatelevel) {
bbbf2d40 1943
1944 case CONTEXT_SYSTEM: // no parent
957861f7 1945 return array();
bbbf2d40 1946 break;
1947
1948 case CONTEXT_PERSONAL:
957861f7 1949 if (!$parent = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
1950 return array();
1951 } else {
1952 return array($parent->id);
1953 }
bbbf2d40 1954 break;
1955
4b10f08b 1956 case CONTEXT_USER:
957861f7 1957 if (!$parent = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
1958 return array();
1959 } else {
1960 return array($parent->id);
1961 }
bbbf2d40 1962 break;
1963
1964 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
957861f7 1965 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
1966 return array();
1967 }
c5ddc3fd 1968 if (!empty($coursecat->parent)) { // return parent value if exist
bbbf2d40 1969 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1970 return array_merge(array($parent->id), get_parent_contexts($parent));
1971 } else { // else return site value
1972 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
1973 return array($parent->id);
1974 }
1975 break;
1976
1977 case CONTEXT_COURSE: // 1 to 1 to course cat
957861f7 1978 if (!$course = get_record('course','id',$context->instanceid)) {
1979 return array();
1980 }
1981 if (!empty($course->category)) {
1982 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1983 return array_merge(array($parent->id), get_parent_contexts($parent));
1984 } else {
1985 return array();
1986 }
bbbf2d40 1987 break;
1988
1989 case CONTEXT_GROUP: // 1 to 1 to course
957861f7 1990 if (!$group = get_record('groups','id',$context->instanceid)) {
1991 return array();
1992 }
1993 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
1994 return array_merge(array($parent->id), get_parent_contexts($parent));
1995 } else {
1996 return array();
1997 }
bbbf2d40 1998 break;
1999
2000 case CONTEXT_MODULE: // 1 to 1 to course
957861f7 2001 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
2002 return array();
2003 }
2004 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
2005 return array_merge(array($parent->id), get_parent_contexts($parent));
2006 } else {
2007 return array();
2008 }
bbbf2d40 2009 break;
2010
2011 case CONTEXT_BLOCK: // 1 to 1 to course
957861f7 2012 if (!$block = get_record('block_instance','id',$context->instanceid)) {
2013 return array();
2014 }
2015 if ($parent = get_context_instance(CONTEXT_COURSE, $block->pageid)) {
2016 return array_merge(array($parent->id), get_parent_contexts($parent));
2017 } else {
2018 return array();
2019 }
bbbf2d40 2020 break;
2021
2022 default:
957861f7 2023 error('This is an unknown context!');
bbbf2d40 2024 return false;
2025 }
bbbf2d40 2026}
2027
ea8158c1 2028/** gets a string for sql calls, searching for stuff
2029 * in this context or above
2030 * @param object $context
2031 * @return string
2032 */
2033function get_related_contexts_string($context) {
2034 if ($parents = get_parent_contexts($context)) {
2035 return (' IN ('.$context->id.','.implode(',', $parents).')');
2036 } else {
2037 return (' ='.$context->id);
2038 }
2039}
bbbf2d40 2040/**
2041 * This function gets the capability of a role in a given context.
2042 * It is needed when printing override forms.
2043 * @param int $contextid
bbbf2d40 2044 * @param string $capability
2045 * @param array $capabilities - array loaded using role_context_capabilities
2046 * @return int (allow, prevent, prohibit, inherit)
2047 */
bbbf2d40 2048function get_role_context_capability($contextid, $capability, $capabilities) {
98882637 2049 return $capabilities[$contextid][$capability];
bbbf2d40 2050}
2051
2052
cee0901c 2053/**
2054 * Returns the human-readable, translated version of the capability.
2055 * Basically a big switch statement.
2056 * @param $capabilityname - e.g. mod/choice:readresponses
2057 */
ceb83c70 2058function get_capability_string($capabilityname) {
ae9e4c06 2059
cee0901c 2060 // Typical capabilityname is mod/choice:readresponses
ceb83c70 2061
2062 $names = split('/', $capabilityname);
2063 $stringname = $names[1]; // choice:readresponses
2064 $components = split(':', $stringname);
2065 $componentname = $components[0]; // choice
98882637 2066
2067 switch ($names[0]) {
2068 case 'mod':
ceb83c70 2069 $string = get_string($stringname, $componentname);
98882637 2070 break;
2071
2072 case 'block':
ceb83c70 2073 $string = get_string($stringname, 'block_'.$componentname);
98882637 2074 break;
ceb83c70 2075
98882637 2076 case 'moodle':
ceb83c70 2077 $string = get_string($stringname, 'role');
98882637 2078 break;
2079
2080 case 'enrol':
ceb83c70 2081 $string = get_string($stringname, 'enrol_'.$componentname);
2082 break;
98882637 2083
2084 default:
ceb83c70 2085 $string = get_string($stringname);
98882637 2086 break;
98882637 2087
2088 }
ceb83c70 2089 return $string;
bbbf2d40 2090}
2091
2092
cee0901c 2093/**
2094 * This gets the mod/block/course/core etc strings.
2095 * @param $component
2096 * @param $contextlevel
2097 */
bbbf2d40 2098function get_component_string($component, $contextlevel) {
2099
98882637 2100 switch ($contextlevel) {
bbbf2d40 2101
98882637 2102 case CONTEXT_SYSTEM:
be382aaf 2103 if (preg_match('|^enrol/|', $component)) {
2104 $langname = str_replace('/', '_', $component);
2105 $string = get_string('enrolname', $langname);
69eb59f2 2106 } else {
2107 $string = get_string('coresystem');
2108 }
bbbf2d40 2109 break;
2110
2111 case CONTEXT_PERSONAL:
98882637 2112 $string = get_string('personal');
bbbf2d40 2113 break;
2114
4b10f08b 2115 case CONTEXT_USER:
98882637 2116 $string = get_string('users');
bbbf2d40 2117 break;
2118
2119 case CONTEXT_COURSECAT:
98882637 2120 $string = get_string('categories');
bbbf2d40 2121 break;
2122
2123 case CONTEXT_COURSE:
98882637 2124 $string = get_string('course');
bbbf2d40 2125 break;
2126
2127 case CONTEXT_GROUP:
98882637 2128 $string = get_string('group');
bbbf2d40 2129 break;
2130
2131 case CONTEXT_MODULE:
98882637 2132 $string = get_string('modulename', basename($component));
bbbf2d40 2133 break;
2134
2135 case CONTEXT_BLOCK:
98882637 2136 $string = get_string('blockname', 'block_'.$component.'.php');
bbbf2d40 2137 break;
2138
2139 default:
2140 error ('This is an unknown context!');
2141 return false;
98882637 2142
2143 }
98882637 2144 return $string;
bbbf2d40 2145}
cee0901c 2146
945f88ca 2147/** gets the list of roles assigned to this context
2148 * @param object $context
2149 * @return array
2150 */
e4dd3222 2151function get_roles_used_in_context($context) {
2152
2153 global $CFG;
2154
2155 return get_records_sql('SELECT distinct r.id, r.name
2156 FROM '.$CFG->prefix.'role_assignments ra,
2157 '.$CFG->prefix.'role r
2158 WHERE r.id = ra.roleid
2159 AND ra.contextid = '.$context->id.'
2160 ORDER BY r.sortorder ASC');
2161}
2162
945f88ca 2163/** this function is used to print roles column in user profile page.
2164 * @param int userid
2165 * @param int contextid
2166 * @return string
2167 */
0a8a95c9 2168function get_user_roles_in_context($userid, $contextid){
2169 global $CFG;
2170
2171 $rolestring = '';
2172 $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';
2173 if ($roles = get_records_sql($SQL)) {
2174 foreach ($roles as $userrole) {
2175 $rolestring .= '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$userrole->contextid.'&amp;roleid='.$userrole->roleid.'">'.$userrole->name.'</a>, ';
2176 }
2177
2178 }
2179 return rtrim($rolestring, ', ');
2180}
68c52526 2181
2182
945f88ca 2183/**
2184 * Checks if a user can override capabilities of a particular role in this context
2185 * @param object $context
2186 * @param int targetroleid - the id of the role you want to override
2187 * @return boolean
2188 */
68c52526 2189function user_can_override($context, $targetroleid) {
2190 // first check if user has override capability
2191 // if not return false;
2192 if (!has_capability('moodle/role:override', $context)) {
2193 return false;
2194 }
2195 // pull out all active roles of this user from this context(or above)
c0614051 2196 if ($userroles = get_user_roles($context)) {
2197 foreach ($userroles as $userrole) {
2198 // if any in the role_allow_override table, then it's ok
2199 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
2200 return true;
2201 }
68c52526 2202 }
2203 }
2204
2205 return false;
2206
2207}
2208
945f88ca 2209/**
2210 * Checks if a user can assign users to a particular role in this context
2211 * @param object $context
2212 * @param int targetroleid - the id of the role you want to assign users to
2213 * @return boolean
2214 */
68c52526 2215function user_can_assign($context, $targetroleid) {
2216
2217 // first check if user has override capability
2218 // if not return false;
2219 if (!has_capability('moodle/role:assign', $context)) {
2220 return false;
2221 }
2222 // pull out all active roles of this user from this context(or above)
c0614051 2223 if ($userroles = get_user_roles($context)) {
2224 foreach ($userroles as $userrole) {
2225 // if any in the role_allow_override table, then it's ok
2226 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
2227 return true;
2228 }
68c52526 2229 }
2230 }
2231
2232 return false;
2233}
2234
945f88ca 2235/**
2236 * gets all the user roles assigned in this context, or higher contexts
2237 * this is mainly used when checking if a user can assign a role, or overriding a role
2238 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2239 * allow_override tables
2240 * @param object $context
2241 * @param int $userid
2242 * @return array
2243 */
5b630667 2244function get_user_roles($context, $userid=0, $checkparentcontexts=true) {
68c52526 2245
2246 global $USER, $CFG, $db;
c0614051 2247
2248 if (empty($userid)) {
2249 if (empty($USER->id)) {
2250 return array();
2251 }
2252 $userid = $USER->id;
2253 }
2254
5b630667 2255 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
2256 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id.')';
c0614051 2257 } else {
5b630667 2258 $contexts = ' ra.contextid = \''.$context->id.'\'';
c0614051 2259 }
2260
5b630667 2261 return get_records_sql('SELECT ra.*, r.name
2262 FROM '.$CFG->prefix.'role_assignments ra,
ec6eb110 2263 '.$CFG->prefix.'role r,
2264 '.$CFG->prefix.'context c
c0614051 2265 WHERE ra.userid = '.$userid.
5b630667 2266 ' AND ra.roleid = r.id
ec6eb110 2267 AND ra.contextid = c.id
5b630667 2268 AND '.$contexts.
ec6eb110 2269 ' ORDER BY c.aggregatelevel DESC');
68c52526 2270}
2271
945f88ca 2272/**
2273 * Creates a record in the allow_override table
2274 * @param int sroleid - source roleid
2275 * @param int troleid - target roleid
2276 * @return int - id or false
2277 */
2278function allow_override($sroleid, $troleid) {
2279 $record->roleid = $sroleid;
2280 $record->allowoverride = $troleid;
2281 return insert_record('role_allow_override', $record);
2282}
2283
2284/**
2285 * Creates a record in the allow_assign table
2286 * @param int sroleid - source roleid
2287 * @param int troleid - target roleid
2288 * @return int - id or false
2289 */
2290function allow_assign($sroleid, $troleid) {
2291 $record->roleid = $sroleid;
2292 $record->allowassign = $troleid;
2293 return insert_record('role_allow_assign', $record);
2294}
2295
2296/**
2297 * gets a list of roles assignalbe in this context for this user
2298 * @param object $context
2299 * @return array
2300 */
2301function get_assignable_roles ($context) {
2302
2303 $role = get_records('role');
2304 $options = array();
2305 foreach ($role as $rolex) {
2306 if (user_can_assign($context, $rolex->id)) {
2307 $options[$rolex->id] = $rolex->name;
2308 }
2309 }
2310 return $options;
2311}
2312
2313/**
2314 * gets a list of roles that can be overriden in this context by this user
2315 * @param object $context
2316 * @return array
2317 */
2318function get_overridable_roles ($context) {
2319
2320 $role = get_records('role');
2321 $options = array();
2322 foreach ($role as $rolex) {
2323 if (user_can_override($context, $rolex->id)) {
2324 $options[$rolex->id] = $rolex->name;
2325 }
2326 }
2327
2328 return $options;
2329
2330}
1648afb2 2331
2332
2333/**
2334 * who has this capability in this context
2335 * does not handling user level resolving!!!
2336 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
2337 * @param $context - object
2338 * @param $capability - string capability
2339 * @param $fields - fields to be pulled
2340 * @param $sort - the sort order
04417640 2341 * @param $limitfrom - number of records to skip (offset)
2342 * @param $limitnum - number of records to fetch
1c45e42e 2343 * @param $groups - single group or array of groups - group(s) user is in
71dea306 2344 * @param $exceptions - list of users to exclude
1648afb2 2345 */
64026e8c 2346function get_users_by_capability($context, $capability, $fields='', $sort='',
2347 $limitfrom='', $limitnum='', $groups='', $exceptions='') {
1648afb2 2348 global $CFG;
2349
64026e8c 2350/// Sorting out groups
1c45e42e 2351 if ($groups) {
71dea306 2352 $groupjoin = 'INNER JOIN '.$CFG->prefix.'groups_members gm ON gm.userid = ra.userid';
1c45e42e 2353
2354 if (is_array($groups)) {
a05708ad 2355 $groupsql = 'AND gm.groupid IN ('.implode(',', $groups).')';
1c45e42e 2356 } else {
a05708ad 2357 $groupsql = 'AND gm.groupid = '.$groups;
1c45e42e 2358 }
2359 } else {
2360 $groupjoin = '';
2361 $groupsql = '';
2362 }
2363
64026e8c 2364/// Sorting out exceptions
5081e786 2365 $exceptionsql = $exceptions ? "AND u.id NOT IN ($exceptions)" : '';
64026e8c 2366
2367/// Set up default fields
2368 if (empty($fields)) {
5b630667 2369 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
64026e8c 2370 }
2371
2372/// Set up default sort
2373 if (empty($sort)) {
2374 $sort = 'ul.timeaccess';
2375 }
2376
2377 $sortby = $sort ? " ORDER BY $sort " : '';
71dea306 2378
64026e8c 2379/// If context is a course, then construct sql for ul
4e5a0168 2380 if ($context->aggregatelevel == CONTEXT_COURSE) {
71dea306 2381 $courseid = $context->instanceid;
f00b7f8d 2382 $coursesql = "AND (ul.courseid = $courseid OR ul.courseid IS NULL)";
5081e786 2383 } else {
2384 $coursesql = '';
71dea306 2385 }
64026e8c 2386
2387/// Sorting out roles with this capability set
ec7a8b79 2388 $possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context);
1648afb2 2389 $validroleids = array();
2390 foreach ($possibleroles as $prole) {
2391 $caps = role_context_capabilities($prole->id, $context, $capability); // resolved list
2392 if ($caps[$capability] > 0) { // resolved capability > 0
2393 $validroleids[] = $prole->id;
2394 }
71dea306 2395 }
2396 $roleids = '('.implode(',', $validroleids).')';
64026e8c 2397
2398/// Construct the main SQL
71dea306 2399 $select = " SELECT $fields";
2400 $from = " FROM {$CFG->prefix}user u
2401 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
2402 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON ul.userid = u.id
2403 $groupjoin";
2404 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
64026e8c 2405 AND u.deleted = 0
2406 AND ra.roleid in $roleids
71dea306 2407 $exceptionsql
2408 $coursesql
2409 $groupsql";
2410
2411 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
1648afb2 2412}
7700027f 2413
ab5c9044 2414/**
2415 * gets all the users assigned this role in this context or higher
2416 * @param int roleid
2417 * @param int contextid
2418 * @param bool parent if true, get list of users assigned in higher context too
2419 * @return array()
2420 */
2421function get_role_users($roleid, $context, $parent=false) {
2422 global $CFG;
2423
2424 if ($parent) {
2425 if ($contexts = get_parent_contexts($context)) {
2426 $parentcontexts = 'r.contextid IN ('.implode(',', $contexts).')';
2427 } else {
2428 $parentcontexts = '';
2429 }
2430 } else {
2431 $parentcontexts = '';
2432 }
2433
2434 $SQL = "select u.*
2435 from {$CFG->prefix}role_assignments r,
2436 {$CFG->prefix}user u
2437 where (r.contextid = $context->id $parentcontexts)
2438 and r.roleid = $roleid
2439 and u.id = r.userid"; // join now so that we can just use fullname() later
2440
2441 return get_records_sql($SQL);
2442}
2443
1dc1f037 2444?>