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