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