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