New tags
[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
42ac3ecf 466 {$CFG->prefix}role_assignments ra,
467 {$CFG->prefix}role_capabilities rc,
468 {$CFG->prefix}context c1
bbbf2d40 469 WHERE
d4649c76 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
42ac3ecf 485 {$CFG->prefix}role_assignments ra,
486 {$CFG->prefix}role_capabilities rc,
487 {$CFG->prefix}context c1,
488 {$CFG->prefix}context c2
bbbf2d40 489 WHERE
d4649c76 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
dbe7e582 610 if (!empty($otheruserid)) {
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
ccfc5ecc 980/// Only add to cache if context isn't empty.
981 if (!empty($context)) {
982 $context_cache[$aggregatelevel][$instance] = $context; // Cache it for later
983 $context_cache_id[$context->id] = $context; // Cache it for later
984 }
0468976c 985
bbbf2d40 986 return $context;
987}
988
cee0901c 989
340ea4e8 990/**
991 * Get a context instance as an object, from a given id.
992 * @param $id
993 */
994function get_context_instance_by_id($id) {
995
d9a35e12 996 global $context_cache, $context_cache_id;
997
340ea4e8 998 if (isset($context_cache_id[$id])) { // Already cached
75e84883 999 return $context_cache_id[$id];
340ea4e8 1000 }
1001
1002 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
d140ad3f 1003 $context_cache[$context->aggregatelevel][$context->instanceid] = $context;
340ea4e8 1004 $context_cache_id[$context->id] = $context;
1005 return $context;
1006 }
1007
1008 return false;
1009}
1010
bbbf2d40 1011
8737be58 1012/**
1013 * Get the local override (if any) for a given capability in a role in a context
1014 * @param $roleid
0468976c 1015 * @param $contextid
1016 * @param $capability
8737be58 1017 */
1018function get_local_override($roleid, $contextid, $capability) {
1019 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1020}
1021
1022
bbbf2d40 1023
1024/************************************
1025 * DB TABLE RELATED FUNCTIONS *
1026 ************************************/
1027
cee0901c 1028/**
bbbf2d40 1029 * function that creates a role
1030 * @param name - role name
1031 * @param description - role description
1032 * @param legacy - optional legacy capability
1033 * @return id or false
1034 */
1035function create_role($name, $description, $legacy='') {
98882637 1036
1037 // check for duplicate role name
1038
1039 if ($role = get_record('role','name', $name)) {
98882637 1040 error('there is already a role with this name!');
1041 }
1042
1043 $role->name = $name;
1044 $role->description = $description;
ec7a8b79 1045
1046 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
1047
98882637 1048 if ($id = insert_record('role', $role)) {
ec7a8b79 1049 if ($legacy) {
1afecc03 1050 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
98882637 1051 }
ec7a8b79 1052
1053 /// By default, users with role:manage at site level
1054 /// should be able to assign users to this new role, and override this new role's capabilities
1055
1056 // find all admin roles
e46c0987 1057 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
1058 // foreach admin role
1059 foreach ($adminroles as $arole) {
1060 // write allow_assign and allow_overrid
1061 allow_assign($arole->id, $id);
1062 allow_override($arole->id, $id);
1063 }
ec7a8b79 1064 }
1065
98882637 1066 return $id;
1067 } else {
1068 return false;
1069 }
bbbf2d40 1070
1071}
1072
1073/**
1074 * Function to write context specific overrides, or default capabilities.
1075 * @param module - string name
1076 * @param capability - string name
1077 * @param contextid - context id
1078 * @param roleid - role id
1079 * @param permission - int 1,-1 or -1000
1080 */
1081function assign_capability($capability, $permission, $roleid, $contextid) {
98882637 1082
1083 global $USER;
1084
1085 if (empty($permission) || $permission == 0) { // if permission is not set
1086 unassign_capability($capability, $roleid, $contextid);
1087 }
bbbf2d40 1088
1089 $cap = new object;
1090 $cap->contextid = $contextid;
1091 $cap->roleid = $roleid;
1092 $cap->capability = $capability;
1093 $cap->permission = $permission;
1094 $cap->timemodified = time();
9db12da7 1095 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
bbbf2d40 1096
1097 return insert_record('role_capabilities', $cap);
1098}
1099
1100
1101/**
1102 * Unassign a capability from a role.
1103 * @param $roleid - the role id
1104 * @param $capability - the name of the capability
1105 * @return boolean - success or failure
1106 */
1107function unassign_capability($capability, $roleid, $contextid=NULL) {
98882637 1108
1109 if (isset($contextid)) {
1110 $status = delete_records('role_capabilities', 'capability', $capability,
1111 'roleid', $roleid, 'contextid', $contextid);
1112 } else {
1113 $status = delete_records('role_capabilities', 'capability', $capability,
1114 'roleid', $roleid);
1115 }
1116 return $status;
bbbf2d40 1117}
1118
1119
1120/**
1121 * Get the roles that have a given capability.
1122 * @param $capability - capability name (string)
1123 * @param $permission - optional, the permission defined for this capability
1124 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
1125 * @return array or role objects
1126 */
ec7a8b79 1127function get_roles_with_capability($capability, $permission=NULL, $context='') {
1128
bbbf2d40 1129 global $CFG;
1130
ec7a8b79 1131 if ($context) {
1132 if ($contexts = get_parent_contexts($context)) {
1133 $listofcontexts = '('.implode(',', $contexts).')';
1134 } else {
1135 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
1136 $listofcontexts = '('.$sitecontext->id.')'; // must be site
1137 }
42ac3ecf 1138 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
ec7a8b79 1139 } else {
1140 $contextstr = '';
1141 }
1142
bbbf2d40 1143 $selectroles = "SELECT r.*
42ac3ecf 1144 FROM {$CFG->prefix}role r,
1145 {$CFG->prefix}role_capabilities rc
bbbf2d40 1146 WHERE rc.capability = '$capability'
ec7a8b79 1147 AND rc.roleid = r.id $contextstr";
bbbf2d40 1148
1149 if (isset($permission)) {
1150 $selectroles .= " AND rc.permission = '$permission'";
1151 }
1152 return get_records_sql($selectroles);
1153}
1154
1155
1156/**
a9e1c058 1157 * This function makes a role-assignment (a role for a user or group in a particular context)
bbbf2d40 1158 * @param $roleid - the role of the id
1159 * @param $userid - userid
1160 * @param $groupid - group id
1161 * @param $contextid - id of the context
1162 * @param $timestart - time this assignment becomes effective
1163 * @param $timeend - time this assignemnt ceases to be effective
1164 * @uses $USER
1165 * @return id - new id of the assigment
1166 */
f44152f4 1167function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual') {
aa311411 1168 global $USER, $CFG;
bbbf2d40 1169
218564ac 1170 if ($CFG->debug > 7) {
98882637 1171 notify("Assign roleid $roleid userid $userid contextid $contextid", 'notifytiny');
aa311411 1172 }
bbbf2d40 1173
a9e1c058 1174/// Do some data validation
1175
bbbf2d40 1176 if (empty($roleid)) {
a9e1c058 1177 notify('Role ID not provided');
1178 return false;
bbbf2d40 1179 }
1180
1181 if (empty($userid) && empty($groupid)) {
a9e1c058 1182 notify('Either userid or groupid must be provided');
1183 return false;
bbbf2d40 1184 }
7700027f 1185
1186 if ($userid && !record_exists('user', 'id', $userid)) {
1187 notify('User does not exist!');
1188 return false;
1189 }
bbbf2d40 1190
dc411d1b 1191 if ($groupid && !record_exists('groups', 'id', $groupid)) {
1192 notify('Group does not exist!');
1193 return false;
1194 }
1195
7700027f 1196 if (!$context = get_context_instance_by_id($contextid)) {
a9e1c058 1197 notify('A valid context must be provided');
1198 return false;
bbbf2d40 1199 }
1200
a9e1c058 1201 if (($timestart and $timeend) and ($timestart > $timeend)) {
7700027f 1202 notify('The end time can not be earlier than the start time');
a9e1c058 1203 return false;
1204 }
1205
7700027f 1206
a9e1c058 1207/// Check for existing entry
1208 if ($userid) {
7700027f 1209 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
a9e1c058 1210 } else {
7700027f 1211 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
a9e1c058 1212 }
1213
9ebcb4d2 1214
a9e1c058 1215 $newra = new object;
bbbf2d40 1216
a9e1c058 1217 if (empty($ra)) { // Create a new entry
1218 $newra->roleid = $roleid;
7700027f 1219 $newra->contextid = $context->id;
a9e1c058 1220 $newra->userid = $userid;
1221 $newra->groupid = $groupid;
1222
1223 $newra->hidden = $hidden;
f44152f4 1224 $newra->enrol = $enrol;
a9e1c058 1225 $newra->timestart = $timestart;
1226 $newra->timeend = $timeend;
1227 $newra->timemodified = time();
1228 $newra->modifier = empty($USER->id) ? 0 : $USER->id;
1229
9ebcb4d2 1230 $success = insert_record('role_assignments', $newra);
a9e1c058 1231
1232 } else { // We already have one, just update it
1233
1234 $newra->id = $ra->id;
1235 $newra->hidden = $hidden;
f44152f4 1236 $newra->enrol = $enrol;
a9e1c058 1237 $newra->timestart = $timestart;
1238 $newra->timeend = $timeend;
1239 $newra->timemodified = time();
1240 $newra->modifier = empty($USER->id) ? 0 : $USER->id;
1241
9ebcb4d2 1242 $success = update_record('role_assignments', $newra);
1243 }
1244
7700027f 1245 if ($success) { /// Role was assigned, so do some other things
1246
1247 /// If the user is the current user, then reload the capabilities too.
1248 if (!empty($USER->id) && $USER->id == $userid) {
1249 load_user_capability();
1250 }
1251
1252 /// Make sure the user is subscribed to any appropriate forums in this context
1253 require_once($CFG->dirroot.'/mod/forum/lib.php');
1911105f 1254 forum_add_user_default_subscriptions($userid, $context);
a9e1c058 1255 }
6eb4f823 1256
1257 return $success;
bbbf2d40 1258}
1259
1260
1261/**
1dc1f037 1262 * Deletes one or more role assignments. You must specify at least one parameter.
bbbf2d40 1263 * @param $roleid
1264 * @param $userid
1265 * @param $groupid
1266 * @param $contextid
1267 * @return boolean - success or failure
1268 */
1dc1f037 1269function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0) {
1270 $args = array('roleid', 'userid', 'groupid', 'contextid');
1271 $select = array();
1272 foreach ($args as $arg) {
1273 if ($$arg) {
1274 $select[] = $arg.' = '.$$arg;
1275 }
1276 }
1277 if ($select) {
1278 return delete_records_select('role_assignments', implode(' AND ', $select));
1279 }
1280 return false;
bbbf2d40 1281}
1282
1283
1284/**
1285 * Loads the capability definitions for the component (from file). If no
1286 * capabilities are defined for the component, we simply return an empty array.
1287 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1288 * @return array of capabilities
1289 */
1290function load_capability_def($component) {
1291 global $CFG;
1292
1293 if ($component == 'moodle') {
1294 $defpath = $CFG->libdir.'/db/access.php';
1295 $varprefix = 'moodle';
1296 } else {
1297 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
1298 $varprefix = str_replace('/', '_', $component);
1299 }
1300 $capabilities = array();
1301
1302 if (file_exists($defpath)) {
1303 require_once($defpath);
1304 $capabilities = ${$varprefix.'_capabilities'};
1305 }
1306 return $capabilities;
1307}
1308
1309
1310/**
1311 * Gets the capabilities that have been cached in the database for this
1312 * component.
1313 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1314 * @return array of capabilities
1315 */
1316function get_cached_capabilities($component='moodle') {
1317 if ($component == 'moodle') {
1318 $storedcaps = get_records_select('capabilities',
1319 "name LIKE 'moodle/%:%'");
1320 } else {
1321 $storedcaps = get_records_select('capabilities',
1322 "name LIKE '$component:%'");
1323 }
1324 return $storedcaps;
1325}
1326
1327
1328/**
1329 * Updates the capabilities table with the component capability definitions.
1330 * If no parameters are given, the function updates the core moodle
1331 * capabilities.
1332 *
1333 * Note that the absence of the db/access.php capabilities definition file
1334 * will cause any stored capabilities for the component to be removed from
1335 * the database.
1336 *
1337 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1338 * @return boolean
1339 */
1340function update_capabilities($component='moodle') {
1341
1342 $storedcaps = array();
be4486da 1343
1344 $filecaps = load_capability_def($component);
bbbf2d40 1345 $cachedcaps = get_cached_capabilities($component);
1346 if ($cachedcaps) {
1347 foreach ($cachedcaps as $cachedcap) {
1348 array_push($storedcaps, $cachedcap->name);
be4486da 1349 // update risk bitmasks in existing capabilitites if needed
1350 if (array_key_exists($cachedcap->name, $filecaps)) {
1351 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2b531945 1352 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
be4486da 1353 }
1354 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
1355 $updatecap = new object;
1356 $updatecap->id = $cachedcap->id;
1357 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
1358 if (!update_record('capabilities', $updatecap)) {
1359 return false;
1360 }
1361 }
1362 }
bbbf2d40 1363 }
1364 }
be4486da 1365
bbbf2d40 1366 // Are there new capabilities in the file definition?
1367 $newcaps = array();
1368
1369 foreach ($filecaps as $filecap => $def) {
1370 if (!$storedcaps ||
1371 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2b531945 1372 if (!array_key_exists('riskbitmask', $def)) {
1373 $def['riskbitmask'] = 0; // no risk if not specified
1374 }
bbbf2d40 1375 $newcaps[$filecap] = $def;
1376 }
1377 }
1378 // Add new capabilities to the stored definition.
1379 foreach ($newcaps as $capname => $capdef) {
1380 $capability = new object;
1381 $capability->name = $capname;
1382 $capability->captype = $capdef['captype'];
1383 $capability->contextlevel = $capdef['contextlevel'];
1384 $capability->component = $component;
be4486da 1385 $capability->riskbitmask = $capdef['riskbitmask'];
bbbf2d40 1386
1387 if (!insert_record('capabilities', $capability, false, 'id')) {
1388 return false;
1389 }
1390 // Do we need to assign the new capabilities to roles that have the
1391 // legacy capabilities moodle/legacy:* as well?
1392 if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
1393 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
1394 error('Could not assign legacy capabilities');
1395 return false;
1396 }
1397 }
1398 // Are there any capabilities that have been removed from the file
1399 // definition that we need to delete from the stored capabilities and
1400 // role assignments?
1401 capabilities_cleanup($component, $filecaps);
1402
1403 return true;
1404}
1405
1406
1407/**
1408 * Deletes cached capabilities that are no longer needed by the component.
1409 * Also unassigns these capabilities from any roles that have them.
1410 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1411 * @param $newcapdef - array of the new capability definitions that will be
1412 * compared with the cached capabilities
1413 * @return int - number of deprecated capabilities that have been removed
1414 */
1415function capabilities_cleanup($component, $newcapdef=NULL) {
1416
1417 $removedcount = 0;
1418
1419 if ($cachedcaps = get_cached_capabilities($component)) {
1420 foreach ($cachedcaps as $cachedcap) {
1421 if (empty($newcapdef) ||
1422 array_key_exists($cachedcap->name, $newcapdef) === false) {
1423
1424 // Remove from capabilities cache.
1425 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
1426 error('Could not delete deprecated capability '.$cachedcap->name);
1427 } else {
1428 $removedcount++;
1429 }
1430 // Delete from roles.
1431 if($roles = get_roles_with_capability($cachedcap->name)) {
1432 foreach($roles as $role) {
46943f7b 1433 if (!unassign_capability($cachedcap->name, $role->id)) {
bbbf2d40 1434 error('Could not unassign deprecated capability '.
1435 $cachedcap->name.' from role '.$role->name);
1436 }
1437 }
1438 }
1439 } // End if.
1440 }
1441 }
1442 return $removedcount;
1443}
1444
1445
1446
cee0901c 1447/****************
1448 * UI FUNCTIONS *
1449 ****************/
bbbf2d40 1450
1451
1452/**
1453 * prints human readable context identifier.
1454 */
0468976c 1455function print_context_name($context) {
340ea4e8 1456
ec0810ee 1457 $name = '';
d140ad3f 1458 switch ($context->aggregatelevel) {
ec0810ee 1459
bbbf2d40 1460 case CONTEXT_SYSTEM: // by now it's a definite an inherit
ec0810ee 1461 $name = get_string('site');
340ea4e8 1462 break;
bbbf2d40 1463
1464 case CONTEXT_PERSONAL:
ec0810ee 1465 $name = get_string('personal');
340ea4e8 1466 break;
1467
bbbf2d40 1468 case CONTEXT_USERID:
ec0810ee 1469 if ($user = get_record('user', 'id', $context->instanceid)) {
1470 $name = get_string('user').': '.fullname($user);
1471 }
340ea4e8 1472 break;
1473
bbbf2d40 1474 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
ec0810ee 1475 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
1476 $name = get_string('category').': '.$category->name;
1477 }
340ea4e8 1478 break;
bbbf2d40 1479
1480 case CONTEXT_COURSE: // 1 to 1 to course cat
ec0810ee 1481 if ($course = get_record('course', 'id', $context->instanceid)) {
1482 $name = get_string('course').': '.$course->fullname;
1483 }
340ea4e8 1484 break;
bbbf2d40 1485
1486 case CONTEXT_GROUP: // 1 to 1 to course
ec0810ee 1487 if ($group = get_record('groups', 'id', $context->instanceid)) {
1488 $name = get_string('group').': '.$group->name;
1489 }
340ea4e8 1490 break;
bbbf2d40 1491
1492 case CONTEXT_MODULE: // 1 to 1 to course
98882637 1493 if ($cm = get_record('course_modules','id',$context->instanceid)) {
1494 if ($module = get_record('modules','id',$cm->module)) {
1495 if ($mod = get_record($module->name, 'id', $cm->instance)) {
ec0810ee 1496 $name = get_string('activitymodule').': '.$mod->name;
98882637 1497 }
ec0810ee 1498 }
1499 }
340ea4e8 1500 break;
bbbf2d40 1501
1502 case CONTEXT_BLOCK: // 1 to 1 to course
98882637 1503 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
1504 if ($block = get_record('block','id',$blockinstance->blockid)) {
91be52d7 1505 global $CFG;
1506 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
1507 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
1508 $blockname = "block_$block->name";
1509 if ($blockobject = new $blockname()) {
1510 $name = $blockobject->title.' ('.get_string('block').')';
1511 }
ec0810ee 1512 }
1513 }
340ea4e8 1514 break;
bbbf2d40 1515
1516 default:
1517 error ('This is an unknown context!');
340ea4e8 1518 return false;
1519
1520 }
340ea4e8 1521 return $name;
bbbf2d40 1522}
1523
1524
1525/**
1526 * Extracts the relevant capabilities given a contextid.
1527 * All case based, example an instance of forum context.
1528 * Will fetch all forum related capabilities, while course contexts
1529 * Will fetch all capabilities
0468976c 1530 * @param object context
bbbf2d40 1531 * @return array();
1532 *
1533 * capabilities
1534 * `name` varchar(150) NOT NULL,
1535 * `captype` varchar(50) NOT NULL,
1536 * `contextlevel` int(10) NOT NULL,
1537 * `component` varchar(100) NOT NULL,
1538 */
0468976c 1539function fetch_context_capabilities($context) {
98882637 1540
1541 global $CFG;
bbbf2d40 1542
1543 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
98882637 1544
d140ad3f 1545 switch ($context->aggregatelevel) {
bbbf2d40 1546
98882637 1547 case CONTEXT_SYSTEM: // all
1548 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1549 break;
1550
1551 case CONTEXT_PERSONAL:
0a8a95c9 1552 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
bbbf2d40 1553 break;
1554
1555 case CONTEXT_USERID:
0a8a95c9 1556 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_USERID;
bbbf2d40 1557 break;
1558
1559 case CONTEXT_COURSECAT: // all
98882637 1560 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1561 break;
1562
1563 case CONTEXT_COURSE: // all
98882637 1564 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1565 break;
1566
1567 case CONTEXT_GROUP: // group caps
1568 break;
1569
1570 case CONTEXT_MODULE: // mod caps
98882637 1571 $cm = get_record('course_modules', 'id', $context->instanceid);
1572 $module = get_record('modules', 'id', $cm->module);
bbbf2d40 1573
98882637 1574 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
1575 and component = 'mod/$module->name'";
bbbf2d40 1576 break;
1577
1578 case CONTEXT_BLOCK: // block caps
98882637 1579 $cb = get_record('block_instance', 'id', $context->instanceid);
1580 $block = get_record('block', 'id', $cb->blockid);
bbbf2d40 1581
98882637 1582 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
1583 and component = 'block/$block->name'";
bbbf2d40 1584 break;
1585
1586 default:
1587 return false;
1588 }
1589
1590 $records = get_records_sql($SQL.' '.$sort);
1591 return $records;
1592
1593}
1594
1595
1596/**
1597 * This function pulls out all the resolved capabilities (overrides and
1598 * defaults) of a role used in capability overrieds in contexts at a given
1599 * context.
0a8a95c9 1600 * @param obj $context
bbbf2d40 1601 * @param int $roleid
1602 * @return array
1603 */
1648afb2 1604function role_context_capabilities($roleid, $context, $cap='') {
98882637 1605 global $CFG;
1606
1607 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
0468976c 1608 if ($sitecontext->id == $context->id) {
20aeb4b8 1609 $contexts = array($sitecontext->id);
1610 } else {
1611 // first of all, figure out all parental contexts
1612 $contexts = array_reverse(get_parent_contexts($context));
98882637 1613 }
98882637 1614 $contexts = '('.implode(',', $contexts).')';
1615
1648afb2 1616 if ($cap) {
e4697bf7 1617 $search = " AND rc.capability = '$cap' ";
1648afb2 1618 } else {
1619 $search = '';
1620 }
1621
98882637 1622 $SQL = "SELECT rc.* FROM {$CFG->prefix}role_capabilities rc, {$CFG->prefix}context c
1623 where rc.contextid in $contexts
1624 and rc.roleid = $roleid
1648afb2 1625 and rc.contextid = c.id $search
d140ad3f 1626 ORDER BY c.aggregatelevel DESC, rc.capability DESC";
1648afb2 1627
98882637 1628 $capabilities = array();
1629
4729012f 1630 if ($records = get_records_sql($SQL)) {
1631 // We are traversing via reverse order.
1632 foreach ($records as $record) {
1633 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
1634 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
1635 $capabilities[$record->capability] = $record->permission;
1636 }
1637 }
98882637 1638 }
1639 return $capabilities;
bbbf2d40 1640}
1641
1642
1643/**
0468976c 1644 * Recursive function which, given a context, find all parent context ids,
bbbf2d40 1645 * and return the array in reverse order, i.e. parent first, then grand
1646 * parent, etc.
1647 * @param object $context
1648 * @return array()
1649 */
bbbf2d40 1650function get_parent_contexts($context) {
1651
d140ad3f 1652 switch ($context->aggregatelevel) {
bbbf2d40 1653
1654 case CONTEXT_SYSTEM: // no parent
957861f7 1655 return array();
bbbf2d40 1656 break;
1657
1658 case CONTEXT_PERSONAL:
957861f7 1659 if (!$parent = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
1660 return array();
1661 } else {
1662 return array($parent->id);
1663 }
bbbf2d40 1664 break;
1665
1666 case CONTEXT_USERID:
957861f7 1667 if (!$parent = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
1668 return array();
1669 } else {
1670 return array($parent->id);
1671 }
bbbf2d40 1672 break;
1673
1674 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
957861f7 1675 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
1676 return array();
1677 }
c5ddc3fd 1678 if (!empty($coursecat->parent)) { // return parent value if exist
bbbf2d40 1679 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1680 return array_merge(array($parent->id), get_parent_contexts($parent));
1681 } else { // else return site value
1682 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
1683 return array($parent->id);
1684 }
1685 break;
1686
1687 case CONTEXT_COURSE: // 1 to 1 to course cat
957861f7 1688 if (!$course = get_record('course','id',$context->instanceid)) {
1689 return array();
1690 }
1691 if (!empty($course->category)) {
1692 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1693 return array_merge(array($parent->id), get_parent_contexts($parent));
1694 } else {
1695 return array();
1696 }
bbbf2d40 1697 break;
1698
1699 case CONTEXT_GROUP: // 1 to 1 to course
957861f7 1700 if (!$group = get_record('groups','id',$context->instanceid)) {
1701 return array();
1702 }
1703 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
1704 return array_merge(array($parent->id), get_parent_contexts($parent));
1705 } else {
1706 return array();
1707 }
bbbf2d40 1708 break;
1709
1710 case CONTEXT_MODULE: // 1 to 1 to course
957861f7 1711 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
1712 return array();
1713 }
1714 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
1715 return array_merge(array($parent->id), get_parent_contexts($parent));
1716 } else {
1717 return array();
1718 }
bbbf2d40 1719 break;
1720
1721 case CONTEXT_BLOCK: // 1 to 1 to course
957861f7 1722 if (!$block = get_record('block_instance','id',$context->instanceid)) {
1723 return array();
1724 }
1725 if ($parent = get_context_instance(CONTEXT_COURSE, $block->pageid)) {
1726 return array_merge(array($parent->id), get_parent_contexts($parent));
1727 } else {
1728 return array();
1729 }
bbbf2d40 1730 break;
1731
1732 default:
957861f7 1733 error('This is an unknown context!');
bbbf2d40 1734 return false;
1735 }
bbbf2d40 1736}
1737
1738
1739/**
1740 * This function gets the capability of a role in a given context.
1741 * It is needed when printing override forms.
1742 * @param int $contextid
bbbf2d40 1743 * @param string $capability
1744 * @param array $capabilities - array loaded using role_context_capabilities
1745 * @return int (allow, prevent, prohibit, inherit)
1746 */
bbbf2d40 1747function get_role_context_capability($contextid, $capability, $capabilities) {
98882637 1748 return $capabilities[$contextid][$capability];
bbbf2d40 1749}
1750
1751
cee0901c 1752/**
1753 * Returns the human-readable, translated version of the capability.
1754 * Basically a big switch statement.
1755 * @param $capabilityname - e.g. mod/choice:readresponses
1756 */
ceb83c70 1757function get_capability_string($capabilityname) {
bbbf2d40 1758
cee0901c 1759 // Typical capabilityname is mod/choice:readresponses
ceb83c70 1760
1761 $names = split('/', $capabilityname);
1762 $stringname = $names[1]; // choice:readresponses
1763 $components = split(':', $stringname);
1764 $componentname = $components[0]; // choice
98882637 1765
1766 switch ($names[0]) {
1767 case 'mod':
ceb83c70 1768 $string = get_string($stringname, $componentname);
98882637 1769 break;
1770
1771 case 'block':
ceb83c70 1772 $string = get_string($stringname, 'block_'.$componentname);
98882637 1773 break;
ceb83c70 1774
98882637 1775 case 'moodle':
ceb83c70 1776 $string = get_string($stringname, 'role');
98882637 1777 break;
1778
1779 case 'enrol':
ceb83c70 1780 $string = get_string($stringname, 'enrol_'.$componentname);
1781 break;
98882637 1782
1783 default:
ceb83c70 1784 $string = get_string($stringname);
98882637 1785 break;
98882637 1786
1787 }
ceb83c70 1788 return $string;
bbbf2d40 1789}
1790
1791
cee0901c 1792/**
1793 * This gets the mod/block/course/core etc strings.
1794 * @param $component
1795 * @param $contextlevel
1796 */
bbbf2d40 1797function get_component_string($component, $contextlevel) {
1798
98882637 1799 switch ($contextlevel) {
bbbf2d40 1800
98882637 1801 case CONTEXT_SYSTEM:
ceb83c70 1802 $string = get_string('coresystem');
bbbf2d40 1803 break;
1804
1805 case CONTEXT_PERSONAL:
98882637 1806 $string = get_string('personal');
bbbf2d40 1807 break;
1808
1809 case CONTEXT_USERID:
98882637 1810 $string = get_string('users');
bbbf2d40 1811 break;
1812
1813 case CONTEXT_COURSECAT:
98882637 1814 $string = get_string('categories');
bbbf2d40 1815 break;
1816
1817 case CONTEXT_COURSE:
98882637 1818 $string = get_string('course');
bbbf2d40 1819 break;
1820
1821 case CONTEXT_GROUP:
98882637 1822 $string = get_string('group');
bbbf2d40 1823 break;
1824
1825 case CONTEXT_MODULE:
98882637 1826 $string = get_string('modulename', basename($component));
bbbf2d40 1827 break;
1828
1829 case CONTEXT_BLOCK:
98882637 1830 $string = get_string('blockname', 'block_'.$component.'.php');
bbbf2d40 1831 break;
1832
1833 default:
1834 error ('This is an unknown context!');
1835 return false;
98882637 1836
1837 }
98882637 1838 return $string;
bbbf2d40 1839}
cee0901c 1840
945f88ca 1841/** gets the list of roles assigned to this context
1842 * @param object $context
1843 * @return array
1844 */
e4dd3222 1845function get_roles_used_in_context($context) {
1846
1847 global $CFG;
1848
1849 return get_records_sql('SELECT distinct r.id, r.name
1850 FROM '.$CFG->prefix.'role_assignments ra,
1851 '.$CFG->prefix.'role r
1852 WHERE r.id = ra.roleid
1853 AND ra.contextid = '.$context->id.'
1854 ORDER BY r.sortorder ASC');
1855}
1856
945f88ca 1857/** this function is used to print roles column in user profile page.
1858 * @param int userid
1859 * @param int contextid
1860 * @return string
1861 */
0a8a95c9 1862function get_user_roles_in_context($userid, $contextid){
1863 global $CFG;
1864
1865 $rolestring = '';
1866 $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';
1867 if ($roles = get_records_sql($SQL)) {
1868 foreach ($roles as $userrole) {
1869 $rolestring .= '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$userrole->contextid.'&amp;roleid='.$userrole->roleid.'">'.$userrole->name.'</a>, ';
1870 }
1871
1872 }
1873 return rtrim($rolestring, ', ');
1874}
68c52526 1875
1876
945f88ca 1877/**
1878 * Checks if a user can override capabilities of a particular role in this context
1879 * @param object $context
1880 * @param int targetroleid - the id of the role you want to override
1881 * @return boolean
1882 */
68c52526 1883function user_can_override($context, $targetroleid) {
1884 // first check if user has override capability
1885 // if not return false;
1886 if (!has_capability('moodle/role:override', $context)) {
1887 return false;
1888 }
1889 // pull out all active roles of this user from this context(or above)
c0614051 1890 if ($userroles = get_user_roles($context)) {
1891 foreach ($userroles as $userrole) {
1892 // if any in the role_allow_override table, then it's ok
1893 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
1894 return true;
1895 }
68c52526 1896 }
1897 }
1898
1899 return false;
1900
1901}
1902
945f88ca 1903/**
1904 * Checks if a user can assign users to a particular role in this context
1905 * @param object $context
1906 * @param int targetroleid - the id of the role you want to assign users to
1907 * @return boolean
1908 */
68c52526 1909function user_can_assign($context, $targetroleid) {
1910
1911 // first check if user has override capability
1912 // if not return false;
1913 if (!has_capability('moodle/role:assign', $context)) {
1914 return false;
1915 }
1916 // pull out all active roles of this user from this context(or above)
c0614051 1917 if ($userroles = get_user_roles($context)) {
1918 foreach ($userroles as $userrole) {
1919 // if any in the role_allow_override table, then it's ok
1920 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
1921 return true;
1922 }
68c52526 1923 }
1924 }
1925
1926 return false;
1927}
1928
945f88ca 1929/**
1930 * gets all the user roles assigned in this context, or higher contexts
1931 * this is mainly used when checking if a user can assign a role, or overriding a role
1932 * i.e. we need to know what this user holds, in order to verify against allow_assign and
1933 * allow_override tables
1934 * @param object $context
1935 * @param int $userid
1936 * @return array
1937 */
c0614051 1938function get_user_roles($context, $userid=0) {
68c52526 1939
1940 global $USER, $CFG, $db;
c0614051 1941
1942 if (empty($userid)) {
1943 if (empty($USER->id)) {
1944 return array();
1945 }
1946 $userid = $USER->id;
1947 }
1948
1949 if ($parents = get_parent_contexts($context)) {
1950 $contexts = ' AND ra.contextid IN ('.implode(',' , $parents).')';
1951 } else {
1952 $contexts = ' AND ra.contextid = \''.$context->id.'\'';
1953 }
1954
68c52526 1955 return get_records_sql('SELECT *
1956 FROM '.$CFG->prefix.'role_assignments ra
c0614051 1957 WHERE ra.userid = '.$userid.
1958 $contexts);
68c52526 1959}
1960
945f88ca 1961/**
1962 * Creates a record in the allow_override table
1963 * @param int sroleid - source roleid
1964 * @param int troleid - target roleid
1965 * @return int - id or false
1966 */
1967function allow_override($sroleid, $troleid) {
1968 $record->roleid = $sroleid;
1969 $record->allowoverride = $troleid;
1970 return insert_record('role_allow_override', $record);
1971}
1972
1973/**
1974 * Creates a record in the allow_assign table
1975 * @param int sroleid - source roleid
1976 * @param int troleid - target roleid
1977 * @return int - id or false
1978 */
1979function allow_assign($sroleid, $troleid) {
1980 $record->roleid = $sroleid;
1981 $record->allowassign = $troleid;
1982 return insert_record('role_allow_assign', $record);
1983}
1984
1985/**
1986 * gets a list of roles assignalbe in this context for this user
1987 * @param object $context
1988 * @return array
1989 */
1990function get_assignable_roles ($context) {
1991
1992 $role = get_records('role');
1993 $options = array();
1994 foreach ($role as $rolex) {
1995 if (user_can_assign($context, $rolex->id)) {
1996 $options[$rolex->id] = $rolex->name;
1997 }
1998 }
1999 return $options;
2000}
2001
2002/**
2003 * gets a list of roles that can be overriden in this context by this user
2004 * @param object $context
2005 * @return array
2006 */
2007function get_overridable_roles ($context) {
2008
2009 $role = get_records('role');
2010 $options = array();
2011 foreach ($role as $rolex) {
2012 if (user_can_override($context, $rolex->id)) {
2013 $options[$rolex->id] = $rolex->name;
2014 }
2015 }
2016
2017 return $options;
2018
2019}
1648afb2 2020
2021
2022/**
2023 * who has this capability in this context
2024 * does not handling user level resolving!!!
2025 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
2026 * @param $context - object
2027 * @param $capability - string capability
2028 * @param $fields - fields to be pulled
2029 * @param $sort - the sort order
04417640 2030 * @param $limitfrom - number of records to skip (offset)
2031 * @param $limitnum - number of records to fetch
1648afb2 2032 */
5de6e614 2033function get_users_by_capability($context, $capability, $fields='u.*', $sort='', $limitfrom='', $limitnum='') {
1648afb2 2034
2035 global $CFG;
2036
2037 // first get all roles with this capability in this context, or above
ec7a8b79 2038 $possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context);
1648afb2 2039 $validroleids = array();
2040 foreach ($possibleroles as $prole) {
2041 $caps = role_context_capabilities($prole->id, $context, $capability); // resolved list
2042 if ($caps[$capability] > 0) { // resolved capability > 0
2043 $validroleids[] = $prole->id;
2044 }
2045 }
2046
ec7a8b79 2047 /// the following few lines may not be needed
1648afb2 2048 if ($usercontexts = get_parent_contexts($context)) {
2049 $listofcontexts = '('.implode(',', $usercontexts).')';
2050 } else {
2051 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
2052 $listofcontexts = '('.$sitecontext->id.')'; // must be site
2053 }
2054
2055 $roleids = '('.implode(',', $validroleids).')';
2056
2057 $select = ' SELECT '.$fields;
2058 $from = ' FROM '.$CFG->prefix.'user u LEFT JOIN '.$CFG->prefix.'role_assignments ra ON ra.userid = u.id ';
ec7a8b79 2059 $where = ' WHERE (ra.contextid = '.$context->id.' OR ra.contextid in '.$listofcontexts.') AND u.deleted = 0 AND ra.roleid in '.$roleids.' ';
1648afb2 2060
04417640 2061 return get_records_sql($select.$from.$where.$sort, $limitfrom, $limitnum);
1648afb2 2062
2063}
7700027f 2064
1dc1f037 2065?>