Added some more stats to reports, added more actions to collapsed view and increased...
[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 }
ab5c9044 1438
1439 global $db;
1440 $db->debug= 999;
bbbf2d40 1441 // Do we need to assign the new capabilities to roles that have the
1442 // legacy capabilities moodle/legacy:* as well?
1443 if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
1444 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2e85fffe 1445 notify('Could not assign legacy capabilities for '.$capname);
bbbf2d40 1446 }
1447 }
1448 // Are there any capabilities that have been removed from the file
1449 // definition that we need to delete from the stored capabilities and
1450 // role assignments?
1451 capabilities_cleanup($component, $filecaps);
1452
1453 return true;
1454}
1455
1456
1457/**
1458 * Deletes cached capabilities that are no longer needed by the component.
1459 * Also unassigns these capabilities from any roles that have them.
1460 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1461 * @param $newcapdef - array of the new capability definitions that will be
1462 * compared with the cached capabilities
1463 * @return int - number of deprecated capabilities that have been removed
1464 */
1465function capabilities_cleanup($component, $newcapdef=NULL) {
1466
1467 $removedcount = 0;
1468
1469 if ($cachedcaps = get_cached_capabilities($component)) {
1470 foreach ($cachedcaps as $cachedcap) {
1471 if (empty($newcapdef) ||
1472 array_key_exists($cachedcap->name, $newcapdef) === false) {
1473
1474 // Remove from capabilities cache.
1475 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
1476 error('Could not delete deprecated capability '.$cachedcap->name);
1477 } else {
1478 $removedcount++;
1479 }
1480 // Delete from roles.
1481 if($roles = get_roles_with_capability($cachedcap->name)) {
1482 foreach($roles as $role) {
46943f7b 1483 if (!unassign_capability($cachedcap->name, $role->id)) {
bbbf2d40 1484 error('Could not unassign deprecated capability '.
1485 $cachedcap->name.' from role '.$role->name);
1486 }
1487 }
1488 }
1489 } // End if.
1490 }
1491 }
1492 return $removedcount;
1493}
1494
1495
1496
cee0901c 1497/****************
1498 * UI FUNCTIONS *
1499 ****************/
bbbf2d40 1500
1501
1502/**
1503 * prints human readable context identifier.
1504 */
0468976c 1505function print_context_name($context) {
340ea4e8 1506
ec0810ee 1507 $name = '';
d140ad3f 1508 switch ($context->aggregatelevel) {
ec0810ee 1509
bbbf2d40 1510 case CONTEXT_SYSTEM: // by now it's a definite an inherit
ec0810ee 1511 $name = get_string('site');
340ea4e8 1512 break;
bbbf2d40 1513
1514 case CONTEXT_PERSONAL:
ec0810ee 1515 $name = get_string('personal');
340ea4e8 1516 break;
1517
bbbf2d40 1518 case CONTEXT_USERID:
ec0810ee 1519 if ($user = get_record('user', 'id', $context->instanceid)) {
1520 $name = get_string('user').': '.fullname($user);
1521 }
340ea4e8 1522 break;
1523
bbbf2d40 1524 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
ec0810ee 1525 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
1526 $name = get_string('category').': '.$category->name;
1527 }
340ea4e8 1528 break;
bbbf2d40 1529
1530 case CONTEXT_COURSE: // 1 to 1 to course cat
ec0810ee 1531 if ($course = get_record('course', 'id', $context->instanceid)) {
1532 $name = get_string('course').': '.$course->fullname;
1533 }
340ea4e8 1534 break;
bbbf2d40 1535
1536 case CONTEXT_GROUP: // 1 to 1 to course
ec0810ee 1537 if ($group = get_record('groups', 'id', $context->instanceid)) {
1538 $name = get_string('group').': '.$group->name;
1539 }
340ea4e8 1540 break;
bbbf2d40 1541
1542 case CONTEXT_MODULE: // 1 to 1 to course
98882637 1543 if ($cm = get_record('course_modules','id',$context->instanceid)) {
1544 if ($module = get_record('modules','id',$cm->module)) {
1545 if ($mod = get_record($module->name, 'id', $cm->instance)) {
ec0810ee 1546 $name = get_string('activitymodule').': '.$mod->name;
98882637 1547 }
ec0810ee 1548 }
1549 }
340ea4e8 1550 break;
bbbf2d40 1551
1552 case CONTEXT_BLOCK: // 1 to 1 to course
98882637 1553 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
1554 if ($block = get_record('block','id',$blockinstance->blockid)) {
91be52d7 1555 global $CFG;
1556 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
1557 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
1558 $blockname = "block_$block->name";
1559 if ($blockobject = new $blockname()) {
1560 $name = $blockobject->title.' ('.get_string('block').')';
1561 }
ec0810ee 1562 }
1563 }
340ea4e8 1564 break;
bbbf2d40 1565
1566 default:
1567 error ('This is an unknown context!');
340ea4e8 1568 return false;
1569
1570 }
340ea4e8 1571 return $name;
bbbf2d40 1572}
1573
1574
1575/**
1576 * Extracts the relevant capabilities given a contextid.
1577 * All case based, example an instance of forum context.
1578 * Will fetch all forum related capabilities, while course contexts
1579 * Will fetch all capabilities
0468976c 1580 * @param object context
bbbf2d40 1581 * @return array();
1582 *
1583 * capabilities
1584 * `name` varchar(150) NOT NULL,
1585 * `captype` varchar(50) NOT NULL,
1586 * `contextlevel` int(10) NOT NULL,
1587 * `component` varchar(100) NOT NULL,
1588 */
0468976c 1589function fetch_context_capabilities($context) {
98882637 1590
1591 global $CFG;
bbbf2d40 1592
1593 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
98882637 1594
d140ad3f 1595 switch ($context->aggregatelevel) {
bbbf2d40 1596
98882637 1597 case CONTEXT_SYSTEM: // all
1598 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1599 break;
1600
1601 case CONTEXT_PERSONAL:
0a8a95c9 1602 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
bbbf2d40 1603 break;
1604
1605 case CONTEXT_USERID:
0a8a95c9 1606 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_USERID;
bbbf2d40 1607 break;
1608
1609 case CONTEXT_COURSECAT: // all
98882637 1610 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1611 break;
1612
1613 case CONTEXT_COURSE: // all
98882637 1614 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1615 break;
1616
1617 case CONTEXT_GROUP: // group caps
1618 break;
1619
1620 case CONTEXT_MODULE: // mod caps
98882637 1621 $cm = get_record('course_modules', 'id', $context->instanceid);
1622 $module = get_record('modules', 'id', $cm->module);
bbbf2d40 1623
98882637 1624 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
1625 and component = 'mod/$module->name'";
bbbf2d40 1626 break;
1627
1628 case CONTEXT_BLOCK: // block caps
98882637 1629 $cb = get_record('block_instance', 'id', $context->instanceid);
1630 $block = get_record('block', 'id', $cb->blockid);
bbbf2d40 1631
98882637 1632 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
1633 and component = 'block/$block->name'";
bbbf2d40 1634 break;
1635
1636 default:
1637 return false;
1638 }
1639
1640 $records = get_records_sql($SQL.' '.$sort);
69eb59f2 1641
1642 // special sorting of core system capabiltites and enrollments
1643 if ($context->aggregatelevel == CONTEXT_SYSTEM) {
1644 $first = array();
1645 foreach ($records as $key=>$record) {
1646 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
1647 $first[$key] = $record;
1648 unset($records[$key]);
1649 } else if (count($first)){
1650 break;
1651 }
1652 }
1653 if (count($first)) {
1654 $records = $first + $records; // merge the two arrays keeping the keys
1655 }
1656 }
1657 // end of special sorting
1658
bbbf2d40 1659 return $records;
1660
1661}
1662
1663
1664/**
1665 * This function pulls out all the resolved capabilities (overrides and
1666 * defaults) of a role used in capability overrieds in contexts at a given
1667 * context.
0a8a95c9 1668 * @param obj $context
bbbf2d40 1669 * @param int $roleid
1670 * @return array
1671 */
1648afb2 1672function role_context_capabilities($roleid, $context, $cap='') {
98882637 1673 global $CFG;
1674
1675 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
0468976c 1676 if ($sitecontext->id == $context->id) {
20aeb4b8 1677 $contexts = array($sitecontext->id);
1678 } else {
1679 // first of all, figure out all parental contexts
1680 $contexts = array_reverse(get_parent_contexts($context));
98882637 1681 }
98882637 1682 $contexts = '('.implode(',', $contexts).')';
1683
1648afb2 1684 if ($cap) {
e4697bf7 1685 $search = " AND rc.capability = '$cap' ";
1648afb2 1686 } else {
1687 $search = '';
1688 }
1689
98882637 1690 $SQL = "SELECT rc.* FROM {$CFG->prefix}role_capabilities rc, {$CFG->prefix}context c
1691 where rc.contextid in $contexts
1692 and rc.roleid = $roleid
1648afb2 1693 and rc.contextid = c.id $search
d140ad3f 1694 ORDER BY c.aggregatelevel DESC, rc.capability DESC";
1648afb2 1695
98882637 1696 $capabilities = array();
1697
4729012f 1698 if ($records = get_records_sql($SQL)) {
1699 // We are traversing via reverse order.
1700 foreach ($records as $record) {
1701 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
1702 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
1703 $capabilities[$record->capability] = $record->permission;
1704 }
1705 }
98882637 1706 }
1707 return $capabilities;
bbbf2d40 1708}
1709
1710
1711/**
0468976c 1712 * Recursive function which, given a context, find all parent context ids,
bbbf2d40 1713 * and return the array in reverse order, i.e. parent first, then grand
1714 * parent, etc.
1715 * @param object $context
1716 * @return array()
1717 */
bbbf2d40 1718function get_parent_contexts($context) {
1719
d140ad3f 1720 switch ($context->aggregatelevel) {
bbbf2d40 1721
1722 case CONTEXT_SYSTEM: // no parent
957861f7 1723 return array();
bbbf2d40 1724 break;
1725
1726 case CONTEXT_PERSONAL:
957861f7 1727 if (!$parent = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
1728 return array();
1729 } else {
1730 return array($parent->id);
1731 }
bbbf2d40 1732 break;
1733
1734 case CONTEXT_USERID:
957861f7 1735 if (!$parent = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
1736 return array();
1737 } else {
1738 return array($parent->id);
1739 }
bbbf2d40 1740 break;
1741
1742 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
957861f7 1743 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
1744 return array();
1745 }
c5ddc3fd 1746 if (!empty($coursecat->parent)) { // return parent value if exist
bbbf2d40 1747 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
1748 return array_merge(array($parent->id), get_parent_contexts($parent));
1749 } else { // else return site value
1750 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
1751 return array($parent->id);
1752 }
1753 break;
1754
1755 case CONTEXT_COURSE: // 1 to 1 to course cat
957861f7 1756 if (!$course = get_record('course','id',$context->instanceid)) {
1757 return array();
1758 }
1759 if (!empty($course->category)) {
1760 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
1761 return array_merge(array($parent->id), get_parent_contexts($parent));
1762 } else {
1763 return array();
1764 }
bbbf2d40 1765 break;
1766
1767 case CONTEXT_GROUP: // 1 to 1 to course
957861f7 1768 if (!$group = get_record('groups','id',$context->instanceid)) {
1769 return array();
1770 }
1771 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
1772 return array_merge(array($parent->id), get_parent_contexts($parent));
1773 } else {
1774 return array();
1775 }
bbbf2d40 1776 break;
1777
1778 case CONTEXT_MODULE: // 1 to 1 to course
957861f7 1779 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
1780 return array();
1781 }
1782 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
1783 return array_merge(array($parent->id), get_parent_contexts($parent));
1784 } else {
1785 return array();
1786 }
bbbf2d40 1787 break;
1788
1789 case CONTEXT_BLOCK: // 1 to 1 to course
957861f7 1790 if (!$block = get_record('block_instance','id',$context->instanceid)) {
1791 return array();
1792 }
1793 if ($parent = get_context_instance(CONTEXT_COURSE, $block->pageid)) {
1794 return array_merge(array($parent->id), get_parent_contexts($parent));
1795 } else {
1796 return array();
1797 }
bbbf2d40 1798 break;
1799
1800 default:
957861f7 1801 error('This is an unknown context!');
bbbf2d40 1802 return false;
1803 }
bbbf2d40 1804}
1805
1806
1807/**
1808 * This function gets the capability of a role in a given context.
1809 * It is needed when printing override forms.
1810 * @param int $contextid
bbbf2d40 1811 * @param string $capability
1812 * @param array $capabilities - array loaded using role_context_capabilities
1813 * @return int (allow, prevent, prohibit, inherit)
1814 */
bbbf2d40 1815function get_role_context_capability($contextid, $capability, $capabilities) {
98882637 1816 return $capabilities[$contextid][$capability];
bbbf2d40 1817}
1818
1819
cee0901c 1820/**
1821 * Returns the human-readable, translated version of the capability.
1822 * Basically a big switch statement.
1823 * @param $capabilityname - e.g. mod/choice:readresponses
1824 */
ceb83c70 1825function get_capability_string($capabilityname) {
ae9e4c06 1826
cee0901c 1827 // Typical capabilityname is mod/choice:readresponses
ceb83c70 1828
1829 $names = split('/', $capabilityname);
1830 $stringname = $names[1]; // choice:readresponses
1831 $components = split(':', $stringname);
1832 $componentname = $components[0]; // choice
98882637 1833
1834 switch ($names[0]) {
1835 case 'mod':
ceb83c70 1836 $string = get_string($stringname, $componentname);
98882637 1837 break;
1838
1839 case 'block':
ceb83c70 1840 $string = get_string($stringname, 'block_'.$componentname);
98882637 1841 break;
ceb83c70 1842
98882637 1843 case 'moodle':
ceb83c70 1844 $string = get_string($stringname, 'role');
98882637 1845 break;
1846
1847 case 'enrol':
ceb83c70 1848 $string = get_string($stringname, 'enrol_'.$componentname);
1849 break;
98882637 1850
1851 default:
ceb83c70 1852 $string = get_string($stringname);
98882637 1853 break;
98882637 1854
1855 }
ceb83c70 1856 return $string;
bbbf2d40 1857}
1858
1859
cee0901c 1860/**
1861 * This gets the mod/block/course/core etc strings.
1862 * @param $component
1863 * @param $contextlevel
1864 */
bbbf2d40 1865function get_component_string($component, $contextlevel) {
1866
98882637 1867 switch ($contextlevel) {
bbbf2d40 1868
98882637 1869 case CONTEXT_SYSTEM:
be382aaf 1870 if (preg_match('|^enrol/|', $component)) {
1871 $langname = str_replace('/', '_', $component);
1872 $string = get_string('enrolname', $langname);
69eb59f2 1873 } else {
1874 $string = get_string('coresystem');
1875 }
bbbf2d40 1876 break;
1877
1878 case CONTEXT_PERSONAL:
98882637 1879 $string = get_string('personal');
bbbf2d40 1880 break;
1881
1882 case CONTEXT_USERID:
98882637 1883 $string = get_string('users');
bbbf2d40 1884 break;
1885
1886 case CONTEXT_COURSECAT:
98882637 1887 $string = get_string('categories');
bbbf2d40 1888 break;
1889
1890 case CONTEXT_COURSE:
98882637 1891 $string = get_string('course');
bbbf2d40 1892 break;
1893
1894 case CONTEXT_GROUP:
98882637 1895 $string = get_string('group');
bbbf2d40 1896 break;
1897
1898 case CONTEXT_MODULE:
98882637 1899 $string = get_string('modulename', basename($component));
bbbf2d40 1900 break;
1901
1902 case CONTEXT_BLOCK:
98882637 1903 $string = get_string('blockname', 'block_'.$component.'.php');
bbbf2d40 1904 break;
1905
1906 default:
1907 error ('This is an unknown context!');
1908 return false;
98882637 1909
1910 }
98882637 1911 return $string;
bbbf2d40 1912}
cee0901c 1913
945f88ca 1914/** gets the list of roles assigned to this context
1915 * @param object $context
1916 * @return array
1917 */
e4dd3222 1918function get_roles_used_in_context($context) {
1919
1920 global $CFG;
1921
1922 return get_records_sql('SELECT distinct r.id, r.name
1923 FROM '.$CFG->prefix.'role_assignments ra,
1924 '.$CFG->prefix.'role r
1925 WHERE r.id = ra.roleid
1926 AND ra.contextid = '.$context->id.'
1927 ORDER BY r.sortorder ASC');
1928}
1929
945f88ca 1930/** this function is used to print roles column in user profile page.
1931 * @param int userid
1932 * @param int contextid
1933 * @return string
1934 */
0a8a95c9 1935function get_user_roles_in_context($userid, $contextid){
1936 global $CFG;
1937
1938 $rolestring = '';
1939 $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';
1940 if ($roles = get_records_sql($SQL)) {
1941 foreach ($roles as $userrole) {
1942 $rolestring .= '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$userrole->contextid.'&amp;roleid='.$userrole->roleid.'">'.$userrole->name.'</a>, ';
1943 }
1944
1945 }
1946 return rtrim($rolestring, ', ');
1947}
68c52526 1948
1949
945f88ca 1950/**
1951 * Checks if a user can override capabilities of a particular role in this context
1952 * @param object $context
1953 * @param int targetroleid - the id of the role you want to override
1954 * @return boolean
1955 */
68c52526 1956function user_can_override($context, $targetroleid) {
1957 // first check if user has override capability
1958 // if not return false;
1959 if (!has_capability('moodle/role:override', $context)) {
1960 return false;
1961 }
1962 // pull out all active roles of this user from this context(or above)
c0614051 1963 if ($userroles = get_user_roles($context)) {
1964 foreach ($userroles as $userrole) {
1965 // if any in the role_allow_override table, then it's ok
1966 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
1967 return true;
1968 }
68c52526 1969 }
1970 }
1971
1972 return false;
1973
1974}
1975
945f88ca 1976/**
1977 * Checks if a user can assign users to a particular role in this context
1978 * @param object $context
1979 * @param int targetroleid - the id of the role you want to assign users to
1980 * @return boolean
1981 */
68c52526 1982function user_can_assign($context, $targetroleid) {
1983
1984 // first check if user has override capability
1985 // if not return false;
1986 if (!has_capability('moodle/role:assign', $context)) {
1987 return false;
1988 }
1989 // pull out all active roles of this user from this context(or above)
c0614051 1990 if ($userroles = get_user_roles($context)) {
1991 foreach ($userroles as $userrole) {
1992 // if any in the role_allow_override table, then it's ok
1993 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
1994 return true;
1995 }
68c52526 1996 }
1997 }
1998
1999 return false;
2000}
2001
945f88ca 2002/**
2003 * gets all the user roles assigned in this context, or higher contexts
2004 * this is mainly used when checking if a user can assign a role, or overriding a role
2005 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2006 * allow_override tables
2007 * @param object $context
2008 * @param int $userid
2009 * @return array
2010 */
c0614051 2011function get_user_roles($context, $userid=0) {
68c52526 2012
2013 global $USER, $CFG, $db;
c0614051 2014
2015 if (empty($userid)) {
2016 if (empty($USER->id)) {
2017 return array();
2018 }
2019 $userid = $USER->id;
2020 }
2021
2022 if ($parents = get_parent_contexts($context)) {
2023 $contexts = ' AND ra.contextid IN ('.implode(',' , $parents).')';
2024 } else {
2025 $contexts = ' AND ra.contextid = \''.$context->id.'\'';
2026 }
2027
68c52526 2028 return get_records_sql('SELECT *
2029 FROM '.$CFG->prefix.'role_assignments ra
c0614051 2030 WHERE ra.userid = '.$userid.
2031 $contexts);
68c52526 2032}
2033
945f88ca 2034/**
2035 * Creates a record in the allow_override table
2036 * @param int sroleid - source roleid
2037 * @param int troleid - target roleid
2038 * @return int - id or false
2039 */
2040function allow_override($sroleid, $troleid) {
2041 $record->roleid = $sroleid;
2042 $record->allowoverride = $troleid;
2043 return insert_record('role_allow_override', $record);
2044}
2045
2046/**
2047 * Creates a record in the allow_assign table
2048 * @param int sroleid - source roleid
2049 * @param int troleid - target roleid
2050 * @return int - id or false
2051 */
2052function allow_assign($sroleid, $troleid) {
2053 $record->roleid = $sroleid;
2054 $record->allowassign = $troleid;
2055 return insert_record('role_allow_assign', $record);
2056}
2057
2058/**
2059 * gets a list of roles assignalbe in this context for this user
2060 * @param object $context
2061 * @return array
2062 */
2063function get_assignable_roles ($context) {
2064
2065 $role = get_records('role');
2066 $options = array();
2067 foreach ($role as $rolex) {
2068 if (user_can_assign($context, $rolex->id)) {
2069 $options[$rolex->id] = $rolex->name;
2070 }
2071 }
2072 return $options;
2073}
2074
2075/**
2076 * gets a list of roles that can be overriden in this context by this user
2077 * @param object $context
2078 * @return array
2079 */
2080function get_overridable_roles ($context) {
2081
2082 $role = get_records('role');
2083 $options = array();
2084 foreach ($role as $rolex) {
2085 if (user_can_override($context, $rolex->id)) {
2086 $options[$rolex->id] = $rolex->name;
2087 }
2088 }
2089
2090 return $options;
2091
2092}
1648afb2 2093
2094
2095/**
2096 * who has this capability in this context
2097 * does not handling user level resolving!!!
2098 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
2099 * @param $context - object
2100 * @param $capability - string capability
2101 * @param $fields - fields to be pulled
2102 * @param $sort - the sort order
04417640 2103 * @param $limitfrom - number of records to skip (offset)
2104 * @param $limitnum - number of records to fetch
1c45e42e 2105 * @param $groups - single group or array of groups - group(s) user is in
1648afb2 2106 */
1c45e42e 2107function get_users_by_capability($context, $capability, $fields='u.*', $sort='', $limitfrom='', $limitnum='', $groups='') {
1648afb2 2108
2109 global $CFG;
2110
1c45e42e 2111 if ($groups) {
2112
2113 $groupjoin = 'LEFT JOIN '.$CFG->prefix.'groups_members gm ON gm.userid = ra.userid';
2114
2115 if (is_array($groups)) {
2116 $groupsql = 'AND gm.id IN ('.implode(',', $groups).')';
2117 } else {
2118 $groupsql = 'AND gm.id = '.$groups;
2119 }
2120 } else {
2121 $groupjoin = '';
2122 $groupsql = '';
2123 }
2124
1648afb2 2125 // first get all roles with this capability in this context, or above
ec7a8b79 2126 $possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context);
1648afb2 2127 $validroleids = array();
2128 foreach ($possibleroles as $prole) {
2129 $caps = role_context_capabilities($prole->id, $context, $capability); // resolved list
2130 if ($caps[$capability] > 0) { // resolved capability > 0
2131 $validroleids[] = $prole->id;
2132 }
2133 }
2134
ec7a8b79 2135 /// the following few lines may not be needed
1648afb2 2136 if ($usercontexts = get_parent_contexts($context)) {
2137 $listofcontexts = '('.implode(',', $usercontexts).')';
2138 } else {
2139 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
2140 $listofcontexts = '('.$sitecontext->id.')'; // must be site
2141 }
2142
2143 $roleids = '('.implode(',', $validroleids).')';
2144
2145 $select = ' SELECT '.$fields;
1c45e42e 2146 $from = ' FROM '.$CFG->prefix.'user u LEFT JOIN '.$CFG->prefix.'role_assignments ra ON ra.userid = u.id '.$groupjoin;
2147 $where = ' WHERE (ra.contextid = '.$context->id.' OR ra.contextid in '.$listofcontexts.') AND u.deleted = 0 AND ra.roleid in '.$roleids.' '.$groupsql;
1648afb2 2148
04417640 2149 return get_records_sql($select.$from.$where.$sort, $limitfrom, $limitnum);
1648afb2 2150
2151}
7700027f 2152
ab5c9044 2153/**
2154 * gets all the users assigned this role in this context or higher
2155 * @param int roleid
2156 * @param int contextid
2157 * @param bool parent if true, get list of users assigned in higher context too
2158 * @return array()
2159 */
2160function get_role_users($roleid, $context, $parent=false) {
2161 global $CFG;
2162
2163 if ($parent) {
2164 if ($contexts = get_parent_contexts($context)) {
2165 $parentcontexts = 'r.contextid IN ('.implode(',', $contexts).')';
2166 } else {
2167 $parentcontexts = '';
2168 }
2169 } else {
2170 $parentcontexts = '';
2171 }
2172
2173 $SQL = "select u.*
2174 from {$CFG->prefix}role_assignments r,
2175 {$CFG->prefix}user u
2176 where (r.contextid = $context->id $parentcontexts)
2177 and r.roleid = $roleid
2178 and u.id = r.userid"; // join now so that we can just use fullname() later
2179
2180 return get_records_sql($SQL);
2181}
2182
1dc1f037 2183?>