major whitespace cleanup - fixed tabs
[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
e49e61bf 18define('CAP_INHERIT', 0);
bbbf2d40 19define('CAP_ALLOW', 1);
20define('CAP_PREVENT', -1);
21define('CAP_PROHIBIT', -1000);
22
bbbf2d40 23// context definitions
24define('CONTEXT_SYSTEM', 10);
25define('CONTEXT_PERSONAL', 20);
4b10f08b 26define('CONTEXT_USER', 30);
bbbf2d40 27define('CONTEXT_COURSECAT', 40);
28define('CONTEXT_COURSE', 50);
29define('CONTEXT_GROUP', 60);
30define('CONTEXT_MODULE', 70);
31define('CONTEXT_BLOCK', 80);
32
21b6db6e 33// capability risks - see http://docs.moodle.org/en/Hardening_new_Roles_system
34define('RISK_MANAGETRUST', 0x0001);
a6b02b65 35define('RISK_CONFIG', 0x0002);
21b6db6e 36define('RISK_XSS', 0x0004);
37define('RISK_PERSONAL', 0x0008);
38define('RISK_SPAM', 0x0010);
39
40
340ea4e8 41$context_cache = array(); // Cache of all used context objects for performance (by level and instance)
42$context_cache_id = array(); // Index to above cache by id
bbbf2d40 43
7700027f 44
e7876c1e 45/**
46 * Loads the capabilities for the default guest role to the current user in a specific context
47 * @return object
48 */
49function load_guest_role($context=NULL) {
50 global $USER;
51
52 static $guestrole;
53
54 if (!isloggedin()) {
55 return false;
56 }
57
58 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
59 return false;
60 }
61
62 if (empty($context)) {
63 $context = $sitecontext;
64 }
65
66 if (empty($guestrole)) {
8f8ed475 67 if (!$guestrole = get_guest_role()) {
e7876c1e 68 return false;
69 }
70 }
71
72 if ($capabilities = get_records_select('role_capabilities',
73 "roleid = $guestrole->id AND contextid = $sitecontext->id")) {
74 foreach ($capabilities as $capability) {
75 $USER->capabilities[$context->id][$capability->capability] = $capability->permission;
76 }
77 }
78
79 return true;
80}
81
7700027f 82/**
83 * Load default not logged in role capabilities when user is not logged in
84 * @return bool
85 */
20aeb4b8 86function load_notloggedin_role() {
87 global $CFG, $USER;
88
7700027f 89 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
90 return false;
35a518c5 91 }
92
7700027f 93 if (empty($CFG->notloggedinroleid)) { // Let's set the default to the guest role
8f8ed475 94 if ($role = get_guest_role()) {
7700027f 95 set_config('notloggedinroleid', $role->id);
96 } else {
97 return false;
98 }
99 }
20aeb4b8 100
7700027f 101 if ($capabilities = get_records_select('role_capabilities',
102 "roleid = $CFG->notloggedinroleid AND contextid = $sitecontext->id")) {
103 foreach ($capabilities as $capability) {
104 $USER->capabilities[$sitecontext->id][$capability->capability] = $capability->permission;
105 }
20aeb4b8 106 }
107
108 return true;
109}
cee0901c 110
8f8ed475 111/**
112 * Load default not logged in role capabilities when user is not logged in
113 * @return bool
114 */
115function load_defaultuser_role() {
116 global $CFG, $USER;
117
118 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
119 return false;
120 }
121
122 if (empty($CFG->defaultuserroleid)) { // Let's set the default to the guest role
123 if ($role = get_guest_role()) {
124 set_config('defaultuserroleid', $role->id);
125 } else {
126 return false;
127 }
128 }
129
130 if ($capabilities = get_records_select('role_capabilities',
131 "roleid = $CFG->defaultuserroleid AND contextid = $sitecontext->id")) {
132 foreach ($capabilities as $capability) {
ca23ffdb 133 if (!isset($USER->capabilities[$sitecontext->id][$capability->capability])) { // Don't overwrite
134 $USER->capabilities[$sitecontext->id][$capability->capability] = $capability->permission;
135 }
8f8ed475 136 }
137
138 // SPECIAL EXCEPTION: If the default user role is actually a guest role, then
139 // remove some capabilities so this user doesn't get confused with a REAL guest
2f089dd5 140 if (isset($USER->capabilities[$sitecontext->id]['moodle/legacy:guest']) and $USER->username != 'guest') {
8f8ed475 141 unset($USER->capabilities[$sitecontext->id]['moodle/legacy:guest']);
142 unset($USER->capabilities[$sitecontext->id]['moodle/course:view']); // No access to courses by default
143 }
144 }
145
146 return true;
147}
148
149
150/**
151 * Get the default guest role
152 * @return object role
153 */
154function get_guest_role() {
155 if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
156 return array_shift($roles); // Pick the first one
157 } else {
158 return false;
159 }
160}
161
162
bbbf2d40 163/**
164 * This functions get all the course categories in proper order
0468976c 165 * @param int $context
bbbf2d40 166 * @param int $type
167 * @return array of contextids
168 */
0468976c 169function get_parent_cats($context, $type) {
98882637 170
171 $parents = array();
98882637 172
c5ddc3fd 173 switch ($type) {
98882637 174 case CONTEXT_COURSECAT:
c5ddc3fd 175 if (!$cat = get_record('course_categories','id',$context->instanceid)) {
176 break;
177 }
178
179 while (!empty($cat->parent)) {
180 if (!$context = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
181 break;
182 }
98882637 183 $parents[] = $context->id;
184 $cat = get_record('course_categories','id',$cat->parent);
185 }
98882637 186 break;
187
188 case CONTEXT_COURSE:
c5ddc3fd 189 if (!$course = get_record('course', 'id', $context->instanceid)) {
190 break;
191 }
192 if (!$catinstance = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
193 break;
194 }
195
98882637 196 $parents[] = $catinstance->id;
c5ddc3fd 197
198 if (!$cat = get_record('course_categories','id',$course->category)) {
199 break;
200 }
201
202 while (!empty($cat->parent)) {
203 if (!$context = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
204 break;
205 }
98882637 206 $parents[] = $context->id;
207 $cat = get_record('course_categories','id',$cat->parent);
208 }
209 break;
210
211 default:
212 break;
98882637 213 }
98882637 214 return array_reverse($parents);
bbbf2d40 215}
216
217
cee0901c 218
0468976c 219/**
220 * This function checks for a capability assertion being true. If it isn't
221 * then the page is terminated neatly with a standard error message
222 * @param string $capability - name of the capability
223 * @param object $context - a context object (record from context table)
224 * @param integer $userid - a userid number
d74067e8 225 * @param bool $doanything - if false, ignore do anything
0468976c 226 * @param string $errorstring - an errorstring
d74067e8 227 * @param string $stringfile - which stringfile to get it from
0468976c 228 */
d74067e8 229function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
230 $errormessage="nopermissions", $stringfile='') {
a9e1c058 231
232 global $USER;
233
234/// If the current user is not logged in, then make sure they are
235
236 if (empty($userid) and empty($USER->id)) {
237 if ($context && ($context->aggregatelevel == CONTEXT_COURSE)) {
238 require_login($context->instanceid);
239 } else {
240 require_login();
241 }
242 }
243
244/// OK, if they still don't have the capability then print a nice error message
245
d74067e8 246 if (!has_capability($capability, $context, $userid, $doanything)) {
0468976c 247 $capabilityname = get_capability_string($capability);
248 print_error($errormessage, $stringfile, '', $capabilityname);
249 }
250}
251
252
bbbf2d40 253/**
254 * This function returns whether the current user has the capability of performing a function
255 * For example, we can do has_capability('mod/forum:replypost',$cm) in forum
256 * only one of the 4 (moduleinstance, courseid, site, userid) would be set at 1 time
257 * This is a recursive funciton.
bbbf2d40 258 * @uses $USER
259 * @param string $capability - name of the capability
0468976c 260 * @param object $context - a context object (record from context table)
261 * @param integer $userid - a userid number
20aeb4b8 262 * @param bool $doanything - if false, ignore do anything
bbbf2d40 263 * @return bool
264 */
d74067e8 265function has_capability($capability, $context=NULL, $userid=NULL, $doanything=true) {
bbbf2d40 266
20aeb4b8 267 global $USER, $CONTEXT, $CFG;
bbbf2d40 268
a8a7300a 269 if (debugging() && !record_exists('capabilities', 'name', $capability)) {
7f7cacdf 270 debugging('Cabability "'.$capability.'" was not found! This should be fixed in code.');
a8a7300a 271 }
272
8f8ed475 273 if (empty($userid) && empty($USER->capabilities)) { // Real user, first time here
274 if (isloggedin()) {
275 load_defaultuser_role(); // All users get this by default
276 } else {
277 load_notloggedin_role(); // others get this by default
278 }
20aeb4b8 279 }
280
281 if ($userid && $userid != $USER->id) {
9425b25f 282 if (empty($USER->id) or ($userid != $USER->id)) {
283 $capabilities = load_user_capability($capability, $context, $userid);
284 } else { //$USER->id == $userid
285 $capabilities = empty($USER->capabilities) ? NULL : $USER->capabilities;
286 }
287 } else { // no userid
288 $capabilities = empty($USER->capabilities) ? NULL : $USER->capabilities;
98882637 289 }
9425b25f 290
0468976c 291 if (empty($context)) { // Use default CONTEXT if none specified
340ea4e8 292 if (empty($CONTEXT)) {
293 return false;
294 } else {
295 $context = $CONTEXT;
296 }
0468976c 297 } else { // A context was given to us
298 if (empty($CONTEXT)) {
299 $CONTEXT = $context; // Store FIRST used context in this global as future default
300 }
340ea4e8 301 }
bbbf2d40 302
20aeb4b8 303 if ($doanything) {
304 // Check site
305 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
306 if (isset($capabilities[$sitecontext->id]['moodle/site:doanything'])) {
307 return (0 < $capabilities[$sitecontext->id]['moodle/site:doanything']);
308 }
98882637 309
20aeb4b8 310 switch ($context->aggregatelevel) {
bbbf2d40 311
20aeb4b8 312 case CONTEXT_COURSECAT:
313 // Check parent cats.
314 $parentcats = get_parent_cats($context, CONTEXT_COURSECAT);
315 foreach ($parentcats as $parentcat) {
316 if (isset($capabilities[$parentcat]['moodle/site:doanything'])) {
317 return (0 < $capabilities[$parentcat]['moodle/site:doanything']);
318 }
cee0901c 319 }
20aeb4b8 320 break;
bbbf2d40 321
20aeb4b8 322 case CONTEXT_COURSE:
323 // Check parent cat.
324 $parentcats = get_parent_cats($context, CONTEXT_COURSE);
98882637 325
20aeb4b8 326 foreach ($parentcats as $parentcat) {
327 if (isset($capabilities[$parentcat]['do_anything'])) {
328 return (0 < $capabilities[$parentcat]['do_anything']);
329 }
9425b25f 330 }
20aeb4b8 331 break;
bbbf2d40 332
20aeb4b8 333 case CONTEXT_GROUP:
334 // Find course.
335 $group = get_record('groups','id',$context->instanceid);
336 $courseinstance = get_context_instance(CONTEXT_COURSE, $group->courseid);
9425b25f 337
20aeb4b8 338 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE);
339 foreach ($parentcats as $parentcat) {
340 if (isset($capabilities[$parentcat->id]['do_anything'])) {
341 return (0 < $capabilities[$parentcat->id]['do_anything']);
342 }
9425b25f 343 }
9425b25f 344
20aeb4b8 345 $coursecontext = '';
346 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
347 return (0 < $capabilities[$courseinstance->id]['do_anything']);
348 }
9425b25f 349
20aeb4b8 350 break;
bbbf2d40 351
20aeb4b8 352 case CONTEXT_MODULE:
353 // Find course.
354 $cm = get_record('course_modules', 'id', $context->instanceid);
355 $courseinstance = get_context_instance(CONTEXT_COURSE, $cm->course);
9425b25f 356
20aeb4b8 357 if ($parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE)) {
358 foreach ($parentcats as $parentcat) {
359 if (isset($capabilities[$parentcat]['do_anything'])) {
360 return (0 < $capabilities[$parentcat]['do_anything']);
361 }
cee0901c 362 }
9425b25f 363 }
98882637 364
20aeb4b8 365 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
366 return (0 < $capabilities[$courseinstance->id]['do_anything']);
367 }
bbbf2d40 368
20aeb4b8 369 break;
bbbf2d40 370
20aeb4b8 371 case CONTEXT_BLOCK:
372 // 1 to 1 to course.
373 // Find course.
374 $block = get_record('block_instance','id',$context->instanceid);
375 $courseinstance = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
9425b25f 376
20aeb4b8 377 $parentcats = get_parent_cats($courseinstance, CONTEXT_COURSE);
378 foreach ($parentcats as $parentcat) {
379 if (isset($capabilities[$parentcat]['do_anything'])) {
380 return (0 < $capabilities[$parentcat]['do_anything']);
381 }
cee0901c 382 }
9425b25f 383
20aeb4b8 384 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
385 return (0 < $capabilities[$courseinstance->id]['do_anything']);
386 }
387 break;
bbbf2d40 388
20aeb4b8 389 default:
4b10f08b 390 // CONTEXT_SYSTEM: CONTEXT_PERSONAL: CONTEXT_USER:
20aeb4b8 391 // Do nothing.
392 break;
393 }
bbbf2d40 394
20aeb4b8 395 // Last: check self.
396 if (isset($capabilities[$context->id]['do_anything'])) {
397 return (0 < $capabilities[$context->id]['do_anything']);
398 }
98882637 399 }
98882637 400 // do_anything has not been set, we now look for it the normal way.
9425b25f 401 return (0 < capability_search($capability, $context, $capabilities));
bbbf2d40 402
9425b25f 403}
bbbf2d40 404
405
406/**
407 * In a separate function so that we won't have to deal with do_anything.
408 * again. Used by function has_capability.
409 * @param $capability - capability string
0468976c 410 * @param $context - the context object
bbbf2d40 411 * @param $capabilities - either $USER->capability or loaded array
412 * @return permission (int)
413 */
0468976c 414function capability_search($capability, $context, $capabilities) {
759ac72d 415
bbbf2d40 416 global $USER, $CFG;
0468976c 417
0468976c 418 if (isset($capabilities[$context->id][$capability])) {
ea82d6b6 419 debugging("Found $capability in context $context->id at level $context->aggregatelevel: ".$capabilities[$context->id][$capability], E_ALL);
0468976c 420 return ($capabilities[$context->id][$capability]);
bbbf2d40 421 }
9425b25f 422
bbbf2d40 423 /* Then, we check the cache recursively */
9425b25f 424 $permission = 0;
425
d140ad3f 426 switch ($context->aggregatelevel) {
bbbf2d40 427
428 case CONTEXT_SYSTEM: // by now it's a definite an inherit
429 $permission = 0;
430 break;
431
432 case CONTEXT_PERSONAL:
0468976c 433 $parentcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
434 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 435 break;
9425b25f 436
4b10f08b 437 case CONTEXT_USER:
0468976c 438 $parentcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
439 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 440 break;
9425b25f 441
bbbf2d40 442 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
443 $coursecat = get_record('course_categories','id',$context->instanceid);
0468976c 444 if (!empty($coursecat->parent)) { // return parent value if it exists
445 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
bbbf2d40 446 } else { // else return site value
0468976c 447 $parentcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
bbbf2d40 448 }
0468976c 449 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 450 break;
451
452 case CONTEXT_COURSE: // 1 to 1 to course cat
453 // find the course cat, and return its value
454 $course = get_record('course','id',$context->instanceid);
0468976c 455 $parentcontext = get_context_instance(CONTEXT_COURSECAT, $course->category);
456 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 457 break;
458
459 case CONTEXT_GROUP: // 1 to 1 to course
460 $group = get_record('groups','id',$context->instanceid);
0468976c 461 $parentcontext = get_context_instance(CONTEXT_COURSE, $group->courseid);
462 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 463 break;
464
465 case CONTEXT_MODULE: // 1 to 1 to course
466 $cm = get_record('course_modules','id',$context->instanceid);
0468976c 467 $parentcontext = get_context_instance(CONTEXT_COURSE, $cm->course);
468 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 469 break;
470
471 case CONTEXT_BLOCK: // 1 to 1 to course
472 $block = get_record('block_instance','id',$context->instanceid);
0468976c 473 $parentcontext = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
474 $permission = capability_search($capability, $parentcontext, $capabilities);
bbbf2d40 475 break;
476
477 default:
478 error ('This is an unknown context!');
479 return false;
480 }
ea82d6b6 481 debugging("Found $capability recursively from context $context->id at level $context->aggregatelevel: $permission", E_ALL);
9425b25f 482
98882637 483 return $permission;
bbbf2d40 484}
485
486
487/**
488 * This function should be called immediately after a login, when $USER is set.
489 * It will build an array of all the capabilities at each level
490 * i.e. site/metacourse/course_category/course/moduleinstance
491 * Note we should only load capabilities if they are explicitly assigned already,
492 * we should not load all module's capability!
493 * @param $userid - the id of the user whose capabilities we want to load
494 * @return array
495 * possible just s simple 2D array with [contextid][capabilityname]
496 * [Capabilities] => [26][forum_post] = 1
497 * [26][forum_start] = -8990
498 * [26][forum_edit] = -1
499 * [273][blah blah] = 1
500 * [273][blah blah blah] = 2
501 */
0468976c 502function load_user_capability($capability='', $context ='', $userid='') {
d140ad3f 503
98882637 504 global $USER, $CFG;
bbbf2d40 505
506 if (empty($userid)) {
dc411d1b 507 if (empty($USER->id)) { // We have no user to get capabilities for
64026e8c 508 debugging('User not logged in for load_user_capability!');
dc411d1b 509 return false;
510 }
64026e8c 511 unset($USER->capabilities); // We don't want possible older capabilites hanging around
512
513 check_enrolment_plugins($USER); // Call "enrol" system to ensure that we have the correct picture
8f8ed475 514
bbbf2d40 515 $userid = $USER->id;
dc411d1b 516 $otheruserid = false;
bbbf2d40 517 } else {
64026e8c 518 if (!$user = get_record('user', 'id', $userid)) {
519 debugging('Non-existent userid in load_user_capability!');
520 return false;
521 }
522
523 check_enrolment_plugins($user); // Ensure that we have the correct picture
524
9425b25f 525 $otheruserid = $userid;
bbbf2d40 526 }
9425b25f 527
5f70bcc3 528
529/// First we generate a list of all relevant contexts of the user
530
531 $usercontexts = array();
bbbf2d40 532
0468976c 533 if ($context) { // if context is specified
534 $usercontexts = get_parent_contexts($context);
98882637 535 } else { // else, we load everything
5f70bcc3 536 if ($userroles = get_records('role_assignments','userid',$userid)) {
537 foreach ($userroles as $userrole) {
538 $usercontexts[] = $userrole->contextid;
539 }
98882637 540 }
5f70bcc3 541 }
542
543/// Set up SQL fragments for searching contexts
544
545 if ($usercontexts) {
0468976c 546 $listofcontexts = '('.implode(',', $usercontexts).')';
5f70bcc3 547 $searchcontexts1 = "c1.id IN $listofcontexts AND";
548 $searchcontexts2 = "c2.id IN $listofcontexts AND";
549 } else {
550 $listofcontexts = $searchcontexts1 = $searchcontexts2 = '';
bbbf2d40 551 }
0468976c 552
64026e8c 553 if ($capability) {
554 $capsearch = " AND rc.capability = '$capability' ";
555 } else {
556 $capsearch ="";
557 }
558
5f70bcc3 559/// Then we use 1 giant SQL to bring out all relevant capabilities.
560/// The first part gets the capabilities of orginal role.
561/// The second part gets the capabilities of overriden roles.
bbbf2d40 562
98882637 563 $siteinstance = get_context_instance(CONTEXT_SYSTEM, SITEID);
bbbf2d40 564
75e84883 565 $SQL = " SELECT rc.capability, c1.id, (c1.aggregatelevel * 100) AS aggrlevel,
bbbf2d40 566 SUM(rc.permission) AS sum
567 FROM
42ac3ecf 568 {$CFG->prefix}role_assignments ra,
569 {$CFG->prefix}role_capabilities rc,
570 {$CFG->prefix}context c1
bbbf2d40 571 WHERE
d4649c76 572 ra.contextid=c1.id AND
573 ra.roleid=rc.roleid AND
bbbf2d40 574 ra.userid=$userid AND
5f70bcc3 575 $searchcontexts1
bbbf2d40 576 rc.contextid=$siteinstance->id
98882637 577 $capsearch
bbbf2d40 578 GROUP BY
0be16c1d 579 rc.capability, (c1.aggregatelevel * 100), c1.id
bbbf2d40 580 HAVING
41811960 581 SUM(rc.permission) != 0
bbbf2d40 582 UNION
583
75e84883 584 SELECT rc.capability, c1.id, (c1.aggregatelevel * 100 + c2.aggregatelevel) AS aggrlevel,
bbbf2d40 585 SUM(rc.permission) AS sum
586 FROM
42ac3ecf 587 {$CFG->prefix}role_assignments ra,
588 {$CFG->prefix}role_capabilities rc,
589 {$CFG->prefix}context c1,
590 {$CFG->prefix}context c2
bbbf2d40 591 WHERE
d4649c76 592 ra.contextid=c1.id AND
593 ra.roleid=rc.roleid AND
594 ra.userid=$userid AND
595 rc.contextid=c2.id AND
5f70bcc3 596 $searchcontexts1
597 $searchcontexts2
598 rc.contextid != $siteinstance->id
bbbf2d40 599 $capsearch
600
601 GROUP BY
0be16c1d 602 rc.capability, (c1.aggregatelevel * 100 + c2.aggregatelevel), c1.id
bbbf2d40 603 HAVING
41811960 604 SUM(rc.permission) != 0
bbbf2d40 605 ORDER BY
75e84883 606 aggrlevel ASC
bbbf2d40 607 ";
608
98882637 609 $capabilities = array(); // Reinitialize.
75e84883 610 if (!$rs = get_recordset_sql($SQL)) {
611 error("Query failed in load_user_capability.");
612 }
5cf38a57 613
bbbf2d40 614 if ($rs && $rs->RecordCount() > 0) {
615 while (!$rs->EOF) {
75e84883 616 $array = $rs->fields;
617 $temprecord = new object;
98882637 618
619 foreach ($array as $key=>$val) {
75e84883 620 if ($key == 'aggrlevel') {
621 $temprecord->aggregatelevel = $val;
622 } else {
623 $temprecord->{$key} = $val;
624 }
98882637 625 }
bbbf2d40 626 $capabilities[] = $temprecord;
627 $rs->MoveNext();
628 }
629 }
d140ad3f 630
bbbf2d40 631 /* so up to this point we should have somethign like this
41811960 632 * $capabilities[1] ->aggregatelevel = 1000
bbbf2d40 633 ->module = SITEID
634 ->capability = do_anything
635 ->id = 1 (id is the context id)
636 ->sum = 0
637
41811960 638 * $capabilities[2] ->aggregatelevel = 1000
bbbf2d40 639 ->module = SITEID
640 ->capability = post_messages
641 ->id = 1
642 ->sum = -9000
643
41811960 644 * $capabilittes[3] ->aggregatelevel = 3000
bbbf2d40 645 ->module = course
646 ->capability = view_course_activities
647 ->id = 25
648 ->sum = 1
649
41811960 650 * $capabilittes[4] ->aggregatelevel = 3000
bbbf2d40 651 ->module = course
652 ->capability = view_course_activities
653 ->id = 26
654 ->sum = 0 (this is another course)
655
41811960 656 * $capabilities[5] ->aggregatelevel = 3050
bbbf2d40 657 ->module = course
658 ->capability = view_course_activities
659 ->id = 25 (override in course 25)
660 ->sum = -1
661 * ....
662 * now we proceed to write the session array, going from top to bottom
663 * at anypoint, we need to go up and check parent to look for prohibit
664 */
665 // print_object($capabilities);
666
667 /* This is where we write to the actualy capabilities array
668 * what we need to do from here on is
669 * going down the array from lowest level to highest level
670 * 1) recursively check for prohibit,
671 * if any, we write prohibit
672 * else, we write the value
673 * 2) at an override level, we overwrite current level
674 * if it's not set to prohibit already, and if different
675 * ........ that should be it ........
676 */
98882637 677 $usercap = array(); // for other user's capabilities
bbbf2d40 678 foreach ($capabilities as $capability) {
679
0468976c 680 $context = get_context_instance_by_id($capability->id);
681
41811960 682 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
98882637 683
0468976c 684 if (capability_prohibits($capability->capability, $context, $capability->sum, $usercap)) {
98882637 685 $usercap[$capability->id][$capability->capability] = -9000;
686 continue;
687 }
688
689 $usercap[$capability->id][$capability->capability] = $capability->sum;
690
691 } else {
692
0468976c 693 if (capability_prohibits($capability->capability, $context, $capability->sum)) { // if any parent or parent's parent is set to prohibit
98882637 694 $USER->capabilities[$capability->id][$capability->capability] = -9000;
695 continue;
696 }
697
698 // if no parental prohibit set
699 // just write to session, i am not sure this is correct yet
700 // since 3050 shows up after 3000, and 3070 shows up after 3050,
701 // it should be ok just to overwrite like this, provided that there's no
702 // parental prohibits
703 // no point writing 0, since 0 = inherit
704 // we need to write even if it's 0, because it could be an inherit override
705 $USER->capabilities[$capability->id][$capability->capability] = $capability->sum;
706 }
bbbf2d40 707 }
708
709 // now we don't care about the huge array anymore, we can dispose it.
710 unset($capabilities);
711
dbe7e582 712 if (!empty($otheruserid)) {
98882637 713 return $usercap; // return the array
bbbf2d40 714 }
715 // see array in session to see what it looks like
716
717}
718
64026e8c 719/*
720 * Check all the login enrolment information for the given user object
721 * by querying the enrolment plugins
722 */
723function check_enrolment_plugins(&$user) {
724 global $CFG;
725
726 require_once($CFG->dirroot .'/enrol/enrol.class.php');
727
728 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
729 $plugins = array($CFG->enrol);
730 }
731
732 foreach ($plugins as $plugin) {
733 $enrol = enrolment_factory::factory($plugin);
734 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
735 $enrol->setup_enrolments($user);
736 } else { /// Run legacy enrolment methods
737 if (method_exists($enrol, 'get_student_courses')) {
738 $enrol->get_student_courses($user);
739 }
740 if (method_exists($enrol, 'get_teacher_courses')) {
741 $enrol->get_teacher_courses($user);
742 }
743
744 /// deal with $user->students and $user->teachers stuff
745 unset($user->student);
746 unset($user->teacher);
747 }
748 unset($enrol);
749 }
750}
751
bbbf2d40 752
753/**
754 * This is a recursive function that checks whether the capability in this
755 * context, or the parent capabilities are set to prohibit.
756 *
757 * At this point, we can probably just use the values already set in the
758 * session variable, since we are going down the level. Any prohit set in
759 * parents would already reflect in the session.
760 *
761 * @param $capability - capability name
762 * @param $sum - sum of all capabilities values
0468976c 763 * @param $context - the context object
bbbf2d40 764 * @param $array - when loading another user caps, their caps are not stored in session but an array
765 */
0468976c 766function capability_prohibits($capability, $context, $sum='', $array='') {
bbbf2d40 767 global $USER;
0468976c 768
bbbf2d40 769 if ($sum < -8000) {
770 // If this capability is set to prohibit.
771 return true;
772 }
773
774 if (isset($array)) {
0468976c 775 if (isset($array[$context->id][$capability])
776 && $array[$context->id][$capability] < -8000) {
98882637 777 return true;
778 }
bbbf2d40 779 } else {
98882637 780 // Else if set in session.
0468976c 781 if (isset($USER->capabilities[$context->id][$capability])
782 && $USER->capabilities[$context->id][$capability] < -8000) {
98882637 783 return true;
784 }
bbbf2d40 785 }
d140ad3f 786 switch ($context->aggregatelevel) {
bbbf2d40 787
788 case CONTEXT_SYSTEM:
789 // By now it's a definite an inherit.
790 return 0;
791 break;
792
793 case CONTEXT_PERSONAL:
794 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
0468976c 795 return capability_prohibits($capability, $parent);
bbbf2d40 796 break;
797
4b10f08b 798 case CONTEXT_USER:
bbbf2d40 799 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
0468976c 800 return capability_prohibits($capability, $parent);
bbbf2d40 801 break;
802
803 case CONTEXT_COURSECAT:
804 // Coursecat -> coursecat or site.
805 $coursecat = get_record('course_categories','id',$context->instanceid);
41811960 806 if (!empty($coursecat->parent)) {
bbbf2d40 807 // return parent value if exist.
808 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
809 } else {
810 // Return site value.
811 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
812 }
0468976c 813 return capability_prohibits($capability, $parent);
bbbf2d40 814 break;
815
816 case CONTEXT_COURSE:
817 // 1 to 1 to course cat.
818 // Find the course cat, and return its value.
819 $course = get_record('course','id',$context->instanceid);
820 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
0468976c 821 return capability_prohibits($capability, $parent);
bbbf2d40 822 break;
823
824 case CONTEXT_GROUP:
825 // 1 to 1 to course.
826 $group = get_record('groups','id',$context->instanceid);
827 $parent = get_context_instance(CONTEXT_COURSE, $group->courseid);
0468976c 828 return capability_prohibits($capability, $parent);
bbbf2d40 829 break;
830
831 case CONTEXT_MODULE:
832 // 1 to 1 to course.
833 $cm = get_record('course_modules','id',$context->instanceid);
834 $parent = get_context_instance(CONTEXT_COURSE, $cm->course);
0468976c 835 return capability_prohibits($capability, $parent);
bbbf2d40 836 break;
837
838 case CONTEXT_BLOCK:
839 // 1 to 1 to course.
840 $block = get_record('block_instance','id',$context->instanceid);
841 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
0468976c 842 return capability_prohibits($capability, $parent);
bbbf2d40 843 break;
844
845 default:
846 error ('This is an unknown context!');
847 return false;
848 }
849}
850
851
852/**
853 * A print form function. This should either grab all the capabilities from
854 * files or a central table for that particular module instance, then present
855 * them in check boxes. Only relevant capabilities should print for known
856 * context.
857 * @param $mod - module id of the mod
858 */
859function print_capabilities($modid=0) {
860 global $CFG;
861
862 $capabilities = array();
863
864 if ($modid) {
865 // We are in a module specific context.
866
867 // Get the mod's name.
868 // Call the function that grabs the file and parse.
869 $cm = get_record('course_modules', 'id', $modid);
870 $module = get_record('modules', 'id', $cm->module);
871
872 } else {
873 // Print all capabilities.
874 foreach ($capabilities as $capability) {
875 // Prints the check box component.
876 }
877 }
878}
879
880
881/**
1afecc03 882 * Installs the roles system.
883 * This function runs on a fresh install as well as on an upgrade from the old
884 * hard-coded student/teacher/admin etc. roles to the new roles system.
bbbf2d40 885 */
1afecc03 886function moodle_install_roles() {
bbbf2d40 887
1afecc03 888 global $CFG, $db;
889
bbbf2d40 890 // Create a system wide context for assignemnt.
891 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
892
1afecc03 893
894 // Create default/legacy roles and capabilities.
895 // (1 legacy capability per legacy role at system level).
31f26796 896 $adminrole = create_role(get_string('administrator'), 'admin', get_string('administratordescription'), 'moodle/legacy:admin');
98882637 897 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
bbbf2d40 898 error('Could not assign moodle/site:doanything to the admin role');
899 }
31f26796 900 $coursecreatorrole = create_role(get_string('coursecreators'), 'coursecreator', get_string('coursecreatorsdescription'), 'moodle/legacy:coursecreator');
901 $editteacherrole = create_role(get_string('defaultcourseteacher'), 'editingteacher', get_string('defaultcourseteacherdescription'), 'moodle/legacy:editingteacher');
902 $noneditteacherrole = create_role(get_string('noneditingteacher'), 'teacher', get_string('noneditingteacherdescription'), 'moodle/legacy:teacher');
903 $studentrole = create_role(get_string('defaultcoursestudent'), 'student', get_string('defaultcoursestudentdescription'), 'moodle/legacy:student');
904 $guestrole = create_role(get_string('guest'), 'guest', get_string('guestdescription'), 'moodle/legacy:guest');
1afecc03 905
906
907 // Look inside user_admin, user_creator, user_teachers, user_students and
908 // assign above new roles. If a user has both teacher and student role,
909 // only teacher role is assigned. The assignment should be system level.
910 $dbtables = $db->MetaTables('TABLES');
bbbf2d40 911
1afecc03 912
98882637 913 /**
bbbf2d40 914 * Upgrade the admins.
1afecc03 915 * Sort using id ASC, first one is primary admin.
bbbf2d40 916 */
1afecc03 917 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
918 if ($useradmins = get_records_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
919 foreach ($useradmins as $admin) {
920 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
921 }
922 }
923 } else {
924 // This is a fresh install.
bbbf2d40 925 }
1afecc03 926
927
bbbf2d40 928 /**
929 * Upgrade course creators.
930 */
1afecc03 931 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
932 if ($usercoursecreators = get_records('user_coursecreators')) {
933 foreach ($usercoursecreators as $coursecreator) {
56b4d70d 934 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
1afecc03 935 }
936 }
bbbf2d40 937 }
938
1afecc03 939
bbbf2d40 940 /**
941 * Upgrade editting teachers and non-editting teachers.
942 */
1afecc03 943 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
944 if ($userteachers = get_records('user_teachers')) {
945 foreach ($userteachers as $teacher) {
17d6a25e 946 // populate the user_lastaccess table
947 unset($access);
948 $access->timeaccess = $teacher->timeaccess;
949 $access->userid = $teacher->userid;
950 $access->courseid = $teacher->course;
951 insert_record('user_lastaccess', $access);
952 // assign the default student role
1afecc03 953 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
954 if ($teacher->editall) { // editting teacher
955 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id);
956 } else {
957 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id);
958 }
959 }
bbbf2d40 960 }
961 }
1afecc03 962
963
bbbf2d40 964 /**
965 * Upgrade students.
966 */
1afecc03 967 if (in_array($CFG->prefix.'user_students', $dbtables)) {
968 if ($userstudents = get_records('user_students')) {
17d6a25e 969 foreach ($userstudents as $student) {
970 // populate the user_lastaccess table
971 unset($access);
972 $access->timeaccess = $student->timeaccess;
973 $access->userid = $student->userid;
974 $access->courseid = $student->course;
975 insert_record('user_lastaccess', $access);
976 // assign the default student role
1afecc03 977 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
978 role_assign($studentrole, $student->userid, 0, $coursecontext->id);
979 }
980 }
bbbf2d40 981 }
1afecc03 982
983
bbbf2d40 984 /**
985 * Upgrade guest (only 1 entry).
986 */
1afecc03 987 if ($guestuser = get_record('user', 'username', 'guest')) {
988 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
989 }
990
945f88ca 991 /**
992 * Insert the correct records for legacy roles
993 */
994 allow_assign($adminrole, $adminrole);
995 allow_assign($adminrole, $coursecreatorrole);
996 allow_assign($adminrole, $noneditteacherrole);
997 allow_assign($adminrole, $editteacherrole);
998 allow_assign($adminrole, $studentrole);
999 allow_assign($adminrole, $guestrole);
1000
1001 allow_assign($coursecreatorrole, $noneditteacherrole);
1002 allow_assign($coursecreatorrole, $editteacherrole);
1003 allow_assign($coursecreatorrole, $studentrole);
1004 allow_assign($coursecreatorrole, $guestrole);
1005
1006 allow_assign($editteacherrole, $noneditteacherrole);
1007 allow_assign($editteacherrole, $studentrole);
1008 allow_assign($editteacherrole, $guestrole);
1009
1010 /// overrides
1011 allow_override($adminrole, $adminrole);
1012 allow_override($adminrole, $coursecreatorrole);
1013 allow_override($adminrole, $noneditteacherrole);
1014 allow_override($adminrole, $editteacherrole);
1015 allow_override($adminrole, $studentrole);
5769734f 1016 allow_override($adminrole, $guestrole);
1afecc03 1017
746a04c5 1018
1afecc03 1019 // Should we delete the tables after we are done? Not yet.
bbbf2d40 1020}
1021
bbbf2d40 1022/**
1023 * Assign the defaults found in this capabality definition to roles that have
1024 * the corresponding legacy capabilities assigned to them.
1025 * @param $legacyperms - an array in the format (example):
1026 * 'guest' => CAP_PREVENT,
1027 * 'student' => CAP_ALLOW,
1028 * 'teacher' => CAP_ALLOW,
1029 * 'editingteacher' => CAP_ALLOW,
1030 * 'coursecreator' => CAP_ALLOW,
1031 * 'admin' => CAP_ALLOW
1032 * @return boolean - success or failure.
1033 */
1034function assign_legacy_capabilities($capability, $legacyperms) {
1035
1036 foreach ($legacyperms as $type => $perm) {
1037
1038 $systemcontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
1039
1040 // The legacy capabilities are:
1041 // 'moodle/legacy:guest'
1042 // 'moodle/legacy:student'
1043 // 'moodle/legacy:teacher'
1044 // 'moodle/legacy:editingteacher'
1045 // 'moodle/legacy:coursecreator'
1046 // 'moodle/legacy:admin'
1047
2e85fffe 1048 if ($roles = get_roles_with_capability('moodle/legacy:'.$type, CAP_ALLOW)) {
1049 foreach ($roles as $role) {
1050 // Assign a site level capability.
1051 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1052 return false;
1053 }
bbbf2d40 1054 }
1055 }
1056 }
1057 return true;
1058}
1059
1060
cee0901c 1061/**
1062 * Checks to see if a capability is a legacy capability.
1063 * @param $capabilityname
1064 * @return boolean
1065 */
bbbf2d40 1066function islegacy($capabilityname) {
98882637 1067 if (strstr($capabilityname, 'legacy') === false) {
1068 return false;
1069 } else {
1070 return true;
1071 }
bbbf2d40 1072}
1073
cee0901c 1074
1075
1076/**********************************
bbbf2d40 1077 * Context Manipulation functions *
1078 **********************************/
1079
bbbf2d40 1080/**
1081 * This should be called prolly everytime a user, group, module, course,
1082 * coursecat or site is set up maybe?
1083 * @param $level
1084 * @param $instanceid
1085 */
d140ad3f 1086function create_context($aggregatelevel, $instanceid) {
1087 if (!get_record('context','aggregatelevel',$aggregatelevel,'instanceid',$instanceid)) {
bbbf2d40 1088 $context = new object;
d140ad3f 1089 $context->aggregatelevel = $aggregatelevel;
bbbf2d40 1090 $context->instanceid = $instanceid;
1091 return insert_record('context',$context);
1092 }
1093}
1094
1095
1096/**
1097 * Get the context instance as an object. This function will create the
1098 * context instance if it does not exist yet.
1099 * @param $level
1100 * @param $instance
1101 */
d140ad3f 1102function get_context_instance($aggregatelevel=NULL, $instance=SITEID) {
e5605780 1103
51195e6f 1104 global $context_cache, $context_cache_id, $CONTEXT;
d9a35e12 1105
340ea4e8 1106/// If no level is supplied then return the current global context if there is one
d140ad3f 1107 if (empty($aggregatelevel)) {
340ea4e8 1108 if (empty($CONTEXT)) {
ea82d6b6 1109 debugging("Error: get_context_instance() called without a context");
340ea4e8 1110 } else {
1111 return $CONTEXT;
1112 }
e5605780 1113 }
1114
340ea4e8 1115/// Check the cache
d140ad3f 1116 if (isset($context_cache[$aggregatelevel][$instance])) { // Already cached
1117 return $context_cache[$aggregatelevel][$instance];
e5605780 1118 }
1119
340ea4e8 1120/// Get it from the database, or create it
d140ad3f 1121 if (!$context = get_record('context', 'aggregatelevel', $aggregatelevel, 'instanceid', $instance)) {
1122 create_context($aggregatelevel, $instance);
1123 $context = get_record('context', 'aggregatelevel', $aggregatelevel, 'instanceid', $instance);
e5605780 1124 }
1125
ccfc5ecc 1126/// Only add to cache if context isn't empty.
1127 if (!empty($context)) {
1128 $context_cache[$aggregatelevel][$instance] = $context; // Cache it for later
1129 $context_cache_id[$context->id] = $context; // Cache it for later
1130 }
0468976c 1131
bbbf2d40 1132 return $context;
1133}
1134
cee0901c 1135
340ea4e8 1136/**
1137 * Get a context instance as an object, from a given id.
1138 * @param $id
1139 */
1140function get_context_instance_by_id($id) {
1141
d9a35e12 1142 global $context_cache, $context_cache_id;
1143
340ea4e8 1144 if (isset($context_cache_id[$id])) { // Already cached
75e84883 1145 return $context_cache_id[$id];
340ea4e8 1146 }
1147
1148 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
d140ad3f 1149 $context_cache[$context->aggregatelevel][$context->instanceid] = $context;
340ea4e8 1150 $context_cache_id[$context->id] = $context;
1151 return $context;
1152 }
1153
1154 return false;
1155}
1156
bbbf2d40 1157
8737be58 1158/**
1159 * Get the local override (if any) for a given capability in a role in a context
1160 * @param $roleid
0468976c 1161 * @param $contextid
1162 * @param $capability
8737be58 1163 */
1164function get_local_override($roleid, $contextid, $capability) {
1165 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
1166}
1167
1168
bbbf2d40 1169
1170/************************************
1171 * DB TABLE RELATED FUNCTIONS *
1172 ************************************/
1173
cee0901c 1174/**
bbbf2d40 1175 * function that creates a role
1176 * @param name - role name
31f26796 1177 * @param shortname - role short name
bbbf2d40 1178 * @param description - role description
1179 * @param legacy - optional legacy capability
1180 * @return id or false
1181 */
31f26796 1182function create_role($name, $shortname, $description, $legacy='') {
98882637 1183
1184 // check for duplicate role name
1185
1186 if ($role = get_record('role','name', $name)) {
98882637 1187 error('there is already a role with this name!');
1188 }
1189
31f26796 1190 if ($role = get_record('role','shortname', $shortname)) {
1191 error('there is already a role with this shortname!');
1192 }
1193
98882637 1194 $role->name = $name;
31f26796 1195 $role->shortname = $shortname;
98882637 1196 $role->description = $description;
ec7a8b79 1197
1198 $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
1199
98882637 1200 if ($id = insert_record('role', $role)) {
ec7a8b79 1201 if ($legacy) {
1afecc03 1202 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
98882637 1203 }
ec7a8b79 1204
1205 /// By default, users with role:manage at site level
1206 /// should be able to assign users to this new role, and override this new role's capabilities
1207
1208 // find all admin roles
e46c0987 1209 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
1210 // foreach admin role
1211 foreach ($adminroles as $arole) {
1212 // write allow_assign and allow_overrid
1213 allow_assign($arole->id, $id);
1214 allow_override($arole->id, $id);
1215 }
ec7a8b79 1216 }
1217
98882637 1218 return $id;
1219 } else {
1220 return false;
1221 }
bbbf2d40 1222
1223}
1224
1225/**
1226 * Function to write context specific overrides, or default capabilities.
1227 * @param module - string name
1228 * @param capability - string name
1229 * @param contextid - context id
1230 * @param roleid - role id
1231 * @param permission - int 1,-1 or -1000
1232 */
e7876c1e 1233function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
98882637 1234
1235 global $USER;
1236
1237 if (empty($permission) || $permission == 0) { // if permission is not set
1238 unassign_capability($capability, $roleid, $contextid);
1239 }
bbbf2d40 1240
2e85fffe 1241 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
e7876c1e 1242
1243 if ($existing and !$overwrite) { // We want to keep whatever is there already
1244 return true;
1245 }
1246
bbbf2d40 1247 $cap = new object;
1248 $cap->contextid = $contextid;
1249 $cap->roleid = $roleid;
1250 $cap->capability = $capability;
1251 $cap->permission = $permission;
1252 $cap->timemodified = time();
9db12da7 1253 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
e7876c1e 1254
1255 if ($existing) {
1256 $cap->id = $existing->id;
1257 return update_record('role_capabilities', $cap);
1258 } else {
1259 return insert_record('role_capabilities', $cap);
1260 }
bbbf2d40 1261}
1262
1263
1264/**
1265 * Unassign a capability from a role.
1266 * @param $roleid - the role id
1267 * @param $capability - the name of the capability
1268 * @return boolean - success or failure
1269 */
1270function unassign_capability($capability, $roleid, $contextid=NULL) {
98882637 1271
1272 if (isset($contextid)) {
1273 $status = delete_records('role_capabilities', 'capability', $capability,
1274 'roleid', $roleid, 'contextid', $contextid);
1275 } else {
1276 $status = delete_records('role_capabilities', 'capability', $capability,
1277 'roleid', $roleid);
1278 }
1279 return $status;
bbbf2d40 1280}
1281
1282
1283/**
759ac72d 1284 * Get the roles that have a given capability assigned to it. This function
1285 * does not resolve the actual permission of the capability. It just checks
1286 * for assignment only.
bbbf2d40 1287 * @param $capability - capability name (string)
1288 * @param $permission - optional, the permission defined for this capability
1289 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
1290 * @return array or role objects
1291 */
ec7a8b79 1292function get_roles_with_capability($capability, $permission=NULL, $context='') {
1293
bbbf2d40 1294 global $CFG;
1295
ec7a8b79 1296 if ($context) {
1297 if ($contexts = get_parent_contexts($context)) {
1298 $listofcontexts = '('.implode(',', $contexts).')';
1299 } else {
1300 $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
1301 $listofcontexts = '('.$sitecontext->id.')'; // must be site
1302 }
42ac3ecf 1303 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
ec7a8b79 1304 } else {
1305 $contextstr = '';
1306 }
1307
bbbf2d40 1308 $selectroles = "SELECT r.*
42ac3ecf 1309 FROM {$CFG->prefix}role r,
1310 {$CFG->prefix}role_capabilities rc
bbbf2d40 1311 WHERE rc.capability = '$capability'
ec7a8b79 1312 AND rc.roleid = r.id $contextstr";
bbbf2d40 1313
1314 if (isset($permission)) {
1315 $selectroles .= " AND rc.permission = '$permission'";
1316 }
1317 return get_records_sql($selectroles);
1318}
1319
1320
1321/**
a9e1c058 1322 * This function makes a role-assignment (a role for a user or group in a particular context)
bbbf2d40 1323 * @param $roleid - the role of the id
1324 * @param $userid - userid
1325 * @param $groupid - group id
1326 * @param $contextid - id of the context
1327 * @param $timestart - time this assignment becomes effective
1328 * @param $timeend - time this assignemnt ceases to be effective
1329 * @uses $USER
1330 * @return id - new id of the assigment
1331 */
f44152f4 1332function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual') {
aa311411 1333 global $USER, $CFG;
bbbf2d40 1334
ea82d6b6 1335 debugging("Assign roleid $roleid userid $userid contextid $contextid", E_ALL);
bbbf2d40 1336
a9e1c058 1337/// Do some data validation
1338
bbbf2d40 1339 if (empty($roleid)) {
a9e1c058 1340 notify('Role ID not provided');
1341 return false;
bbbf2d40 1342 }
1343
1344 if (empty($userid) && empty($groupid)) {
a9e1c058 1345 notify('Either userid or groupid must be provided');
1346 return false;
bbbf2d40 1347 }
7700027f 1348
1349 if ($userid && !record_exists('user', 'id', $userid)) {
1350 notify('User does not exist!');
1351 return false;
1352 }
bbbf2d40 1353
dc411d1b 1354 if ($groupid && !record_exists('groups', 'id', $groupid)) {
1355 notify('Group does not exist!');
1356 return false;
1357 }
1358
7700027f 1359 if (!$context = get_context_instance_by_id($contextid)) {
a9e1c058 1360 notify('A valid context must be provided');
1361 return false;
bbbf2d40 1362 }
1363
a9e1c058 1364 if (($timestart and $timeend) and ($timestart > $timeend)) {
7700027f 1365 notify('The end time can not be earlier than the start time');
a9e1c058 1366 return false;
1367 }
1368
7700027f 1369
a9e1c058 1370/// Check for existing entry
1371 if ($userid) {
7700027f 1372 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
a9e1c058 1373 } else {
7700027f 1374 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
a9e1c058 1375 }
1376
9ebcb4d2 1377
a9e1c058 1378 $newra = new object;
bbbf2d40 1379
a9e1c058 1380 if (empty($ra)) { // Create a new entry
1381 $newra->roleid = $roleid;
7700027f 1382 $newra->contextid = $context->id;
a9e1c058 1383 $newra->userid = $userid;
1384 $newra->groupid = $groupid;
1385
1386 $newra->hidden = $hidden;
f44152f4 1387 $newra->enrol = $enrol;
a9e1c058 1388 $newra->timestart = $timestart;
1389 $newra->timeend = $timeend;
1390 $newra->timemodified = time();
1391 $newra->modifier = empty($USER->id) ? 0 : $USER->id;
1392
9ebcb4d2 1393 $success = insert_record('role_assignments', $newra);
a9e1c058 1394
1395 } else { // We already have one, just update it
1396
1397 $newra->id = $ra->id;
1398 $newra->hidden = $hidden;
f44152f4 1399 $newra->enrol = $enrol;
a9e1c058 1400 $newra->timestart = $timestart;
1401 $newra->timeend = $timeend;
1402 $newra->timemodified = time();
1403 $newra->modifier = empty($USER->id) ? 0 : $USER->id;
1404
9ebcb4d2 1405 $success = update_record('role_assignments', $newra);
1406 }
1407
7700027f 1408 if ($success) { /// Role was assigned, so do some other things
1409
1410 /// If the user is the current user, then reload the capabilities too.
1411 if (!empty($USER->id) && $USER->id == $userid) {
1412 load_user_capability();
1413 }
1414
0f161e1f 1415 /// Ask all the modules if anything needs to be done for this user
1416 if ($mods = get_list_of_plugins('mod')) {
1417 foreach ($mods as $mod) {
1418 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
1419 $functionname = $mod.'_role_assign';
1420 if (function_exists($functionname)) {
1421 $functionname($userid, $context);
1422 }
1423 }
1424 }
1425
1426 /// Make sure they have an entry in user_lastaccess for courses they can access
1427 // role_add_lastaccess_entries($userid, $context);
a9e1c058 1428 }
4e5f3064 1429
1430 /// now handle metacourse role assignments if in course context
1431 if ($success and $context->aggregatelevel == CONTEXT_COURSE) {
1432 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
1433 foreach ($parents as $parent) {
1aad4310 1434 sync_metacourse($parent->parent_course);
4e5f3064 1435 }
1436 }
1437 }
6eb4f823 1438
1439 return $success;
bbbf2d40 1440}
1441
1442
1443/**
1dc1f037 1444 * Deletes one or more role assignments. You must specify at least one parameter.
bbbf2d40 1445 * @param $roleid
1446 * @param $userid
1447 * @param $groupid
1448 * @param $contextid
1449 * @return boolean - success or failure
1450 */
1dc1f037 1451function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0) {
d74067e8 1452
1453 global $USER, $CFG;
4e5f3064 1454
1455 $success = true;
d74067e8 1456
1dc1f037 1457 $args = array('roleid', 'userid', 'groupid', 'contextid');
1458 $select = array();
1459 foreach ($args as $arg) {
1460 if ($$arg) {
1461 $select[] = $arg.' = '.$$arg;
1462 }
1463 }
d74067e8 1464
1dc1f037 1465 if ($select) {
4e5f3064 1466 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
1467 $mods = get_list_of_plugins('mod');
1468 foreach($ras as $ra) {
86e2c51d 1469 /// infinite loop protection when deleting recursively
1470 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
1471 continue;
1472 }
4e5f3064 1473 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
86e2c51d 1474
4e5f3064 1475 /// If the user is the current user, then reload the capabilities too.
1476 if (!empty($USER->id) && $USER->id == $ra->userid) {
1477 load_user_capability();
1478 }
1479 $context = get_record('context', 'id', $ra->contextid);
0f161e1f 1480
1481 /// Ask all the modules if anything needs to be done for this user
4e5f3064 1482 foreach ($mods as $mod) {
1483 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
1484 $functionname = $mod.'_role_unassign';
1485 if (function_exists($functionname)) {
1486 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
1487 }
1488 }
1489
1490 /// now handle metacourse role unassigment and removing from goups if in course context
1491 if (!empty($context) and $context->aggregatelevel == CONTEXT_COURSE) {
1492 //remove from groups when user has no role
1493 $roles = get_user_roles($context, $ra->userid, true);
1494 if (empty($roles)) {
1495 if ($groups = get_groups($context->instanceid, $ra->userid)) {
1496 foreach ($groups as $group) {
1497 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
1498 }
1499 }
1500 }
1aad4310 1501 //unassign roles in metacourses if needed
4e5f3064 1502 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
1503 foreach ($parents as $parent) {
1aad4310 1504 sync_metacourse($parent->parent_course);
0f161e1f 1505 }
1506 }
0f161e1f 1507 }
1508 }
d74067e8 1509 }
1dc1f037 1510 }
4e5f3064 1511
1512 return $success;
bbbf2d40 1513}
1514
b963384f 1515/*
1516 * A convenience function to take care of the common case where you
1517 * just want to enrol someone using the default role into a course
1518 *
1519 * @param object $course
1520 * @param object $user
1521 * @param string $enrol - the plugin used to do this enrolment
1522 */
1523function enrol_into_course($course, $user, $enrol) {
1524
1525 if ($course->enrolperiod) {
1526 $timestart = time();
1527 $timeend = time() + $course->enrolperiod;
1528 } else {
1529 $timestart = $timeend = 0;
1530 }
1531
1532 if ($role = get_default_course_role($course)) {
c4381ef5 1533
1534 $context = get_context_instance(CONTEXT_COURSE, $course->id);
1535
b963384f 1536 if (role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
1537 return false;
1538 }
1539
1540 email_welcome_message_to_user($course, $user);
1541
1542 add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
1543
1544 return true;
1545 }
1546
1547 return false;
1548}
1549
0f161e1f 1550/**
1551 * Add last access times to user_lastaccess as required
1552 * @param $userid
1553 * @param $context
1554 * @return boolean - success or failure
1555 */
1556function role_add_lastaccess_entries($userid, $context) {
1557
1558 global $USER, $CFG;
1559
1560 if (empty($context->aggregatelevel)) {
1561 return false;
1562 }
1563
1564 $lastaccess = new object; // Reusable object below
1565 $lastaccess->userid = $userid;
1566 $lastaccess->timeaccess = 0;
1567
1568 switch ($context->aggregatelevel) {
1569
1570 case CONTEXT_SYSTEM: // For the whole site
1571 if ($courses = get_record('course')) {
1572 foreach ($courses as $course) {
1573 $lastaccess->courseid = $course->id;
1574 role_set_lastaccess($lastaccess);
1575 }
1576 }
1577 break;
1578
1579 case CONTEXT_CATEGORY: // For a whole category
1580 if ($courses = get_record('course', 'category', $context->instanceid)) {
1581 foreach ($courses as $course) {
1582 $lastaccess->courseid = $course->id;
1583 role_set_lastaccess($lastaccess);
1584 }
1585 }
1586 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
1587 foreach ($categories as $category) {
1588 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
1589 role_add_lastaccess_entries($userid, $subcontext);
1590 }
1591 }
1592 break;
1593
1594
1595 case CONTEXT_COURSE: // For a whole course
1596 if ($course = get_record('course', 'id', $context->instanceid)) {
1597 $lastaccess->courseid = $course->id;
1598 role_set_lastaccess($lastaccess);
1599 }
1600 break;
1601 }
1602}
1603
1604/**
1605 * Delete last access times from user_lastaccess as required
1606 * @param $userid
1607 * @param $context
1608 * @return boolean - success or failure
1609 */
1610function role_remove_lastaccess_entries($userid, $context) {
1611
1612 global $USER, $CFG;
1613
1614}
1615
bbbf2d40 1616
1617/**
1618 * Loads the capability definitions for the component (from file). If no
1619 * capabilities are defined for the component, we simply return an empty array.
1620 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1621 * @return array of capabilities
1622 */
1623function load_capability_def($component) {
1624 global $CFG;
1625
1626 if ($component == 'moodle') {
1627 $defpath = $CFG->libdir.'/db/access.php';
1628 $varprefix = 'moodle';
1629 } else {
0c4d9f49 1630 $compparts = explode('/', $component);
1631
1632 if ($compparts[0] == 'block') {
1633 // Blocks are an exception. Blocks directory is 'blocks', and not
1634 // 'block'. So we need to jump through hoops.
1635 $defpath = $CFG->dirroot.'/'.$compparts[0].
1636 's/'.$compparts[1].'/db/access.php';
1637 $varprefix = $compparts[0].'_'.$compparts[1];
1638 } else {
1639 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
1640 $varprefix = str_replace('/', '_', $component);
1641 }
bbbf2d40 1642 }
1643 $capabilities = array();
1644
1645 if (file_exists($defpath)) {
1646 require_once($defpath);
1647 $capabilities = ${$varprefix.'_capabilities'};
1648 }
1649 return $capabilities;
1650}
1651
1652
1653/**
1654 * Gets the capabilities that have been cached in the database for this
1655 * component.
1656 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1657 * @return array of capabilities
1658 */
1659function get_cached_capabilities($component='moodle') {
1660 if ($component == 'moodle') {
1661 $storedcaps = get_records_select('capabilities',
1662 "name LIKE 'moodle/%:%'");
1663 } else {
1664 $storedcaps = get_records_select('capabilities',
1665 "name LIKE '$component:%'");
1666 }
1667 return $storedcaps;
1668}
1669
1670
1671/**
1672 * Updates the capabilities table with the component capability definitions.
1673 * If no parameters are given, the function updates the core moodle
1674 * capabilities.
1675 *
1676 * Note that the absence of the db/access.php capabilities definition file
1677 * will cause any stored capabilities for the component to be removed from
1678 * the database.
1679 *
1680 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1681 * @return boolean
1682 */
1683function update_capabilities($component='moodle') {
1684
1685 $storedcaps = array();
be4486da 1686
1687 $filecaps = load_capability_def($component);
bbbf2d40 1688 $cachedcaps = get_cached_capabilities($component);
1689 if ($cachedcaps) {
1690 foreach ($cachedcaps as $cachedcap) {
1691 array_push($storedcaps, $cachedcap->name);
be4486da 1692 // update risk bitmasks in existing capabilitites if needed
1693 if (array_key_exists($cachedcap->name, $filecaps)) {
1694 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2b531945 1695 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
be4486da 1696 }
1697 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
1698 $updatecap = new object;
1699 $updatecap->id = $cachedcap->id;
1700 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
1701 if (!update_record('capabilities', $updatecap)) {
1702 return false;
1703 }
1704 }
1705 }
bbbf2d40 1706 }
1707 }
be4486da 1708
bbbf2d40 1709 // Are there new capabilities in the file definition?
1710 $newcaps = array();
1711
1712 foreach ($filecaps as $filecap => $def) {
1713 if (!$storedcaps ||
1714 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2b531945 1715 if (!array_key_exists('riskbitmask', $def)) {
1716 $def['riskbitmask'] = 0; // no risk if not specified
1717 }
bbbf2d40 1718 $newcaps[$filecap] = $def;
1719 }
1720 }
1721 // Add new capabilities to the stored definition.
1722 foreach ($newcaps as $capname => $capdef) {
1723 $capability = new object;
1724 $capability->name = $capname;
1725 $capability->captype = $capdef['captype'];
1726 $capability->contextlevel = $capdef['contextlevel'];
1727 $capability->component = $component;
be4486da 1728 $capability->riskbitmask = $capdef['riskbitmask'];
bbbf2d40 1729
1730 if (!insert_record('capabilities', $capability, false, 'id')) {
1731 return false;
1732 }
ab5c9044 1733
1734 global $db;
1735 $db->debug= 999;
bbbf2d40 1736 // Do we need to assign the new capabilities to roles that have the
1737 // legacy capabilities moodle/legacy:* as well?
1738 if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
1739 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2e85fffe 1740 notify('Could not assign legacy capabilities for '.$capname);
bbbf2d40 1741 }
1742 }
1743 // Are there any capabilities that have been removed from the file
1744 // definition that we need to delete from the stored capabilities and
1745 // role assignments?
1746 capabilities_cleanup($component, $filecaps);
1747
1748 return true;
1749}
1750
1751
1752/**
1753 * Deletes cached capabilities that are no longer needed by the component.
1754 * Also unassigns these capabilities from any roles that have them.
1755 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
1756 * @param $newcapdef - array of the new capability definitions that will be
1757 * compared with the cached capabilities
1758 * @return int - number of deprecated capabilities that have been removed
1759 */
1760function capabilities_cleanup($component, $newcapdef=NULL) {
1761
1762 $removedcount = 0;
1763
1764 if ($cachedcaps = get_cached_capabilities($component)) {
1765 foreach ($cachedcaps as $cachedcap) {
1766 if (empty($newcapdef) ||
1767 array_key_exists($cachedcap->name, $newcapdef) === false) {
1768
1769 // Remove from capabilities cache.
1770 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
1771 error('Could not delete deprecated capability '.$cachedcap->name);
1772 } else {
1773 $removedcount++;
1774 }
1775 // Delete from roles.
1776 if($roles = get_roles_with_capability($cachedcap->name)) {
1777 foreach($roles as $role) {
46943f7b 1778 if (!unassign_capability($cachedcap->name, $role->id)) {
bbbf2d40 1779 error('Could not unassign deprecated capability '.
1780 $cachedcap->name.' from role '.$role->name);
1781 }
1782 }
1783 }
1784 } // End if.
1785 }
1786 }
1787 return $removedcount;
1788}
1789
1790
1791
cee0901c 1792/****************
1793 * UI FUNCTIONS *
1794 ****************/
bbbf2d40 1795
1796
1797/**
1798 * prints human readable context identifier.
1799 */
0468976c 1800function print_context_name($context) {
340ea4e8 1801
ec0810ee 1802 $name = '';
d140ad3f 1803 switch ($context->aggregatelevel) {
ec0810ee 1804
bbbf2d40 1805 case CONTEXT_SYSTEM: // by now it's a definite an inherit
ec0810ee 1806 $name = get_string('site');
340ea4e8 1807 break;
bbbf2d40 1808
1809 case CONTEXT_PERSONAL:
ec0810ee 1810 $name = get_string('personal');
340ea4e8 1811 break;
1812
4b10f08b 1813 case CONTEXT_USER:
ec0810ee 1814 if ($user = get_record('user', 'id', $context->instanceid)) {
1815 $name = get_string('user').': '.fullname($user);
1816 }
340ea4e8 1817 break;
1818
bbbf2d40 1819 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
ec0810ee 1820 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
1821 $name = get_string('category').': '.$category->name;
1822 }
340ea4e8 1823 break;
bbbf2d40 1824
1825 case CONTEXT_COURSE: // 1 to 1 to course cat
ec0810ee 1826 if ($course = get_record('course', 'id', $context->instanceid)) {
1827 $name = get_string('course').': '.$course->fullname;
1828 }
340ea4e8 1829 break;
bbbf2d40 1830
1831 case CONTEXT_GROUP: // 1 to 1 to course
ec0810ee 1832 if ($group = get_record('groups', 'id', $context->instanceid)) {
1833 $name = get_string('group').': '.$group->name;
1834 }
340ea4e8 1835 break;
bbbf2d40 1836
1837 case CONTEXT_MODULE: // 1 to 1 to course
98882637 1838 if ($cm = get_record('course_modules','id',$context->instanceid)) {
1839 if ($module = get_record('modules','id',$cm->module)) {
1840 if ($mod = get_record($module->name, 'id', $cm->instance)) {
ec0810ee 1841 $name = get_string('activitymodule').': '.$mod->name;
98882637 1842 }
ec0810ee 1843 }
1844 }
340ea4e8 1845 break;
bbbf2d40 1846
1847 case CONTEXT_BLOCK: // 1 to 1 to course
98882637 1848 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
1849 if ($block = get_record('block','id',$blockinstance->blockid)) {
91be52d7 1850 global $CFG;
1851 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
1852 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
1853 $blockname = "block_$block->name";
1854 if ($blockobject = new $blockname()) {
1855 $name = $blockobject->title.' ('.get_string('block').')';
1856 }
ec0810ee 1857 }
1858 }
340ea4e8 1859 break;
bbbf2d40 1860
1861 default:
1862 error ('This is an unknown context!');
340ea4e8 1863 return false;
1864
1865 }
340ea4e8 1866 return $name;
bbbf2d40 1867}
1868
1869
1870/**
1871 * Extracts the relevant capabilities given a contextid.
1872 * All case based, example an instance of forum context.
1873 * Will fetch all forum related capabilities, while course contexts
1874 * Will fetch all capabilities
0468976c 1875 * @param object context
bbbf2d40 1876 * @return array();
1877 *
1878 * capabilities
1879 * `name` varchar(150) NOT NULL,
1880 * `captype` varchar(50) NOT NULL,
1881 * `contextlevel` int(10) NOT NULL,
1882 * `component` varchar(100) NOT NULL,
1883 */
0468976c 1884function fetch_context_capabilities($context) {
98882637 1885
1886 global $CFG;
bbbf2d40 1887
1888 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
98882637 1889
d140ad3f 1890 switch ($context->aggregatelevel) {
bbbf2d40 1891
98882637 1892 case CONTEXT_SYSTEM: // all
1893 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1894 break;
1895
1896 case CONTEXT_PERSONAL:
0a8a95c9 1897 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_PERSONAL;
bbbf2d40 1898 break;
1899
4b10f08b 1900 case CONTEXT_USER:
1901 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_USER;
bbbf2d40 1902 break;
1903
1904 case CONTEXT_COURSECAT: // all
98882637 1905 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1906 break;
1907
1908 case CONTEXT_COURSE: // all
98882637 1909 $SQL = "select * from {$CFG->prefix}capabilities";
bbbf2d40 1910 break;
1911
1912 case CONTEXT_GROUP: // group caps
1913 break;
1914
1915 case CONTEXT_MODULE: // mod caps
98882637 1916 $cm = get_record('course_modules', 'id', $context->instanceid);
1917 $module = get_record('modules', 'id', $cm->module);
bbbf2d40 1918
98882637 1919 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
1920 and component = 'mod/$module->name'";
bbbf2d40 1921 break;
1922
1923 case CONTEXT_BLOCK: // block caps
98882637 1924 $cb = get_record('block_instance', 'id', $context->instanceid);
1925 $block = get_record('block', 'id', $cb->blockid);
bbbf2d40 1926
98882637 1927 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_BLOCK."
1928 and component = 'block/$block->name'";
bbbf2d40 1929 break;
1930
1931 default:
1932 return false;
1933 }
1934
1935 $records = get_records_sql($SQL.' '.$sort);
759ac72d 1936 $contextindependentcaps = fetch_context_independent_capabilities();
1937 $records = array_merge($records, $contextindependentcaps);
69eb59f2 1938
1939 // special sorting of core system capabiltites and enrollments
1940 if ($context->aggregatelevel == CONTEXT_SYSTEM) {
1941 $first = array();
1942 foreach ($records as $key=>$record) {
1943 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
1944 $first[$key] = $record;
1945 unset($records[$key]);
1946 } else if (count($first)){
1947 break;
1948 }
1949 }
1950 if (count($first)) {
1951 $records = $first + $records; // merge the two arrays keeping the keys
1952 }
1953 }
1954 // end of special sorting
bbbf2d40 1955 return $records;
1956
1957}
1958
1959
759ac72d 1960/**
1961 * Gets the context-independent capabilities that should be overrridable in
1962 * any context.
1963 * @return array of capability records from the capabilities table.
1964 */
1965function fetch_context_independent_capabilities() {
1966
1967 $contextindependentcaps = array(
1968 'moodle/site:accessallgroups'
1969 );
1970
1971 $records = array();
1972
1973 foreach ($contextindependentcaps as $capname) {
1974 $record = get_record('capabilities', 'name', $capname);
1975 array_push($records, $record);
1976 }
1977 return $records;
1978}
1979
1980
bbbf2d40 1981/**
1982 * This function pulls out all the resolved capabilities (overrides and
759ac72d 1983 * defaults) of a role used in capability overrides in contexts at a given
bbbf2d40 1984 * context.
0a8a95c9 1985 * @param obj $context
bbbf2d40 1986 * @param int $roleid
dc558690 1987 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
bbbf2d40 1988 * @return array
1989 */
1648afb2 1990function role_context_capabilities($roleid, $context, $cap='') {
dc558690 1991 global $CFG;
98882637 1992
8521d83a 1993 $contexts = get_parent_contexts($context);
1994 $contexts[] = $context->id;
98882637 1995 $contexts = '('.implode(',', $contexts).')';
1996
1648afb2 1997 if ($cap) {
e4697bf7 1998 $search = " AND rc.capability = '$cap' ";
1648afb2 1999 } else {
2000 $search = '';
2001 }
2002
dc558690 2003 $SQL = "SELECT rc.*
2004 FROM {$CFG->prefix}role_capabilities rc,
2005 {$CFG->prefix}context c
2006 WHERE rc.contextid in $contexts
2007 AND rc.roleid = $roleid
2008 AND rc.contextid = c.id $search
2009 ORDER BY c.aggregatelevel DESC,
2010 rc.capability DESC";
759ac72d 2011
98882637 2012 $capabilities = array();
2013
4729012f 2014 if ($records = get_records_sql($SQL)) {
2015 // We are traversing via reverse order.
2016 foreach ($records as $record) {
2017 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2018 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2019 $capabilities[$record->capability] = $record->permission;
2020 }
2021 }
98882637 2022 }
2023 return $capabilities;
bbbf2d40 2024}
2025
bbbf2d40 2026/**
0468976c 2027 * Recursive function which, given a context, find all parent context ids,
bbbf2d40 2028 * and return the array in reverse order, i.e. parent first, then grand
2029 * parent, etc.
2030 * @param object $context
2031 * @return array()
2032 */
bbbf2d40 2033function get_parent_contexts($context) {
759ac72d 2034
d140ad3f 2035 switch ($context->aggregatelevel) {
bbbf2d40 2036
2037 case CONTEXT_SYSTEM: // no parent
957861f7 2038 return array();
bbbf2d40 2039 break;
2040
2041 case CONTEXT_PERSONAL:
957861f7 2042 if (!$parent = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
2043 return array();
2044 } else {
2045 return array($parent->id);
2046 }
bbbf2d40 2047 break;
2048
4b10f08b 2049 case CONTEXT_USER:
957861f7 2050 if (!$parent = get_context_instance(CONTEXT_SYSTEM, SITEID)) {
2051 return array();
2052 } else {
2053 return array($parent->id);
2054 }
bbbf2d40 2055 break;
2056
2057 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
957861f7 2058 if (!$coursecat = get_record('course_categories','id',$context->instanceid)) {
2059 return array();
2060 }
c5ddc3fd 2061 if (!empty($coursecat->parent)) { // return parent value if exist
bbbf2d40 2062 $parent = get_context_instance(CONTEXT_COURSECAT, $coursecat->parent);
2063 return array_merge(array($parent->id), get_parent_contexts($parent));
2064 } else { // else return site value
2065 $parent = get_context_instance(CONTEXT_SYSTEM, SITEID);
2066 return array($parent->id);
2067 }
2068 break;
2069
2070 case CONTEXT_COURSE: // 1 to 1 to course cat
957861f7 2071 if (!$course = get_record('course','id',$context->instanceid)) {
2072 return array();
2073 }
2074 if (!empty($course->category)) {
2075 $parent = get_context_instance(CONTEXT_COURSECAT, $course->category);
2076 return array_merge(array($parent->id), get_parent_contexts($parent));
2077 } else {
2078 return array();
2079 }
bbbf2d40 2080 break;
2081
2082 case CONTEXT_GROUP: // 1 to 1 to course
957861f7 2083 if (!$group = get_record('groups','id',$context->instanceid)) {
2084 return array();
2085 }
2086 if ($parent = get_context_instance(CONTEXT_COURSE, $group->courseid)) {
2087 return array_merge(array($parent->id), get_parent_contexts($parent));
2088 } else {
2089 return array();
2090 }
bbbf2d40 2091 break;
2092
2093 case CONTEXT_MODULE: // 1 to 1 to course
957861f7 2094 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
2095 return array();
2096 }
2097 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
2098 return array_merge(array($parent->id), get_parent_contexts($parent));
2099 } else {
2100 return array();
2101 }
bbbf2d40 2102 break;
2103
2104 case CONTEXT_BLOCK: // 1 to 1 to course
957861f7 2105 if (!$block = get_record('block_instance','id',$context->instanceid)) {
2106 return array();
2107 }
2108 if ($parent = get_context_instance(CONTEXT_COURSE, $block->pageid)) {
2109 return array_merge(array($parent->id), get_parent_contexts($parent));
2110 } else {
2111 return array();
2112 }
bbbf2d40 2113 break;
2114
2115 default:
957861f7 2116 error('This is an unknown context!');
bbbf2d40 2117 return false;
2118 }
bbbf2d40 2119}
2120
759ac72d 2121
2122/**
2123 * Gets a string for sql calls, searching for stuff in this context or above
ea8158c1 2124 * @param object $context
2125 * @return string
2126 */
2127function get_related_contexts_string($context) {
2128 if ($parents = get_parent_contexts($context)) {
2129 return (' IN ('.$context->id.','.implode(',', $parents).')');
2130 } else {
2131 return (' ='.$context->id);
2132 }
2133}
759ac72d 2134
2135
bbbf2d40 2136/**
2137 * This function gets the capability of a role in a given context.
2138 * It is needed when printing override forms.
2139 * @param int $contextid
bbbf2d40 2140 * @param string $capability
2141 * @param array $capabilities - array loaded using role_context_capabilities
2142 * @return int (allow, prevent, prohibit, inherit)
2143 */
bbbf2d40 2144function get_role_context_capability($contextid, $capability, $capabilities) {
759ac72d 2145 if (isset($capabilities[$contextid][$capability])) {
2146 return $capabilities[$contextid][$capability];
2147 }
2148 else {
2149 return false;
2150 }
bbbf2d40 2151}
2152
2153
cee0901c 2154/**
2155 * Returns the human-readable, translated version of the capability.
2156 * Basically a big switch statement.
2157 * @param $capabilityname - e.g. mod/choice:readresponses
2158 */
ceb83c70 2159function get_capability_string($capabilityname) {
ae9e4c06 2160
cee0901c 2161 // Typical capabilityname is mod/choice:readresponses
ceb83c70 2162
2163 $names = split('/', $capabilityname);
2164 $stringname = $names[1]; // choice:readresponses
2165 $components = split(':', $stringname);
2166 $componentname = $components[0]; // choice
98882637 2167
2168 switch ($names[0]) {
2169 case 'mod':
ceb83c70 2170 $string = get_string($stringname, $componentname);
98882637 2171 break;
2172
2173 case 'block':
ceb83c70 2174 $string = get_string($stringname, 'block_'.$componentname);
98882637 2175 break;
ceb83c70 2176
98882637 2177 case 'moodle':
ceb83c70 2178 $string = get_string($stringname, 'role');
98882637 2179 break;
2180
2181 case 'enrol':
ceb83c70 2182 $string = get_string($stringname, 'enrol_'.$componentname);
2183 break;
98882637 2184
2185 default:
ceb83c70 2186 $string = get_string($stringname);
98882637 2187 break;
98882637 2188
2189 }
ceb83c70 2190 return $string;
bbbf2d40 2191}
2192
2193
cee0901c 2194/**
2195 * This gets the mod/block/course/core etc strings.
2196 * @param $component
2197 * @param $contextlevel
2198 */
bbbf2d40 2199function get_component_string($component, $contextlevel) {
2200
98882637 2201 switch ($contextlevel) {
bbbf2d40 2202
98882637 2203 case CONTEXT_SYSTEM:
be382aaf 2204 if (preg_match('|^enrol/|', $component)) {
2205 $langname = str_replace('/', '_', $component);
2206 $string = get_string('enrolname', $langname);
69eb59f2 2207 } else {
2208 $string = get_string('coresystem');
2209 }
bbbf2d40 2210 break;
2211
2212 case CONTEXT_PERSONAL:
98882637 2213 $string = get_string('personal');
bbbf2d40 2214 break;
2215
4b10f08b 2216 case CONTEXT_USER:
98882637 2217 $string = get_string('users');
bbbf2d40 2218 break;
2219
2220 case CONTEXT_COURSECAT:
98882637 2221 $string = get_string('categories');
bbbf2d40 2222 break;
2223
2224 case CONTEXT_COURSE:
98882637 2225 $string = get_string('course');
bbbf2d40 2226 break;
2227
2228 case CONTEXT_GROUP:
98882637 2229 $string = get_string('group');
bbbf2d40 2230 break;
2231
2232 case CONTEXT_MODULE:
98882637 2233 $string = get_string('modulename', basename($component));
bbbf2d40 2234 break;
2235
2236 case CONTEXT_BLOCK:
98882637 2237 $string = get_string('blockname', 'block_'.$component.'.php');
bbbf2d40 2238 break;
2239
2240 default:
2241 error ('This is an unknown context!');
2242 return false;
98882637 2243
2244 }
98882637 2245 return $string;
bbbf2d40 2246}
cee0901c 2247
759ac72d 2248/**
2249 * Gets the list of roles assigned to this context and up (parents)
945f88ca 2250 * @param object $context
2251 * @return array
2252 */
e4dd3222 2253function get_roles_used_in_context($context) {
2254
2255 global $CFG;
2d9965e1 2256 $contextlist = get_related_contexts_string($context);
759ac72d 2257
2258 $sql = "SELECT DISTINCT r.id,
2259 r.name,
2260 r.shortname,
2261 r.sortorder
2262 FROM {$CFG->prefix}role_assignments ra,
2263 {$CFG->prefix}role r
2264 WHERE r.id = ra.roleid
2265 AND ra.contextid $contextlist
2266 ORDER BY r.sortorder ASC";
2267
2268 return get_records_sql($sql);
e4dd3222 2269}
2270
945f88ca 2271/** this function is used to print roles column in user profile page.
2272 * @param int userid
2273 * @param int contextid
2274 * @return string
2275 */
0a8a95c9 2276function get_user_roles_in_context($userid, $contextid){
2277 global $CFG;
2278
2279 $rolestring = '';
2280 $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';
2281 if ($roles = get_records_sql($SQL)) {
2282 foreach ($roles as $userrole) {
2283 $rolestring .= '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$userrole->contextid.'&amp;roleid='.$userrole->roleid.'">'.$userrole->name.'</a>, ';
2284 }
2285
2286 }
2287 return rtrim($rolestring, ', ');
2288}
68c52526 2289
2290
945f88ca 2291/**
2292 * Checks if a user can override capabilities of a particular role in this context
2293 * @param object $context
2294 * @param int targetroleid - the id of the role you want to override
2295 * @return boolean
2296 */
68c52526 2297function user_can_override($context, $targetroleid) {
2298 // first check if user has override capability
2299 // if not return false;
2300 if (!has_capability('moodle/role:override', $context)) {
2301 return false;
2302 }
2303 // pull out all active roles of this user from this context(or above)
c0614051 2304 if ($userroles = get_user_roles($context)) {
2305 foreach ($userroles as $userrole) {
2306 // if any in the role_allow_override table, then it's ok
2307 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
2308 return true;
2309 }
68c52526 2310 }
2311 }
2312
2313 return false;
2314
2315}
2316
945f88ca 2317/**
2318 * Checks if a user can assign users to a particular role in this context
2319 * @param object $context
2320 * @param int targetroleid - the id of the role you want to assign users to
2321 * @return boolean
2322 */
68c52526 2323function user_can_assign($context, $targetroleid) {
2324
2325 // first check if user has override capability
2326 // if not return false;
2327 if (!has_capability('moodle/role:assign', $context)) {
2328 return false;
2329 }
2330 // pull out all active roles of this user from this context(or above)
c0614051 2331 if ($userroles = get_user_roles($context)) {
2332 foreach ($userroles as $userrole) {
2333 // if any in the role_allow_override table, then it's ok
2334 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
2335 return true;
2336 }
68c52526 2337 }
2338 }
2339
2340 return false;
2341}
2342
945f88ca 2343/**
2344 * gets all the user roles assigned in this context, or higher contexts
2345 * this is mainly used when checking if a user can assign a role, or overriding a role
2346 * i.e. we need to know what this user holds, in order to verify against allow_assign and
2347 * allow_override tables
2348 * @param object $context
2349 * @param int $userid
2350 * @return array
2351 */
5b630667 2352function get_user_roles($context, $userid=0, $checkparentcontexts=true) {
68c52526 2353
2354 global $USER, $CFG, $db;
c0614051 2355
2356 if (empty($userid)) {
2357 if (empty($USER->id)) {
2358 return array();
2359 }
2360 $userid = $USER->id;
2361 }
2362
5b630667 2363 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
2364 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id.')';
c0614051 2365 } else {
5b630667 2366 $contexts = ' ra.contextid = \''.$context->id.'\'';
c0614051 2367 }
2368
31f26796 2369 return get_records_sql('SELECT ra.*, r.name, r.shortname
5b630667 2370 FROM '.$CFG->prefix.'role_assignments ra,
ec6eb110 2371 '.$CFG->prefix.'role r,
2372 '.$CFG->prefix.'context c
c0614051 2373 WHERE ra.userid = '.$userid.
5b630667 2374 ' AND ra.roleid = r.id
ec6eb110 2375 AND ra.contextid = c.id
5b630667 2376 AND '.$contexts.
ec6eb110 2377 ' ORDER BY c.aggregatelevel DESC');
68c52526 2378}
2379
945f88ca 2380/**
2381 * Creates a record in the allow_override table
2382 * @param int sroleid - source roleid
2383 * @param int troleid - target roleid
2384 * @return int - id or false
2385 */
2386function allow_override($sroleid, $troleid) {
2387 $record->roleid = $sroleid;
2388 $record->allowoverride = $troleid;
2389 return insert_record('role_allow_override', $record);
2390}
2391
2392/**
2393 * Creates a record in the allow_assign table
2394 * @param int sroleid - source roleid
2395 * @param int troleid - target roleid
2396 * @return int - id or false
2397 */
2398function allow_assign($sroleid, $troleid) {
ff64aaea 2399 $record = new object;
945f88ca 2400 $record->roleid = $sroleid;
2401 $record->allowassign = $troleid;
2402 return insert_record('role_allow_assign', $record);
2403}
2404
2405/**
ff64aaea 2406 * Gets a list of roles that this user can assign in this context
945f88ca 2407 * @param object $context
2408 * @return array
2409 */
2410function get_assignable_roles ($context) {
2411
945f88ca 2412 $options = array();
ff64aaea 2413
2414 if ($roles = get_records('role')) {
2415 foreach ($roles as $role) {
2416 if (user_can_assign($context, $role->id)) {
2417 $options[$role->id] = $role->name;
2418 }
945f88ca 2419 }
2420 }
2421 return $options;
2422}
2423
2424/**
ff64aaea 2425 * Gets a list of roles that this user can override in this context
945f88ca 2426 * @param object $context
2427 * @return array
2428 */
2429function get_overridable_roles ($context) {
2430
945f88ca 2431 $options = array();
ff64aaea 2432
2433 if ($roles = get_records('role')) {
2434 foreach ($roles as $role) {
2435 if (user_can_override($context, $role->id)) {
2436 $options[$role->id] = $role->name;
2437 }
945f88ca 2438 }
ff64aaea 2439 }
945f88ca 2440
2441 return $options;
945f88ca 2442}
1648afb2 2443
b963384f 2444/*
2445 * Returns a role object that is the default role for new enrolments
2446 * in a given course
2447 *
2448 * @param object $course
2449 * @return object $role
2450 */
2451function get_default_course_role($course) {
2452 global $CFG;
2453
2454/// First let's take the default role the course may have
2455 if (!empty($course->defaultrole)) {
2456 if ($role = get_record('role', 'id', $course->defaultrole)) {
2457 return $role;
2458 }
2459 }
2460
2461/// Otherwise the site setting should tell us
2462 if ($CFG->defaultcourseroleid) {
2463 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid)) {
2464 return $role;
2465 }
2466 }
2467
2468/// It's unlikely we'll get here, but just in case, try and find a student role
2469 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
2470 return array_shift($studentroles); /// Take the first one
2471 }
2472
2473 return NULL;
2474}
2475
1648afb2 2476
2477/**
2478 * who has this capability in this context
2479 * does not handling user level resolving!!!
2480 * i.e 1 person has 2 roles 1 allow, 1 prevent, this will not work properly
2481 * @param $context - object
2482 * @param $capability - string capability
2483 * @param $fields - fields to be pulled
2484 * @param $sort - the sort order
04417640 2485 * @param $limitfrom - number of records to skip (offset)
2486 * @param $limitnum - number of records to fetch
1c45e42e 2487 * @param $groups - single group or array of groups - group(s) user is in
71dea306 2488 * @param $exceptions - list of users to exclude
1648afb2 2489 */
64026e8c 2490function get_users_by_capability($context, $capability, $fields='', $sort='',
2491 $limitfrom='', $limitnum='', $groups='', $exceptions='') {
1648afb2 2492 global $CFG;
2493
64026e8c 2494/// Sorting out groups
1c45e42e 2495 if ($groups) {
71dea306 2496 $groupjoin = 'INNER JOIN '.$CFG->prefix.'groups_members gm ON gm.userid = ra.userid';
1c45e42e 2497
2498 if (is_array($groups)) {
a05708ad 2499 $groupsql = 'AND gm.groupid IN ('.implode(',', $groups).')';
1c45e42e 2500 } else {
a05708ad 2501 $groupsql = 'AND gm.groupid = '.$groups;
1c45e42e 2502 }
2503 } else {
2504 $groupjoin = '';
2505 $groupsql = '';
2506 }
2507
64026e8c 2508/// Sorting out exceptions
5081e786 2509 $exceptionsql = $exceptions ? "AND u.id NOT IN ($exceptions)" : '';
64026e8c 2510
2511/// Set up default fields
2512 if (empty($fields)) {
5b630667 2513 $fields = 'u.*, ul.timeaccess as lastaccess, ra.hidden';
64026e8c 2514 }
2515
2516/// Set up default sort
2517 if (empty($sort)) {
2518 $sort = 'ul.timeaccess';
2519 }
2520
2521 $sortby = $sort ? " ORDER BY $sort " : '';
71dea306 2522
64026e8c 2523/// If context is a course, then construct sql for ul
4e5a0168 2524 if ($context->aggregatelevel == CONTEXT_COURSE) {
71dea306 2525 $courseid = $context->instanceid;
f00b7f8d 2526 $coursesql = "AND (ul.courseid = $courseid OR ul.courseid IS NULL)";
5081e786 2527 } else {
2528 $coursesql = '';
71dea306 2529 }
64026e8c 2530
2531/// Sorting out roles with this capability set
ec7a8b79 2532 $possibleroles = get_roles_with_capability($capability, CAP_ALLOW, $context);
1648afb2 2533 $validroleids = array();
2534 foreach ($possibleroles as $prole) {
2535 $caps = role_context_capabilities($prole->id, $context, $capability); // resolved list
2536 if ($caps[$capability] > 0) { // resolved capability > 0
2537 $validroleids[] = $prole->id;
2538 }
71dea306 2539 }
2540 $roleids = '('.implode(',', $validroleids).')';
64026e8c 2541
2542/// Construct the main SQL
71dea306 2543 $select = " SELECT $fields";
2544 $from = " FROM {$CFG->prefix}user u
2545 INNER JOIN {$CFG->prefix}role_assignments ra ON ra.userid = u.id
2546 LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul ON ul.userid = u.id
2547 $groupjoin";
2548 $where = " WHERE ra.contextid ".get_related_contexts_string($context)."
64026e8c 2549 AND u.deleted = 0
2550 AND ra.roleid in $roleids
71dea306 2551 $exceptionsql
2552 $coursesql
2553 $groupsql";
2554
2555 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
1648afb2 2556}
7700027f 2557
ab5c9044 2558/**
2559 * gets all the users assigned this role in this context or higher
2560 * @param int roleid
2561 * @param int contextid
2562 * @param bool parent if true, get list of users assigned in higher context too
2563 * @return array()
2564 */
2565function get_role_users($roleid, $context, $parent=false) {
2566 global $CFG;
2567
2568 if ($parent) {
2569 if ($contexts = get_parent_contexts($context)) {
2570 $parentcontexts = 'r.contextid IN ('.implode(',', $contexts).')';
2571 } else {
2572 $parentcontexts = '';
2573 }
2574 } else {
2575 $parentcontexts = '';
2576 }
2577
2578 $SQL = "select u.*
2579 from {$CFG->prefix}role_assignments r,
2580 {$CFG->prefix}user u
2581 where (r.contextid = $context->id $parentcontexts)
2582 and r.roleid = $roleid
2583 and u.id = r.userid"; // join now so that we can just use fullname() later
2584
2585 return get_records_sql($SQL);
2586}
2587
d76a5a7f 2588/**
2589 * This function gets the list of courses that this user has a particular capability in
2590 * This is not the most efficient way of doing this
2591 * @param string capability
2592 * @param int $userid
2593 * @return array
2594 */
2595function get_user_capability_course($capability, $userid='') {
2596
2597 global $USER;
2598 if (!$userid) {
2599 $userid = $USER->id;
2600 }
2601
2602 $usercourses = array();
2603 $courses = get_records_select('course', '', '', 'id, id');
2604
2605 foreach ($courses as $course) {
2606 if (has_capability($capability, get_context_capability(CONTEXT_COURSE, $course->id))) {
2607 $usercourses[] = $course;
2608 }
2609 }
2610 return $usercourses;
759ac72d 2611}