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