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