Removed tabs
[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 */
1648afb2 1410function role_context_capabilities($roleid, $context, $cap='') {
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
1648afb2 1422 if ($cap) {
1423 $search = ' AND rc.capability = "'.$cap.'" ';
1424 } else {
1425 $search = '';
1426 }
1427
98882637 1428 $SQL = "SELECT rc.* FROM {$CFG->prefix}role_capabilities rc, {$CFG->prefix}context c
1429 where rc.contextid in $contexts
1430 and rc.roleid = $roleid
1648afb2 1431 and rc.contextid = c.id $search
d140ad3f 1432 ORDER BY c.aggregatelevel DESC, rc.capability DESC";
1648afb2 1433
98882637 1434 $records = get_records_sql($SQL);
98882637 1435 $capabilities = array();
1436
1437 // We are traversing via reverse order.
1438 foreach ($records as $record) {
1439 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
1440 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
1441 $capabilities[$record->capability] = $record->permission;
1442 }
1443 }
1444 return $capabilities;
bbbf2d40 1445}
1446
1447
1448/**
0468976c 1449 * Recursive function which, given a context, find all parent context ids,
bbbf2d40 1450 * and return the array in reverse order, i.e. parent first, then grand
1451 * parent, etc.
1452 * @param object $context
1453 * @return array()
1454 */
bbbf2d40 1455function get_parent_contexts($context) {
1456
d140ad3f 1457 switch ($context->aggregatelevel) {
bbbf2d40 1458
1459 case CONTEXT_SYSTEM: // no parent
98882637 1460 return null;
bbbf2d40 1461 break;
1462
1463 case CONTEXT_PERSONAL:
1464 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
1465 return array($parent->id);
1466 break;
1467
1468 case CONTEXT_USERID:
1469 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
1470 return array($parent->id);
1471 break;
1472
1473 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
1474 $coursecat = get_record('course_categories','id',$context->instanceid);
1475 if ($coursecat->parent) { // return parent value if exist
1476 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1477 return array_merge(array($parent->id), get_parent_contexts($parent));
1478 } else { // else return site value
1479 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
1480 return array($parent->id);
1481 }
1482 break;
1483
1484 case CONTEXT_COURSE: // 1 to 1 to course cat
1485 // find the course cat, and return its value
1486 $course = get_record('course','id',$context->instanceid);
1487 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1488 return array_merge(array($parent->id), get_parent_contexts($parent));
1489 break;
1490
1491 case CONTEXT_GROUP: // 1 to 1 to course
1492 $group = get_record('groups','id',$context->instanceid);
1493 $parent = get_context_instance(CONTEXT_COURSE, $group->courseid);
1494 return array_merge(array($parent->id), get_parent_contexts($parent));
1495 break;
1496
1497 case CONTEXT_MODULE: // 1 to 1 to course
1498 $cm = get_record('course_modules','id',$context->instanceid);
1499 $parent = get_context_instance(CONTEXT_COURSE, $cm->course);
1500 return array_merge(array($parent->id), get_parent_contexts($parent));
1501 break;
1502
1503 case CONTEXT_BLOCK: // 1 to 1 to course
1504 $block = get_record('block_instance','id',$context->instanceid);
1505 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
1506 return array_merge(array($parent->id), get_parent_contexts($parent));
1507 break;
1508
1509 default:
1510 error ('This is an unknown context!');
1511 return false;
1512 }
1513
1514}
1515
1516
1517/**
1518 * This function gets the capability of a role in a given context.
1519 * It is needed when printing override forms.
1520 * @param int $contextid
bbbf2d40 1521 * @param string $capability
1522 * @param array $capabilities - array loaded using role_context_capabilities
1523 * @return int (allow, prevent, prohibit, inherit)
1524 */
bbbf2d40 1525function get_role_context_capability($contextid, $capability, $capabilities) {
98882637 1526 return $capabilities[$contextid][$capability];
bbbf2d40 1527}
1528
1529
cee0901c 1530/**
1531 * Returns the human-readable, translated version of the capability.
1532 * Basically a big switch statement.
1533 * @param $capabilityname - e.g. mod/choice:readresponses
1534 */
ceb83c70 1535function get_capability_string($capabilityname) {
bbbf2d40 1536
cee0901c 1537 // Typical capabilityname is mod/choice:readresponses
ceb83c70 1538
1539 $names = split('/', $capabilityname);
1540 $stringname = $names[1]; // choice:readresponses
1541 $components = split(':', $stringname);
1542 $componentname = $components[0]; // choice
98882637 1543
1544 switch ($names[0]) {
1545 case 'mod':
ceb83c70 1546 $string = get_string($stringname, $componentname);
98882637 1547 break;
1548
1549 case 'block':
ceb83c70 1550 $string = get_string($stringname, 'block_'.$componentname);
98882637 1551 break;
ceb83c70 1552
98882637 1553 case 'moodle':
ceb83c70 1554 $string = get_string($stringname, 'role');
98882637 1555 break;
1556
1557 case 'enrol':
ceb83c70 1558 $string = get_string($stringname, 'enrol_'.$componentname);
1559 break;
98882637 1560
1561 default:
ceb83c70 1562 $string = get_string($stringname);
98882637 1563 break;
98882637 1564
1565 }
ceb83c70 1566 return $string;
bbbf2d40 1567}
1568
1569
cee0901c 1570/**
1571 * This gets the mod/block/course/core etc strings.
1572 * @param $component
1573 * @param $contextlevel
1574 */
bbbf2d40 1575function get_component_string($component, $contextlevel) {
1576
98882637 1577 switch ($contextlevel) {
bbbf2d40 1578
98882637 1579 case CONTEXT_SYSTEM:
ceb83c70 1580 $string = get_string('coresystem');
bbbf2d40 1581 break;
1582
1583 case CONTEXT_PERSONAL:
98882637 1584 $string = get_string('personal');
bbbf2d40 1585 break;
1586
1587 case CONTEXT_USERID:
98882637 1588 $string = get_string('users');
bbbf2d40 1589 break;
1590
1591 case CONTEXT_COURSECAT:
98882637 1592 $string = get_string('categories');
bbbf2d40 1593 break;
1594
1595 case CONTEXT_COURSE:
98882637 1596 $string = get_string('course');
bbbf2d40 1597 break;
1598
1599 case CONTEXT_GROUP:
98882637 1600 $string = get_string('group');
bbbf2d40 1601 break;
1602
1603 case CONTEXT_MODULE:
98882637 1604 $string = get_string('modulename', basename($component));
bbbf2d40 1605 break;
1606
1607 case CONTEXT_BLOCK:
98882637 1608 $string = get_string('blockname', 'block_'.$component.'.php');
bbbf2d40 1609 break;
1610
1611 default:
1612 error ('This is an unknown context!');
1613 return false;
98882637 1614
1615 }
98882637 1616 return $string;
bbbf2d40 1617}
cee0901c 1618
945f88ca 1619/** gets the list of roles assigned to this context
1620 * @param object $context
1621 * @return array
1622 */
e4dd3222 1623function get_roles_used_in_context($context) {
1624
1625 global $CFG;
1626
1627 return get_records_sql('SELECT distinct r.id, r.name
1628 FROM '.$CFG->prefix.'role_assignments ra,
1629 '.$CFG->prefix.'role r
1630 WHERE r.id = ra.roleid
1631 AND ra.contextid = '.$context->id.'
1632 ORDER BY r.sortorder ASC');
1633}
1634
945f88ca 1635/** this function is used to print roles column in user profile page.
1636 * @param int userid
1637 * @param int contextid
1638 * @return string
1639 */
0a8a95c9 1640function get_user_roles_in_context($userid, $contextid){
1641 global $CFG;
1642
1643 $rolestring = '';
1644 $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';
1645 if ($roles = get_records_sql($SQL)) {
1646 foreach ($roles as $userrole) {
1647 $rolestring .= '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$userrole->contextid.'&amp;roleid='.$userrole->roleid.'">'.$userrole->name.'</a>, ';
1648 }
1649
1650 }
1651 return rtrim($rolestring, ', ');
1652}
68c52526 1653
1654
945f88ca 1655/**
1656 * Checks if a user can override capabilities of a particular role in this context
1657 * @param object $context
1658 * @param int targetroleid - the id of the role you want to override
1659 * @return boolean
1660 */
68c52526 1661function user_can_override($context, $targetroleid) {
1662 // first check if user has override capability
1663 // if not return false;
1664 if (!has_capability('moodle/role:override', $context)) {
1665 return false;
1666 }
1667 // pull out all active roles of this user from this context(or above)
c0614051 1668 if ($userroles = get_user_roles($context)) {
1669 foreach ($userroles as $userrole) {
1670 // if any in the role_allow_override table, then it's ok
1671 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
1672 return true;
1673 }
68c52526 1674 }
1675 }
1676
1677 return false;
1678
1679}
1680
945f88ca 1681/**
1682 * Checks if a user can assign users to a particular role in this context
1683 * @param object $context
1684 * @param int targetroleid - the id of the role you want to assign users to
1685 * @return boolean
1686 */
68c52526 1687function user_can_assign($context, $targetroleid) {
1688
1689 // first check if user has override capability
1690 // if not return false;
1691 if (!has_capability('moodle/role:assign', $context)) {
1692 return false;
1693 }
1694 // pull out all active roles of this user from this context(or above)
c0614051 1695 if ($userroles = get_user_roles($context)) {
1696 foreach ($userroles as $userrole) {
1697 // if any in the role_allow_override table, then it's ok
1698 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
1699 return true;
1700 }
68c52526 1701 }
1702 }
1703
1704 return false;
1705}
1706
945f88ca 1707/**
1708 * gets all the user roles assigned in this context, or higher contexts
1709 * this is mainly used when checking if a user can assign a role, or overriding a role
1710 * i.e. we need to know what this user holds, in order to verify against allow_assign and
1711 * allow_override tables
1712 * @param object $context
1713 * @param int $userid
1714 * @return array
1715 */
c0614051 1716function get_user_roles($context, $userid=0) {
68c52526 1717
1718 global $USER, $CFG, $db;
c0614051 1719
1720 if (empty($userid)) {
1721 if (empty($USER->id)) {
1722 return array();
1723 }
1724 $userid = $USER->id;
1725 }
1726
1727 if ($parents = get_parent_contexts($context)) {
1728 $contexts = ' AND ra.contextid IN ('.implode(',' , $parents).')';
1729 } else {
1730 $contexts = ' AND ra.contextid = \''.$context->id.'\'';
1731 }
1732
68c52526 1733 return get_records_sql('SELECT *
1734 FROM '.$CFG->prefix.'role_assignments ra
c0614051 1735 WHERE ra.userid = '.$userid.
1736 $contexts);
68c52526 1737}
1738
945f88ca 1739/**
1740 * Creates a record in the allow_override table
1741 * @param int sroleid - source roleid
1742 * @param int troleid - target roleid
1743 * @return int - id or false
1744 */
1745function allow_override($sroleid, $troleid) {
1746 $record->roleid = $sroleid;
1747 $record->allowoverride = $troleid;
1748 return insert_record('role_allow_override', $record);
1749}
1750
1751/**
1752 * Creates a record in the allow_assign table
1753 * @param int sroleid - source roleid
1754 * @param int troleid - target roleid
1755 * @return int - id or false
1756 */
1757function allow_assign($sroleid, $troleid) {
1758 $record->roleid = $sroleid;
1759 $record->allowassign = $troleid;
1760 return insert_record('role_allow_assign', $record);
1761}
1762
1763/**
1764 * gets a list of roles assignalbe in this context for this user
1765 * @param object $context
1766 * @return array
1767 */
1768function get_assignable_roles ($context) {
1769
1770 $role = get_records('role');
1771 $options = array();
1772 foreach ($role as $rolex) {
1773 if (user_can_assign($context, $rolex->id)) {
1774 $options[$rolex->id] = $rolex->name;
1775 }
1776 }
1777 return $options;
1778}
1779
1780/**
1781 * gets a list of roles that can be overriden in this context by this user
1782 * @param object $context
1783 * @return array
1784 */
1785function get_overridable_roles ($context) {
1786
1787 $role = get_records('role');
1788 $options = array();
1789 foreach ($role as $rolex) {
1790 if (user_can_override($context, $rolex->id)) {
1791 $options[$rolex->id] = $rolex->name;
1792 }
1793 }
1794
1795 return $options;
1796
1797}
1648afb2 1798
1799
1800/**
1801 * who has this capability in this context
1802 * does not handling user level resolving!!!
1803 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
1804 * @param $context - object
1805 * @param $capability - string capability
1806 * @param $fields - fields to be pulled
1807 * @param $sort - the sort order
1808 */
1809function get_users_by_capability($context, $capability, $fields='distinct u.*', $sort='') {
1810
1811 global $CFG;
1812
1813 // first get all roles with this capability in this context, or above
1814 $possibleroles = get_roles_with_capability($capability, CAP_ALLOW);
1815 $validroleids = array();
1816 foreach ($possibleroles as $prole) {
1817 $caps = role_context_capabilities($prole->id, $context, $capability); // resolved list
1818 if ($caps[$capability] > 0) { // resolved capability > 0
1819 $validroleids[] = $prole->id;
1820 }
1821 }
1822
1823 if ($usercontexts = get_parent_contexts($context)) {
1824 $listofcontexts = '('.implode(',', $usercontexts).')';
1825 } else {
1826 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
1827 $listofcontexts = '('.$sitecontext->id.')'; // must be site
1828 }
1829
1830 $roleids = '('.implode(',', $validroleids).')';
1831
1832 $select = ' SELECT '.$fields;
1833 $from = ' FROM '.$CFG->prefix.'user u LEFT JOIN '.$CFG->prefix.'role_assignments ra ON ra.userid = u.id ';
1834 $where = ' WHERE (ra.contextid = '.$context->id.' OR ra.contextid in '.$listofcontexts.') AND u.deleted = 0 AND ra.roleid in '.$roleids.' ';
1835
1836 return get_records_sql($select.$from.$where);
1837
1838}
e4dd3222 1839?>