Bug #6245 - rewritten multilang filter
[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 */
16
17
18// permission definitions
19define('CAP_ALLOW', 1);
20define('CAP_PREVENT', -1);
21define('CAP_PROHIBIT', -1000);
22
23
24// context definitions
25define('CONTEXT_SYSTEM', 10);
26define('CONTEXT_PERSONAL', 20);
27define('CONTEXT_USERID', 30);
28define('CONTEXT_COURSECAT', 40);
29define('CONTEXT_COURSE', 50);
30define('CONTEXT_GROUP', 60);
31define('CONTEXT_MODULE', 70);
32define('CONTEXT_BLOCK', 80);
33
340ea4e8 34$context_cache = array(); // Cache of all used context objects for performance (by level and instance)
35$context_cache_id = array(); // Index to above cache by id
bbbf2d40 36
cee0901c 37
bbbf2d40 38/**
39 * This functions get all the course categories in proper order
0468976c 40 * @param int $context
bbbf2d40 41 * @param int $type
42 * @return array of contextids
43 */
0468976c 44function get_parent_cats($context, $type) {
98882637 45
46 $parents = array();
98882637 47
48 switch($type) {
49
50 case CONTEXT_COURSECAT:
51
52 $cat = get_record('course_categories','id',$context->instanceid);
53 while ($cat->parent) {
54
55 $context = get_context_instance(CONTEXT_COURSECAT, $cat->parent);
56 $parents[] = $context->id;
57 $cat = get_record('course_categories','id',$cat->parent);
58 }
59
60 break;
61
62 case CONTEXT_COURSE:
63
64 $course = get_record('course', 'id', $context->instanceid);
65 $cat = get_record('course_categories','id',$course->category);
66 $catinstance = get_context_instance(CONTEXT_COURSECAT, $course->category);
67 $parents[] = $catinstance->id;
68
69 // what to do with cat 0?
70 while ($cat->parent) {
71 $context = get_context_instance(CONTEXT_COURSECAT, $cat->parent);
72 $parents[] = $context->id;
73 $cat = get_record('course_categories','id',$cat->parent);
74 }
75 break;
76
77 default:
78 break;
79
80 }
81
82 return array_reverse($parents);
bbbf2d40 83}
84
85
cee0901c 86
87/*************************************
88 * Functions for Roles & Capabilites *
89 *************************************/
bbbf2d40 90
91
0468976c 92/**
93 * This function checks for a capability assertion being true. If it isn't
94 * then the page is terminated neatly with a standard error message
95 * @param string $capability - name of the capability
96 * @param object $context - a context object (record from context table)
97 * @param integer $userid - a userid number
98 * @param string $errorstring - an errorstring
99 */
100function require_capability($capability, $context=NULL, $userid=NULL, $errormessage="nopermissions", $stringfile='') {
101 if (!has_capability($capability, $context, $userid)) {
102 $capabilityname = get_capability_string($capability);
103 print_error($errormessage, $stringfile, '', $capabilityname);
104 }
105}
106
107
bbbf2d40 108/**
109 * This function returns whether the current user has the capability of performing a function
110 * For example, we can do has_capability('mod/forum:replypost',$cm) in forum
111 * only one of the 4 (moduleinstance, courseid, site, userid) would be set at 1 time
112 * This is a recursive funciton.
bbbf2d40 113 * @uses $USER
114 * @param string $capability - name of the capability
0468976c 115 * @param object $context - a context object (record from context table)
116 * @param integer $userid - a userid number
bbbf2d40 117 * @return bool
118 */
0468976c 119function has_capability($capability, $context=NULL, $userid=NULL) {
bbbf2d40 120
340ea4e8 121 global $USER, $CONTEXT;
bbbf2d40 122
98882637 123 if ($userid && $userid != $USER->id) { // loading other user's capability
0468976c 124 $capabilities = load_user_capability($capability, $context, $userid);
98882637 125 } else {
126 $capabilities = $USER->capabilities;
127 }
bbbf2d40 128
0468976c 129 if (empty($context)) { // Use default CONTEXT if none specified
340ea4e8 130 if (empty($CONTEXT)) {
131 return false;
132 } else {
133 $context = $CONTEXT;
134 }
0468976c 135 } else { // A context was given to us
136 if (empty($CONTEXT)) {
137 $CONTEXT = $context; // Store FIRST used context in this global as future default
138 }
340ea4e8 139 }
bbbf2d40 140
98882637 141 // Check site
142 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
143 if (isset($capabilities[$sitecontext->id]['moodle/site:doanything'])) {
144 return ($capabilities[$sitecontext->id]['moodle/site:doanything']);
145 }
146
0468976c 147 switch ($context->level) {
bbbf2d40 148
149 case CONTEXT_COURSECAT:
98882637 150 // Check parent cats.
0468976c 151 $parentcats = get_parent_cats($context, CONTEXT_COURSECAT);
98882637 152 foreach ($parentcats as $parentcat) {
153 if (isset($capabilities[$parentcat]['moodle/site:doanything'])) {
154 return ($capabilities[$parentcat]['moodle/site:doanything']);
cee0901c 155 }
98882637 156 }
bbbf2d40 157 break;
158
159 case CONTEXT_COURSE:
98882637 160 // Check parent cat.
0468976c 161 $parentcats = get_parent_cats($context, CONTEXT_COURSE);
98882637 162
163 foreach ($parentcats as $parentcat) {
164 if (isset($capabilities[$parentcat]['do_anything'])) {
165 return ($capabilities[$parentcat]['do_anything']);
166 }
167 }
bbbf2d40 168 break;
169
170 case CONTEXT_GROUP:
98882637 171 // Find course.
172 $group = get_record('groups','id',$context->instanceid);
bbbf2d40 173 $courseinstance = get_context_instance(CONTEXT_COURSE, $group->courseid);
98882637 174
175 $parentcats = get_parent_cats($courseinstance->id, CONTEXT_COURSE);
176 foreach ($parentcats as $parentcat) {
177 if (isset($capabilities[$parentcat->id]['do_anything'])) {
178 return ($capabilities[$parentcat->id]['do_anything']);
179 }
180 }
181
182 $coursecontext = '';
183 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
184 return ($capabilities[$courseinstance->id]['do_anything']);
185 }
186
bbbf2d40 187 break;
188
189 case CONTEXT_MODULE:
190 // Find course.
191 $cm = get_record('course_modules', 'id', $context->instanceid);
98882637 192 $courseinstance = get_context_instance(CONTEXT_COURSE, $cm->course);
bbbf2d40 193
98882637 194 if ($parentcats = get_parent_cats($courseinstance->id, CONTEXT_COURSE)) {
195 foreach ($parentcats as $parentcat) {
196 if (isset($capabilities[$parentcat]['do_anything'])) {
197 return ($capabilities[$parentcat]['do_anything']);
cee0901c 198 }
98882637 199 }
200 }
201
202 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
203 return ($capabilities[$courseinstance->id]['do_anything']);
cee0901c 204 }
bbbf2d40 205
206 break;
207
208 case CONTEXT_BLOCK:
209 // 1 to 1 to course.
210 // Find course.
211 $block = get_record('block_instance','id',$context->instanceid);
212 $courseinstance = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
98882637 213
214 $parentcats = get_parent_cats($courseinstance->id, CONTEXT_COURSE);
215 foreach ($parentcats as $parentcat) {
216 if (isset($capabilities[$parentcat]['do_anything'])) {
217 return ($capabilities[$parentcat]['do_anything']);
cee0901c 218 }
219 }
98882637 220
221 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
222 return ($capabilities[$courseinstance->id]['do_anything']);
cee0901c 223 }
bbbf2d40 224 break;
225
226 default:
227 // CONTEXT_SYSTEM: CONTEXT_PERSONAL: CONTEXT_USERID:
228 // Do nothing.
229 break;
98882637 230 }
bbbf2d40 231
98882637 232 // Last: check self.
0468976c 233 if (isset($capabilities[$context->id]['do_anything'])) {
234 return ($capabilities[$context->id]['do_anything']);
98882637 235 }
236
237 // do_anything has not been set, we now look for it the normal way.
0468976c 238 return capability_search($capability, $context, $capabilities);
bbbf2d40 239
240}
241
242
243/**
244 * In a separate function so that we won't have to deal with do_anything.
245 * again. Used by function has_capability.
246 * @param $capability - capability string
0468976c 247 * @param $context - the context object
bbbf2d40 248 * @param $capabilities - either $USER->capability or loaded array
249 * @return permission (int)
250 */
0468976c 251function capability_search($capability, $context, $capabilities) {
bbbf2d40 252 global $USER, $CFG;
0468976c 253
bbbf2d40 254 if ($CFG->debug) {
0468976c 255 notify("Looking for $capability in context $context->id", 'notifytiny');
bbbf2d40 256 }
257
0468976c 258 if (isset($capabilities[$context->id][$capability])) {
259 return ($capabilities[$context->id][$capability]);
bbbf2d40 260 }
261
262 /* Then, we check the cache recursively */
98882637 263 $permission = 0;
264
0468976c 265 switch ($context->level) {
bbbf2d40 266
267 case CONTEXT_SYSTEM: // by now it's a definite an inherit
268 $permission = 0;
269 break;
270
271 case CONTEXT_PERSONAL:
0468976c 272 $parentcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
273 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 274 break;
275
276 case CONTEXT_USERID:
0468976c 277 $parentcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
278 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 279 break;
280
281 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
282 $coursecat = get_record('course_categories','id',$context->instanceid);
0468976c 283 if (!empty($coursecat->parent)) { // return parent value if it exists
284 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
bbbf2d40 285 } else { // else return site value
0468976c 286 $parentcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
bbbf2d40 287 }
0468976c 288 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 289 break;
290
291 case CONTEXT_COURSE: // 1 to 1 to course cat
292 // find the course cat, and return its value
293 $course = get_record('course','id',$context->instanceid);
0468976c 294 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $course->category);
295 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 296 break;
297
298 case CONTEXT_GROUP: // 1 to 1 to course
299 $group = get_record('groups','id',$context->instanceid);
0468976c 300 $parentcontext = get_context_instance(CONTEXT_COURSE, $group->courseid);
301 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 302 break;
303
304 case CONTEXT_MODULE: // 1 to 1 to course
305 $cm = get_record('course_modules','id',$context->instanceid);
0468976c 306 $parentcontext = get_context_instance(CONTEXT_COURSE, $cm->course);
307 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 308 break;
309
310 case CONTEXT_BLOCK: // 1 to 1 to course
311 $block = get_record('block_instance','id',$context->instanceid);
0468976c 312 $parentcontext = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
313 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 314 break;
315
316 default:
317 error ('This is an unknown context!');
318 return false;
319 }
320
98882637 321 return $permission;
bbbf2d40 322}
323
324
325/**
326 * This function should be called immediately after a login, when $USER is set.
327 * It will build an array of all the capabilities at each level
328 * i.e. site/metacourse/course_category/course/moduleinstance
329 * Note we should only load capabilities if they are explicitly assigned already,
330 * we should not load all module's capability!
331 * @param $userid - the id of the user whose capabilities we want to load
332 * @return array
333 * possible just s simple 2D array with [contextid][capabilityname]
334 * [Capabilities] => [26][forum_post] = 1
335 * [26][forum_start] = -8990
336 * [26][forum_edit] = -1
337 * [273][blah blah] = 1
338 * [273][blah blah blah] = 2
339 */
0468976c 340function load_user_capability($capability='', $context ='', $userid='') {
bbbf2d40 341
98882637 342 global $USER, $CFG;
bbbf2d40 343
344 if (empty($userid)) {
345 $userid = $USER->id;
346 } else {
98882637 347 $otheruserid = $userid;
bbbf2d40 348 }
349
350 if ($capability) {
98882637 351 $capsearch = ' AND rc.capability = '.$capability.' ';
bbbf2d40 352 } else {
98882637 353 $capsearch ='';
bbbf2d40 354 }
355 // First we generate a list of all relevant contexts of the user
356
0468976c 357 if ($context) { // if context is specified
358 $usercontexts = get_parent_contexts($context);
98882637 359 $listofcontexts = '('.implode(',', $usercontexts).')';
360 } else { // else, we load everything
0468976c 361 $userroles = get_records('role_assignments','userid',$userid);
362 $usercontexts = array();
363 foreach ($userroles as $userrole) {
364 $usercontexts[] = $userrole->contextid;
98882637 365 }
0468976c 366 $listofcontexts = '('.implode(',', $usercontexts).')';
bbbf2d40 367 }
0468976c 368
bbbf2d40 369 // Then we use 1 giant SQL to bring out all relevant capabilities.
370 // The first part gets the capabilities of orginal role.
371 // The second part gets the capabilities of overriden roles.
372
98882637 373 $siteinstance = get_context_instance(CONTEXT_SYSTEM, SITEID);
bbbf2d40 374
41811960 375 $SQL = " SELECT rc.capability, c1.id, (c1.level * 100) AS aggregatelevel,
bbbf2d40 376 SUM(rc.permission) AS sum
377 FROM
171948fd 378 {$CFG->prefix}role_assignments AS ra,
379 {$CFG->prefix}role_capabilities AS rc,
380 {$CFG->prefix}context AS c1
bbbf2d40 381 WHERE
171948fd 382 ra.contextid=c1.id AND
383 ra.roleid=rc.roleid AND
bbbf2d40 384 ra.userid=$userid AND
385 c1.id IN $listofcontexts AND
386 rc.contextid=$siteinstance->id
98882637 387 $capsearch
bbbf2d40 388 GROUP BY
41811960 389 rc.capability,aggregatelevel,c1.id
bbbf2d40 390 HAVING
41811960 391 SUM(rc.permission) != 0
bbbf2d40 392 UNION
393
41811960 394 SELECT rc.capability, c1.id, (c1.level * 100 + c2.level) AS aggregatelevel,
bbbf2d40 395 SUM(rc.permission) AS sum
396 FROM
171948fd 397 {$CFG->prefix}role_assignments AS ra,
398 {$CFG->prefix}role_capabilities AS rc,
399 {$CFG->prefix}context AS c1,
400 {$CFG->prefix}context AS c2
bbbf2d40 401 WHERE
171948fd 402 ra.contextid=c1.id AND
403 ra.roleid=rc.roleid AND
404 ra.userid=$userid AND
405 rc.contextid=c2.id AND
bbbf2d40 406 c1.id IN $listofcontexts AND
407 c2.id IN $listofcontexts AND rc.contextid != $siteinstance->id
408 $capsearch
409
410 GROUP BY
41811960 411 rc.capability, aggregatelevel, c1.id
bbbf2d40 412 HAVING
41811960 413 SUM(rc.permission) != 0
bbbf2d40 414 ORDER BY
41811960 415 aggregatelevel ASC
bbbf2d40 416 ";
417
bbbf2d40 418
98882637 419 $capabilities = array(); // Reinitialize.
420 $rs = get_recordset_sql($SQL);
421
bbbf2d40 422 if ($rs && $rs->RecordCount() > 0) {
423 while (!$rs->EOF) {
98882637 424 $array = $rs->fields;
425 $temprecord = new object;
426
427 foreach ($array as $key=>$val) {
428 $temprecord->{$key} = $val;
429 }
bbbf2d40 430 $capabilities[] = $temprecord;
431 $rs->MoveNext();
432 }
433 }
434
435 /* so up to this point we should have somethign like this
41811960 436 * $capabilities[1] ->aggregatelevel = 1000
bbbf2d40 437 ->module = SITEID
438 ->capability = do_anything
439 ->id = 1 (id is the context id)
440 ->sum = 0
441
41811960 442 * $capabilities[2] ->aggregatelevel = 1000
bbbf2d40 443 ->module = SITEID
444 ->capability = post_messages
445 ->id = 1
446 ->sum = -9000
447
41811960 448 * $capabilittes[3] ->aggregatelevel = 3000
bbbf2d40 449 ->module = course
450 ->capability = view_course_activities
451 ->id = 25
452 ->sum = 1
453
41811960 454 * $capabilittes[4] ->aggregatelevel = 3000
bbbf2d40 455 ->module = course
456 ->capability = view_course_activities
457 ->id = 26
458 ->sum = 0 (this is another course)
459
41811960 460 * $capabilities[5] ->aggregatelevel = 3050
bbbf2d40 461 ->module = course
462 ->capability = view_course_activities
463 ->id = 25 (override in course 25)
464 ->sum = -1
465 * ....
466 * now we proceed to write the session array, going from top to bottom
467 * at anypoint, we need to go up and check parent to look for prohibit
468 */
469 // print_object($capabilities);
470
471 /* This is where we write to the actualy capabilities array
472 * what we need to do from here on is
473 * going down the array from lowest level to highest level
474 * 1) recursively check for prohibit,
475 * if any, we write prohibit
476 * else, we write the value
477 * 2) at an override level, we overwrite current level
478 * if it's not set to prohibit already, and if different
479 * ........ that should be it ........
480 */
98882637 481 $usercap = array(); // for other user's capabilities
bbbf2d40 482 foreach ($capabilities as $capability) {
483
0468976c 484 $context = get_context_instance_by_id($capability->id);
485
41811960 486 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
98882637 487
0468976c 488 if (capability_prohibits($capability->capability, $context, $capability->sum, $usercap)) {
98882637 489 $usercap[$capability->id][$capability->capability] = -9000;
490 continue;
491 }
492
493 $usercap[$capability->id][$capability->capability] = $capability->sum;
494
495 } else {
496
0468976c 497 if (capability_prohibits($capability->capability, $context, $capability->sum)) { // if any parent or parent's parent is set to prohibit
98882637 498 $USER->capabilities[$capability->id][$capability->capability] = -9000;
499 continue;
500 }
501
502 // if no parental prohibit set
503 // just write to session, i am not sure this is correct yet
504 // since 3050 shows up after 3000, and 3070 shows up after 3050,
505 // it should be ok just to overwrite like this, provided that there's no
506 // parental prohibits
507 // no point writing 0, since 0 = inherit
508 // we need to write even if it's 0, because it could be an inherit override
509 $USER->capabilities[$capability->id][$capability->capability] = $capability->sum;
510 }
bbbf2d40 511 }
512
513 // now we don't care about the huge array anymore, we can dispose it.
514 unset($capabilities);
515
41811960 516 if (!empty($otheruseid)) {
98882637 517 return $usercap; // return the array
bbbf2d40 518 }
519 // see array in session to see what it looks like
520
521}
522
523
524/**
525 * This is a recursive function that checks whether the capability in this
526 * context, or the parent capabilities are set to prohibit.
527 *
528 * At this point, we can probably just use the values already set in the
529 * session variable, since we are going down the level. Any prohit set in
530 * parents would already reflect in the session.
531 *
532 * @param $capability - capability name
533 * @param $sum - sum of all capabilities values
0468976c 534 * @param $context - the context object
bbbf2d40 535 * @param $array - when loading another user caps, their caps are not stored in session but an array
536 */
0468976c 537function capability_prohibits($capability, $context, $sum='', $array='') {
bbbf2d40 538 global $USER;
0468976c 539
bbbf2d40 540 if ($sum < -8000) {
541 // If this capability is set to prohibit.
542 return true;
543 }
544
545 if (isset($array)) {
0468976c 546 if (isset($array[$context->id][$capability])
547 && $array[$context->id][$capability] < -8000) {
98882637 548 return true;
549 }
bbbf2d40 550 } else {
98882637 551 // Else if set in session.
0468976c 552 if (isset($USER->capabilities[$context->id][$capability])
553 && $USER->capabilities[$context->id][$capability] < -8000) {
98882637 554 return true;
555 }
bbbf2d40 556 }
0468976c 557 switch ($context->level) {
bbbf2d40 558
559 case CONTEXT_SYSTEM:
560 // By now it's a definite an inherit.
561 return 0;
562 break;
563
564 case CONTEXT_PERSONAL:
565 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
0468976c 566 return capability_prohibits($capability, $parent);
bbbf2d40 567 break;
568
569 case CONTEXT_USERID:
570 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
0468976c 571 return capability_prohibits($capability, $parent);
bbbf2d40 572 break;
573
574 case CONTEXT_COURSECAT:
575 // Coursecat -> coursecat or site.
576 $coursecat = get_record('course_categories','id',$context->instanceid);
41811960 577 if (!empty($coursecat->parent)) {
bbbf2d40 578 // return parent value if exist.
579 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
580 } else {
581 // Return site value.
582 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
583 }
0468976c 584 return capability_prohibits($capability, $parent);
bbbf2d40 585 break;
586
587 case CONTEXT_COURSE:
588 // 1 to 1 to course cat.
589 // Find the course cat, and return its value.
590 $course = get_record('course','id',$context->instanceid);
591 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
0468976c 592 return capability_prohibits($capability, $parent);
bbbf2d40 593 break;
594
595 case CONTEXT_GROUP:
596 // 1 to 1 to course.
597 $group = get_record('groups','id',$context->instanceid);
598 $parent = get_context_instance(CONTEXT_COURSE, $group->courseid);
0468976c 599 return capability_prohibits($capability, $parent);
bbbf2d40 600 break;
601
602 case CONTEXT_MODULE:
603 // 1 to 1 to course.
604 $cm = get_record('course_modules','id',$context->instanceid);
605 $parent = get_context_instance(CONTEXT_COURSE, $cm->course);
0468976c 606 return capability_prohibits($capability, $parent);
bbbf2d40 607 break;
608
609 case CONTEXT_BLOCK:
610 // 1 to 1 to course.
611 $block = get_record('block_instance','id',$context->instanceid);
612 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
0468976c 613 return capability_prohibits($capability, $parent);
bbbf2d40 614 break;
615
616 default:
617 error ('This is an unknown context!');
618 return false;
619 }
620}
621
622
623/**
624 * A print form function. This should either grab all the capabilities from
625 * files or a central table for that particular module instance, then present
626 * them in check boxes. Only relevant capabilities should print for known
627 * context.
628 * @param $mod - module id of the mod
629 */
630function print_capabilities($modid=0) {
631 global $CFG;
632
633 $capabilities = array();
634
635 if ($modid) {
636 // We are in a module specific context.
637
638 // Get the mod's name.
639 // Call the function that grabs the file and parse.
640 $cm = get_record('course_modules', 'id', $modid);
641 $module = get_record('modules', 'id', $cm->module);
642
643 } else {
644 // Print all capabilities.
645 foreach ($capabilities as $capability) {
646 // Prints the check box component.
647 }
648 }
649}
650
651
652/**
1afecc03 653 * Installs the roles system.
654 * This function runs on a fresh install as well as on an upgrade from the old
655 * hard-coded student/teacher/admin etc. roles to the new roles system.
bbbf2d40 656 */
1afecc03 657function moodle_install_roles() {
bbbf2d40 658
1afecc03 659 global $CFG, $db;
660
bbbf2d40 661 // Create a system wide context for assignemnt.
662 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
663
1afecc03 664
665 // Create default/legacy roles and capabilities.
666 // (1 legacy capability per legacy role at system level).
bbbf2d40 667 $adminrole = create_role(get_string('administrator'), get_string('administratordescription'), 'moodle/legacy:admin');
98882637 668 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
bbbf2d40 669 error('Could not assign moodle/site:doanything to the admin role');
670 }
671 $coursecreatorrole = create_role(get_string('coursecreators'), get_string('coursecreatorsdescription'), 'moodle/legacy:coursecreator');
98882637 672 $noneditteacherrole = create_role(get_string('noneditingteacher'), get_string('noneditingteacherdescription'), 'moodle/legacy:teacher');
673 $editteacherrole = create_role(get_string('defaultcourseteacher'), get_string('defaultcourseteacherdescription'), 'moodle/legacy:editingteacher');
674 $studentrole = create_role(get_string('defaultcoursestudent'), get_string('defaultcoursestudentdescription'), 'moodle/legacy:student');
bbbf2d40 675 $guestrole = create_role(get_string('guest'), get_string('guestdescription'), 'moodle/legacy:guest');
1afecc03 676
677
678 // Look inside user_admin, user_creator, user_teachers, user_students and
679 // assign above new roles. If a user has both teacher and student role,
680 // only teacher role is assigned. The assignment should be system level.
681 $dbtables = $db->MetaTables('TABLES');
bbbf2d40 682
1afecc03 683
98882637 684 /**
bbbf2d40 685 * Upgrade the admins.
1afecc03 686 * Sort using id ASC, first one is primary admin.
bbbf2d40 687 */
1afecc03 688 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
689 if ($useradmins = get_records_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
690 foreach ($useradmins as $admin) {
691 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
692 }
693 }
694 } else {
695 // This is a fresh install.
bbbf2d40 696 }
1afecc03 697
698
bbbf2d40 699 /**
700 * Upgrade course creators.
701 */
1afecc03 702 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
703 if ($usercoursecreators = get_records('user_coursecreators')) {
704 foreach ($usercoursecreators as $coursecreator) {
705 role_assign($$coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
706 }
707 }
bbbf2d40 708 }
709
1afecc03 710
bbbf2d40 711 /**
712 * Upgrade editting teachers and non-editting teachers.
713 */
1afecc03 714 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
715 if ($userteachers = get_records('user_teachers')) {
716 foreach ($userteachers as $teacher) {
717 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
718 if ($teacher->editall) { // editting teacher
719 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id);
720 } else {
721 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id);
722 }
723 }
bbbf2d40 724 }
725 }
1afecc03 726
727
bbbf2d40 728 /**
729 * Upgrade students.
730 */
1afecc03 731 if (in_array($CFG->prefix.'user_students', $dbtables)) {
732 if ($userstudents = get_records('user_students')) {
733 foreach ($userstudents as $student) {
734 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
735 role_assign($studentrole, $student->userid, 0, $coursecontext->id);
736 }
737 }
bbbf2d40 738 }
1afecc03 739
740
bbbf2d40 741 /**
742 * Upgrade guest (only 1 entry).
743 */
1afecc03 744 if ($guestuser = get_record('user', 'username', 'guest')) {
745 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
746 }
747
748
749 // Should we delete the tables after we are done? Not yet.
bbbf2d40 750}
751
752
753/**
754 * Assign the defaults found in this capabality definition to roles that have
755 * the corresponding legacy capabilities assigned to them.
756 * @param $legacyperms - an array in the format (example):
757 * 'guest' => CAP_PREVENT,
758 * 'student' => CAP_ALLOW,
759 * 'teacher' => CAP_ALLOW,
760 * 'editingteacher' => CAP_ALLOW,
761 * 'coursecreator' => CAP_ALLOW,
762 * 'admin' => CAP_ALLOW
763 * @return boolean - success or failure.
764 */
765function assign_legacy_capabilities($capability, $legacyperms) {
766
767 foreach ($legacyperms as $type => $perm) {
768
769 $systemcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
770
771 // The legacy capabilities are:
772 // 'moodle/legacy:guest'
773 // 'moodle/legacy:student'
774 // 'moodle/legacy:teacher'
775 // 'moodle/legacy:editingteacher'
776 // 'moodle/legacy:coursecreator'
777 // 'moodle/legacy:admin'
778
779 if (!$roles = get_roles_with_capability('moodle/legacy:'.$type, CAP_ALLOW)) {
780 return false;
781 }
782
783 foreach ($roles as $role) {
784 // Assign a site level capability.
785 if(!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
786 return false;
787 }
788 }
789 }
790 return true;
791}
792
793
cee0901c 794/**
795 * Checks to see if a capability is a legacy capability.
796 * @param $capabilityname
797 * @return boolean
798 */
bbbf2d40 799function islegacy($capabilityname) {
98882637 800 if (strstr($capabilityname, 'legacy') === false) {
801 return false;
802 } else {
803 return true;
804 }
bbbf2d40 805}
806
cee0901c 807
808
809/**********************************
bbbf2d40 810 * Context Manipulation functions *
811 **********************************/
812
bbbf2d40 813/**
814 * This should be called prolly everytime a user, group, module, course,
815 * coursecat or site is set up maybe?
816 * @param $level
817 * @param $instanceid
818 */
819function create_context($level, $instanceid) {
820 if (!get_record('context','level',$level,'instanceid',$instanceid)) {
821 $context = new object;
822 $context->level = $level;
823 $context->instanceid = $instanceid;
824 return insert_record('context',$context);
825 }
826}
827
828
829/**
830 * Get the context instance as an object. This function will create the
831 * context instance if it does not exist yet.
832 * @param $level
833 * @param $instance
834 */
340ea4e8 835function get_context_instance($level=NULL, $instance=SITEID) {
bbbf2d40 836
0468976c 837 global $CONTEXT, $context_cache, $context_cache_id;
e5605780 838
340ea4e8 839/// If no level is supplied then return the current global context if there is one
840 if (empty($level)) {
841 if (empty($CONTEXT)) {
842 if ($CFG->debug > 7) {
843 notify("Error: get_context_instance() called without a context");
844 }
845 } else {
846 return $CONTEXT;
847 }
e5605780 848 }
849
340ea4e8 850/// Check the cache
851 if (isset($context_cache[$level][$instance])) { // Already cached
852 return $context_cache[$level][$instance];
e5605780 853 }
854
340ea4e8 855/// Get it from the database, or create it
e5605780 856 if (!$context = get_record('context', 'level', $level, 'instanceid', $instance)) {
98882637 857 create_context($level, $instance);
858 $context = get_record('context', 'level', $level, 'instanceid', $instance);
e5605780 859 }
860
340ea4e8 861/// Update the cache
862 $context_cache[$level][$instance] = $context; // Cache it for later
863 $context_cache_id[$context->id] = $context; // Cache it for later
e5605780 864
0468976c 865
bbbf2d40 866 return $context;
867}
868
cee0901c 869
340ea4e8 870/**
871 * Get a context instance as an object, from a given id.
872 * @param $id
873 */
874function get_context_instance_by_id($id) {
875
876 if (isset($context_cache_id[$id])) { // Already cached
877 return $context_cache[$id];
878 }
879
880 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
65f4d137 881 $context_cache[$context->level][$context->instanceid] = $context;
340ea4e8 882 $context_cache_id[$context->id] = $context;
883 return $context;
884 }
885
886 return false;
887}
888
bbbf2d40 889
8737be58 890/**
891 * Get the local override (if any) for a given capability in a role in a context
892 * @param $roleid
0468976c 893 * @param $contextid
894 * @param $capability
8737be58 895 */
896function get_local_override($roleid, $contextid, $capability) {
897 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
898}
899
900
bbbf2d40 901
902/************************************
903 * DB TABLE RELATED FUNCTIONS *
904 ************************************/
905
cee0901c 906/**
bbbf2d40 907 * function that creates a role
908 * @param name - role name
909 * @param description - role description
910 * @param legacy - optional legacy capability
911 * @return id or false
912 */
913function create_role($name, $description, $legacy='') {
98882637 914
915 // check for duplicate role name
916
917 if ($role = get_record('role','name', $name)) {
98882637 918 error('there is already a role with this name!');
919 }
920
921 $role->name = $name;
922 $role->description = $description;
923
924 if ($id = insert_record('role', $role)) {
1afecc03 925 if ($legacy) {
926 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
927 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
98882637 928 }
929 return $id;
930 } else {
931 return false;
932 }
bbbf2d40 933
934}
935
cee0901c 936
bbbf2d40 937/**
938 * Function to write context specific overrides, or default capabilities.
939 * @param module - string name
940 * @param capability - string name
941 * @param contextid - context id
942 * @param roleid - role id
943 * @param permission - int 1,-1 or -1000
944 */
945function assign_capability($capability, $permission, $roleid, $contextid) {
98882637 946
947 global $USER;
948
949 if (empty($permission) || $permission == 0) { // if permission is not set
950 unassign_capability($capability, $roleid, $contextid);
951 }
bbbf2d40 952
953 $cap = new object;
954 $cap->contextid = $contextid;
955 $cap->roleid = $roleid;
956 $cap->capability = $capability;
957 $cap->permission = $permission;
958 $cap->timemodified = time();
1afecc03 959 if ($USER->id) {
960 $cap->modifierid = $USER->id;
961 } else {
962 $cap->modifierid = -1; // Happens during fresh install or Moodle.
963 }
bbbf2d40 964
965 return insert_record('role_capabilities', $cap);
966}
967
968
969/**
970 * Unassign a capability from a role.
971 * @param $roleid - the role id
972 * @param $capability - the name of the capability
973 * @return boolean - success or failure
974 */
975function unassign_capability($capability, $roleid, $contextid=NULL) {
98882637 976
977 if (isset($contextid)) {
978 $status = delete_records('role_capabilities', 'capability', $capability,
979 'roleid', $roleid, 'contextid', $contextid);
980 } else {
981 $status = delete_records('role_capabilities', 'capability', $capability,
982 'roleid', $roleid);
983 }
984 return $status;
bbbf2d40 985}
986
987
988/**
989 * Get the roles that have a given capability.
990 * @param $capability - capability name (string)
991 * @param $permission - optional, the permission defined for this capability
992 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
993 * @return array or role objects
994 */
995function get_roles_with_capability($capability, $permission=NULL) {
996
997 global $CFG;
998
999 $selectroles = "SELECT r.*
1000 FROM {$CFG->prefix}role AS r,
1001 {$CFG->prefix}role_capabilities AS rc
1002 WHERE rc.capability = '$capability'
1003 AND rc.roleid = r.id";
1004
1005 if (isset($permission)) {
1006 $selectroles .= " AND rc.permission = '$permission'";
1007 }
1008 return get_records_sql($selectroles);
1009}
1010
1011
1012/**
1013 * This function makes a role-assignment (user to a role)
1014 * @param $roleid - the role of the id
1015 * @param $userid - userid
1016 * @param $groupid - group id
1017 * @param $contextid - id of the context
1018 * @param $timestart - time this assignment becomes effective
1019 * @param $timeend - time this assignemnt ceases to be effective
1020 * @uses $USER
1021 * @return id - new id of the assigment
1022 */
1023function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0) {
aa311411 1024 global $USER, $CFG;
bbbf2d40 1025
aa311411 1026 if ($CFG->debug) {
98882637 1027 notify("Assign roleid $roleid userid $userid contextid $contextid", 'notifytiny');
aa311411 1028 }
bbbf2d40 1029
1030 if (empty($roleid)) {
1031 error ('you need to select a role');
1032 }
1033
1034 if (empty($userid) && empty($groupid)) {
1035 error ('you need to assign this role to a user or a group');
1036 }
1037
1038 if (empty($contextid)) {
1039 error ('you need to assign this role to a context, e.g. a course, or an activity');
1040 }
1041
1042 $ra = new object;
1043 $ra->roleid = $roleid;
1044 $ra->contextid = $contextid;
1045 $ra->userid = $userid;
1046 $ra->hidden = $hidden;
1047 $ra->groupid = $groupid;
1048 $ra->timestart = $timestart;
1049 $ra->timeend = $timeend;
1050 $ra->timemodified = time();
1051 $ra->modifier = $USER->id;
1052
1053 return insert_record('role_assignments', $ra);
1054
1055}
1056
1057
1058/**
1059 * Deletes a role assignment.
1060 * @param $roleid
1061 * @param $userid
1062 * @param $groupid
1063 * @param $contextid
1064 * @return boolean - success or failure
1065 */
1066function role_unassign($roleid, $userid, $groupid, $contextid) {
98882637 1067 if ($groupid) {
1068 // do nothing yet as this is not implemented
1069 }
1070 else {
1071 return delete_records('role_assignments', 'userid', $userid,
1072 'roleid', $roleid, 'contextid', $contextid);
1073 }
bbbf2d40 1074}
1075
1076
1077/**
1078 * Loads the capability definitions for the component (from file). If no
1079 * capabilities are defined for the component, we simply return an empty array.
1080 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1081 * @return array of capabilities
1082 */
1083function load_capability_def($component) {
1084 global $CFG;
1085
1086 if ($component == 'moodle') {
1087 $defpath = $CFG->libdir.'/db/access.php';
1088 $varprefix = 'moodle';
1089 } else {
1090 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
1091 $varprefix = str_replace('/', '_', $component);
1092 }
1093 $capabilities = array();
1094
1095 if (file_exists($defpath)) {
1096 require_once($defpath);
1097 $capabilities = ${$varprefix.'_capabilities'};
1098 }
1099 return $capabilities;
1100}
1101
1102
1103/**
1104 * Gets the capabilities that have been cached in the database for this
1105 * component.
1106 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1107 * @return array of capabilities
1108 */
1109function get_cached_capabilities($component='moodle') {
1110 if ($component == 'moodle') {
1111 $storedcaps = get_records_select('capabilities',
1112 "name LIKE 'moodle/%:%'");
1113 } else {
1114 $storedcaps = get_records_select('capabilities',
1115 "name LIKE '$component:%'");
1116 }
1117 return $storedcaps;
1118}
1119
1120
1121/**
1122 * Updates the capabilities table with the component capability definitions.
1123 * If no parameters are given, the function updates the core moodle
1124 * capabilities.
1125 *
1126 * Note that the absence of the db/access.php capabilities definition file
1127 * will cause any stored capabilities for the component to be removed from
1128 * the database.
1129 *
1130 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1131 * @return boolean
1132 */
1133function update_capabilities($component='moodle') {
1134
1135 $storedcaps = array();
1136 $filecaps = array();
1137
1138 $cachedcaps = get_cached_capabilities($component);
1139 if ($cachedcaps) {
1140 foreach ($cachedcaps as $cachedcap) {
1141 array_push($storedcaps, $cachedcap->name);
1142 }
1143 }
1144
1145 $filecaps = load_capability_def($component);
1146
1147 // Are there new capabilities in the file definition?
1148 $newcaps = array();
1149
1150 foreach ($filecaps as $filecap => $def) {
1151 if (!$storedcaps ||
1152 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
1153 $newcaps[$filecap] = $def;
1154 }
1155 }
1156 // Add new capabilities to the stored definition.
1157 foreach ($newcaps as $capname => $capdef) {
1158 $capability = new object;
1159 $capability->name = $capname;
1160 $capability->captype = $capdef['captype'];
1161 $capability->contextlevel = $capdef['contextlevel'];
1162 $capability->component = $component;
1163
1164 if (!insert_record('capabilities', $capability, false, 'id')) {
1165 return false;
1166 }
1167 // Do we need to assign the new capabilities to roles that have the
1168 // legacy capabilities moodle/legacy:* as well?
1169 if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
1170 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
1171 error('Could not assign legacy capabilities');
1172 return false;
1173 }
1174 }
1175 // Are there any capabilities that have been removed from the file
1176 // definition that we need to delete from the stored capabilities and
1177 // role assignments?
1178 capabilities_cleanup($component, $filecaps);
1179
1180 return true;
1181}
1182
1183
1184/**
1185 * Deletes cached capabilities that are no longer needed by the component.
1186 * Also unassigns these capabilities from any roles that have them.
1187 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1188 * @param $newcapdef - array of the new capability definitions that will be
1189 * compared with the cached capabilities
1190 * @return int - number of deprecated capabilities that have been removed
1191 */
1192function capabilities_cleanup($component, $newcapdef=NULL) {
1193
1194 $removedcount = 0;
1195
1196 if ($cachedcaps = get_cached_capabilities($component)) {
1197 foreach ($cachedcaps as $cachedcap) {
1198 if (empty($newcapdef) ||
1199 array_key_exists($cachedcap->name, $newcapdef) === false) {
1200
1201 // Remove from capabilities cache.
1202 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
1203 error('Could not delete deprecated capability '.$cachedcap->name);
1204 } else {
1205 $removedcount++;
1206 }
1207 // Delete from roles.
1208 if($roles = get_roles_with_capability($cachedcap->name)) {
1209 foreach($roles as $role) {
1210 if (!unassign_capability($role->id, $cachedcap->name)) {
1211 error('Could not unassign deprecated capability '.
1212 $cachedcap->name.' from role '.$role->name);
1213 }
1214 }
1215 }
1216 } // End if.
1217 }
1218 }
1219 return $removedcount;
1220}
1221
1222
1223
cee0901c 1224/****************
1225 * UI FUNCTIONS *
1226 ****************/
bbbf2d40 1227
1228
1229/**
1230 * prints human readable context identifier.
1231 */
0468976c 1232function print_context_name($context) {
340ea4e8 1233
ec0810ee 1234 $name = '';
1235
340ea4e8 1236 switch ($context->level) {
ec0810ee 1237
bbbf2d40 1238 case CONTEXT_SYSTEM: // by now it's a definite an inherit
ec0810ee 1239 $name = get_string('site');
340ea4e8 1240 break;
bbbf2d40 1241
1242 case CONTEXT_PERSONAL:
ec0810ee 1243 $name = get_string('personal');
340ea4e8 1244 break;
1245
bbbf2d40 1246 case CONTEXT_USERID:
ec0810ee 1247 if ($user = get_record('user', 'id', $context->instanceid)) {
1248 $name = get_string('user').': '.fullname($user);
1249 }
340ea4e8 1250 break;
1251
bbbf2d40 1252 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
ec0810ee 1253 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
1254 $name = get_string('category').': '.$category->name;
1255 }
340ea4e8 1256 break;
bbbf2d40 1257
1258 case CONTEXT_COURSE: // 1 to 1 to course cat
ec0810ee 1259 if ($course = get_record('course', 'id', $context->instanceid)) {
1260 $name = get_string('course').': '.$course->fullname;
1261 }
340ea4e8 1262 break;
bbbf2d40 1263
1264 case CONTEXT_GROUP: // 1 to 1 to course
ec0810ee 1265 if ($group = get_record('groups', 'id', $context->instanceid)) {
1266 $name = get_string('group').': '.$group->name;
1267 }
340ea4e8 1268 break;
bbbf2d40 1269
1270 case CONTEXT_MODULE: // 1 to 1 to course
98882637 1271 if ($cm = get_record('course_modules','id',$context->instanceid)) {
1272 if ($module = get_record('modules','id',$cm->module)) {
1273 if ($mod = get_record($module->name, 'id', $cm->instance)) {
ec0810ee 1274 $name = get_string('activitymodule').': '.$mod->name;
98882637 1275 }
ec0810ee 1276 }
1277 }
340ea4e8 1278 break;
bbbf2d40 1279
1280 case CONTEXT_BLOCK: // 1 to 1 to course
98882637 1281 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
1282 if ($block = get_record('block','id',$blockinstance->blockid)) {
ec0810ee 1283 $name = get_string('blocks').': '.get_string($block->name, 'block_'.$block->name);
1284 }
1285 }
340ea4e8 1286 break;
bbbf2d40 1287
1288 default:
1289 error ('This is an unknown context!');
340ea4e8 1290 return false;
1291
1292 }
1293
1294 return $name;
bbbf2d40 1295}
1296
1297
1298/**
1299 * Extracts the relevant capabilities given a contextid.
1300 * All case based, example an instance of forum context.
1301 * Will fetch all forum related capabilities, while course contexts
1302 * Will fetch all capabilities
0468976c 1303 * @param object context
bbbf2d40 1304 * @return array();
1305 *
1306 * capabilities
1307 * `name` varchar(150) NOT NULL,
1308 * `captype` varchar(50) NOT NULL,
1309 * `contextlevel` int(10) NOT NULL,
1310 * `component` varchar(100) NOT NULL,
1311 */
0468976c 1312function fetch_context_capabilities($context) {
98882637 1313
1314 global $CFG;
bbbf2d40 1315
1316 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
98882637 1317
0468976c 1318 switch ($context->level) {
bbbf2d40 1319
98882637 1320 case CONTEXT_SYSTEM: // all
1321 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1322 break;
1323
1324 case CONTEXT_PERSONAL:
1325 break;
1326
1327 case CONTEXT_USERID:
1328 break;
1329
1330 case CONTEXT_COURSECAT: // all
98882637 1331 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1332 break;
1333
1334 case CONTEXT_COURSE: // all
98882637 1335 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1336 break;
1337
1338 case CONTEXT_GROUP: // group caps
1339 break;
1340
1341 case CONTEXT_MODULE: // mod caps
98882637 1342 $cm = get_record('course_modules', 'id', $context->instanceid);
1343 $module = get_record('modules', 'id', $cm->module);
bbbf2d40 1344
98882637 1345 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
1346 and component = 'mod/$module->name'";
bbbf2d40 1347 break;
1348
1349 case CONTEXT_BLOCK: // block caps
98882637 1350 $cb = get_record('block_instance', 'id', $context->instanceid);
1351 $block = get_record('block', 'id', $cb->blockid);
bbbf2d40 1352
98882637 1353 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
1354 and component = 'block/$block->name'";
bbbf2d40 1355 break;
1356
1357 default:
1358 return false;
1359 }
1360
1361 $records = get_records_sql($SQL.' '.$sort);
1362 return $records;
1363
1364}
1365
1366
1367/**
1368 * This function pulls out all the resolved capabilities (overrides and
1369 * defaults) of a role used in capability overrieds in contexts at a given
1370 * context.
0468976c 1371 * @param int $context
bbbf2d40 1372 * @param int $roleid
1373 * @return array
1374 */
0468976c 1375function role_context_capabilities($roleid, $context) {
98882637 1376 global $CFG;
1377
1378 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
0468976c 1379 if ($sitecontext->id == $context->id) {
98882637 1380 return array();
1381 }
1382
1383 // first of all, figure out all parental contexts
98882637 1384 $contexts = array_reverse(get_parent_contexts($context));
1385 $contexts = '('.implode(',', $contexts).')';
1386
1387 $SQL = "SELECT rc.* FROM {$CFG->prefix}role_capabilities rc, {$CFG->prefix}context c
1388 where rc.contextid in $contexts
1389 and rc.roleid = $roleid
1390 and rc.contextid = c.id
1391 ORDER BY c.level DESC, rc.capability DESC";
1392
1393 $records = get_records_sql($SQL);
1394
1395 $capabilities = array();
1396
1397 // We are traversing via reverse order.
1398 foreach ($records as $record) {
1399 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
1400 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
1401 $capabilities[$record->capability] = $record->permission;
1402 }
1403 }
1404 return $capabilities;
bbbf2d40 1405}
1406
1407
1408/**
0468976c 1409 * Recursive function which, given a context, find all parent context ids,
bbbf2d40 1410 * and return the array in reverse order, i.e. parent first, then grand
1411 * parent, etc.
1412 * @param object $context
1413 * @return array()
1414 */
bbbf2d40 1415function get_parent_contexts($context) {
1416
0468976c 1417 switch ($context->level) {
bbbf2d40 1418
1419 case CONTEXT_SYSTEM: // no parent
98882637 1420 return null;
bbbf2d40 1421 break;
1422
1423 case CONTEXT_PERSONAL:
1424 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
1425 return array($parent->id);
1426 break;
1427
1428 case CONTEXT_USERID:
1429 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
1430 return array($parent->id);
1431 break;
1432
1433 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
1434 $coursecat = get_record('course_categories','id',$context->instanceid);
1435 if ($coursecat->parent) { // return parent value if exist
1436 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1437 return array_merge(array($parent->id), get_parent_contexts($parent));
1438 } else { // else return site value
1439 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
1440 return array($parent->id);
1441 }
1442 break;
1443
1444 case CONTEXT_COURSE: // 1 to 1 to course cat
1445 // find the course cat, and return its value
1446 $course = get_record('course','id',$context->instanceid);
1447 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1448 return array_merge(array($parent->id), get_parent_contexts($parent));
1449 break;
1450
1451 case CONTEXT_GROUP: // 1 to 1 to course
1452 $group = get_record('groups','id',$context->instanceid);
1453 $parent = get_context_instance(CONTEXT_COURSE, $group->courseid);
1454 return array_merge(array($parent->id), get_parent_contexts($parent));
1455 break;
1456
1457 case CONTEXT_MODULE: // 1 to 1 to course
1458 $cm = get_record('course_modules','id',$context->instanceid);
1459 $parent = get_context_instance(CONTEXT_COURSE, $cm->course);
1460 return array_merge(array($parent->id), get_parent_contexts($parent));
1461 break;
1462
1463 case CONTEXT_BLOCK: // 1 to 1 to course
1464 $block = get_record('block_instance','id',$context->instanceid);
1465 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
1466 return array_merge(array($parent->id), get_parent_contexts($parent));
1467 break;
1468
1469 default:
1470 error ('This is an unknown context!');
1471 return false;
1472 }
1473
1474}
1475
1476
1477/**
1478 * This function gets the capability of a role in a given context.
1479 * It is needed when printing override forms.
1480 * @param int $contextid
bbbf2d40 1481 * @param string $capability
1482 * @param array $capabilities - array loaded using role_context_capabilities
1483 * @return int (allow, prevent, prohibit, inherit)
1484 */
bbbf2d40 1485function get_role_context_capability($contextid, $capability, $capabilities) {
98882637 1486 return $capabilities[$contextid][$capability];
bbbf2d40 1487}
1488
1489
cee0901c 1490/**
1491 * Returns the human-readable, translated version of the capability.
1492 * Basically a big switch statement.
1493 * @param $capabilityname - e.g. mod/choice:readresponses
1494 */
ceb83c70 1495function get_capability_string($capabilityname) {
bbbf2d40 1496
cee0901c 1497 // Typical capabilityname is mod/choice:readresponses
ceb83c70 1498
1499 $names = split('/', $capabilityname);
1500 $stringname = $names[1]; // choice:readresponses
1501 $components = split(':', $stringname);
1502 $componentname = $components[0]; // choice
98882637 1503
1504 switch ($names[0]) {
1505 case 'mod':
ceb83c70 1506 $string = get_string($stringname, $componentname);
98882637 1507 break;
1508
1509 case 'block':
ceb83c70 1510 $string = get_string($stringname, 'block_'.$componentname);
98882637 1511 break;
ceb83c70 1512
98882637 1513 case 'moodle':
ceb83c70 1514 $string = get_string($stringname, 'role');
98882637 1515 break;
1516
1517 case 'enrol':
ceb83c70 1518 $string = get_string($stringname, 'enrol_'.$componentname);
1519 break;
98882637 1520
1521 default:
ceb83c70 1522 $string = get_string($stringname);
98882637 1523 break;
98882637 1524
1525 }
ceb83c70 1526 return $string;
bbbf2d40 1527}
1528
1529
cee0901c 1530/**
1531 * This gets the mod/block/course/core etc strings.
1532 * @param $component
1533 * @param $contextlevel
1534 */
bbbf2d40 1535function get_component_string($component, $contextlevel) {
1536
98882637 1537 switch ($contextlevel) {
bbbf2d40 1538
98882637 1539 case CONTEXT_SYSTEM:
ceb83c70 1540 $string = get_string('coresystem');
bbbf2d40 1541 break;
1542
1543 case CONTEXT_PERSONAL:
98882637 1544 $string = get_string('personal');
bbbf2d40 1545 break;
1546
1547 case CONTEXT_USERID:
98882637 1548 $string = get_string('users');
bbbf2d40 1549 break;
1550
1551 case CONTEXT_COURSECAT:
98882637 1552 $string = get_string('categories');
bbbf2d40 1553 break;
1554
1555 case CONTEXT_COURSE:
98882637 1556 $string = get_string('course');
bbbf2d40 1557 break;
1558
1559 case CONTEXT_GROUP:
98882637 1560 $string = get_string('group');
bbbf2d40 1561 break;
1562
1563 case CONTEXT_MODULE:
98882637 1564 $string = get_string('modulename', basename($component));
bbbf2d40 1565 break;
1566
1567 case CONTEXT_BLOCK:
98882637 1568 $string = get_string('blockname', 'block_'.$component.'.php');
bbbf2d40 1569 break;
1570
1571 default:
1572 error ('This is an unknown context!');
1573 return false;
98882637 1574
1575 }
98882637 1576 return $string;
bbbf2d40 1577}
cee0901c 1578
1579
1580?>