accesslib: initial has_capability() rewrite
[moodle.git] / lib / accesslib.php
CommitLineData
6cdd0f9c 1<?php // $Id$
2
3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
8// http://moodle.org //
9// //
10// Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
11// //
12// This program is free software; you can redistribute it and/or modify //
13// it under the terms of the GNU General Public License as published by //
14// the Free Software Foundation; either version 2 of the License, or //
15// (at your option) any later version. //
16// //
17// This program is distributed in the hope that it will be useful, //
18// but WITHOUT ANY WARRANTY; without even the implied warranty of //
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20// GNU General Public License for more details: //
21// //
22// http://www.gnu.org/copyleft/gpl.html //
23// //
24///////////////////////////////////////////////////////////////////////////
25
cee0901c 26 /**
27 * Capability session information format
bbbf2d40 28 * 2 x 2 array
29 * [context][capability]
30 * where context is the context id of the table 'context'
31 * and capability is a string defining the capability
32 * e.g.
33 *
34 * [Capabilities] => [26][mod/forum:viewpost] = 1
35 * [26][mod/forum:startdiscussion] = -8990
36 * [26][mod/forum:editallpost] = -1
37 * [273][moodle:blahblah] = 1
38 * [273][moodle:blahblahblah] = 2
39 */
bbbf2d40 40
cdfa3035 41require_once $CFG->dirroot.'/lib/blocklib.php';
42
bbbf2d40 43// permission definitions
e49e61bf 44define('CAP_INHERIT', 0);
bbbf2d40 45define('CAP_ALLOW', 1);
46define('CAP_PREVENT', -1);
47define('CAP_PROHIBIT', -1000);
48
bbbf2d40 49// context definitions
50define('CONTEXT_SYSTEM', 10);
51define('CONTEXT_PERSONAL', 20);
4b10f08b 52define('CONTEXT_USER', 30);
bbbf2d40 53define('CONTEXT_COURSECAT', 40);
54define('CONTEXT_COURSE', 50);
55define('CONTEXT_GROUP', 60);
56define('CONTEXT_MODULE', 70);
57define('CONTEXT_BLOCK', 80);
58
21b6db6e 59// capability risks - see http://docs.moodle.org/en/Hardening_new_Roles_system
60define('RISK_MANAGETRUST', 0x0001);
a6b02b65 61define('RISK_CONFIG', 0x0002);
21b6db6e 62define('RISK_XSS', 0x0004);
63define('RISK_PERSONAL', 0x0008);
64define('RISK_SPAM', 0x0010);
65
f3f7610c 66require_once($CFG->dirroot.'/group/lib.php');
21b6db6e 67
340ea4e8 68$context_cache = array(); // Cache of all used context objects for performance (by level and instance)
69$context_cache_id = array(); // Index to above cache by id
bbbf2d40 70
7700027f 71
eef879ec 72function get_role_context_caps($roleid, $context) {
73 //this is really slow!!!! - do not use above course context level!
74 $result = array();
75 $result[$context->id] = array();
e7876c1e 76
eef879ec 77 // first emulate the parent context capabilities merging into context
78 $searchcontexts = array_reverse(get_parent_contexts($context));
79 array_push($searchcontexts, $context->id);
80 foreach ($searchcontexts as $cid) {
81 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
82 foreach ($capabilities as $cap) {
83 if (!array_key_exists($cap->capability, $result[$context->id])) {
84 $result[$context->id][$cap->capability] = 0;
85 }
86 $result[$context->id][$cap->capability] += $cap->permission;
87 }
88 }
89 }
e7876c1e 90
eef879ec 91 // now go through the contexts bellow given context
19bb8a05 92 $searchcontexts = array_keys(get_child_contexts($context));
eef879ec 93 foreach ($searchcontexts as $cid) {
94 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
95 foreach ($capabilities as $cap) {
96 if (!array_key_exists($cap->contextid, $result)) {
97 $result[$cap->contextid] = array();
98 }
99 $result[$cap->contextid][$cap->capability] = $cap->permission;
100 }
101 }
e7876c1e 102 }
103
eef879ec 104 return $result;
105}
106
107function get_role_caps($roleid) {
108 $result = array();
109 if ($capabilities = get_records_select('role_capabilities',"roleid = $roleid")) {
110 foreach ($capabilities as $cap) {
111 if (!array_key_exists($cap->contextid, $result)) {
112 $result[$cap->contextid] = array();
113 }
114 $result[$cap->contextid][$cap->capability] = $cap->permission;
115 }
e7876c1e 116 }
eef879ec 117 return $result;
118}
e7876c1e 119
eef879ec 120function merge_role_caps($caps, $mergecaps) {
121 if (empty($mergecaps)) {
122 return $caps;
e7876c1e 123 }
124
eef879ec 125 if (empty($caps)) {
126 return $mergecaps;
e7876c1e 127 }
128
eef879ec 129 foreach ($mergecaps as $contextid=>$capabilities) {
130 if (!array_key_exists($contextid, $caps)) {
131 $caps[$contextid] = array();
132 }
133 foreach ($capabilities as $capability=>$permission) {
134 if (!array_key_exists($capability, $caps[$contextid])) {
135 $caps[$contextid][$capability] = 0;
2b91b669 136 }
eef879ec 137 $caps[$contextid][$capability] += $permission;
2b91b669 138 }
139 }
eef879ec 140 return $caps;
141}
cdfa3035 142
eef879ec 143/**
144 * Loads the capabilities for the default guest role to the current user in a
145 * specific context.
146 * @return object
147 */
148function load_guest_role($return=false) {
149 global $USER;
cdfa3035 150
eef879ec 151 static $guestrole = false;
152
153 if ($guestrole === false) {
154 if (!$guestrole = get_guest_role()) {
155 return false;
e7876c1e 156 }
157 }
158
eef879ec 159 if ($return) {
160 return get_role_caps($guestrole->id);
161 } else {
8d2b18a8 162 has_capability('clearcache');
eef879ec 163 $USER->capabilities = get_role_caps($guestrole->id);
8d2b18a8 164 return true;
8d2b18a8 165 }
e7876c1e 166}
167
7700027f 168/**
169 * Load default not logged in role capabilities when user is not logged in
eef868d1 170 * @return bool
7700027f 171 */
eef879ec 172function load_notloggedin_role($return=false) {
20aeb4b8 173 global $CFG, $USER;
174
21c9bace 175 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
7700027f 176 return false;
35a518c5 177 }
178
7700027f 179 if (empty($CFG->notloggedinroleid)) { // Let's set the default to the guest role
8f8ed475 180 if ($role = get_guest_role()) {
7700027f 181 set_config('notloggedinroleid', $role->id);
182 } else {
183 return false;
184 }
185 }
20aeb4b8 186
eef879ec 187 if ($return) {
188 return get_role_caps($CFG->notloggedinroleid);
189 } else {
99ad7633 190 has_capability('clearcache');
eef879ec 191 $USER->capabilities = get_role_caps($CFG->notloggedinroleid);
192 return true;
20aeb4b8 193 }
20aeb4b8 194}
cee0901c 195
8f8ed475 196/**
eef879ec 197 * Load default logged in role capabilities for all logged in users
eef868d1 198 * @return bool
8f8ed475 199 */
8d2b18a8 200function load_defaultuser_role($return=false) {
8f8ed475 201 global $CFG, $USER;
202
21c9bace 203 if (!$sitecontext = get_context_instance(CONTEXT_SYSTEM)) {
8f8ed475 204 return false;
205 }
206
207 if (empty($CFG->defaultuserroleid)) { // Let's set the default to the guest role
208 if ($role = get_guest_role()) {
209 set_config('defaultuserroleid', $role->id);
210 } else {
211 return false;
212 }
213 }
214
eef879ec 215 $capabilities = get_role_caps($CFG->defaultuserroleid);
8d2b18a8 216
eef879ec 217 // fix the guest user heritage:
218 // If the default role is a guest role, then don't copy legacy:guest,
219 // otherwise this user could get confused with a REAL guest. Also don't copy
c421ad4b 220 // course:view, which is a hack that's necessary because guest roles are
eef879ec 221 // not really handled properly (see MDL-7513)
222 if (!empty($capabilities[$sitecontext->id]['moodle/legacy:guest'])) {
223 unset($capabilities[$sitecontext->id]['moodle/legacy:guest']);
224 unset($capabilities[$sitecontext->id]['moodle/course:view']);
8f8ed475 225 }
226
8d2b18a8 227 if ($return) {
eef879ec 228 return $capabilities;
8d2b18a8 229 } else {
230 has_capability('clearcache');
eef879ec 231 $USER->capabilities = $capabilities;
8d2b18a8 232 return true;
233 }
8f8ed475 234}
235
236
237/**
238 * Get the default guest role
239 * @return object role
240 */
241function get_guest_role() {
ebce32b5 242 global $CFG;
243
244 if (empty($CFG->guestroleid)) {
245 if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
246 $guestrole = array_shift($roles); // Pick the first one
247 set_config('guestroleid', $guestrole->id);
248 return $guestrole;
249 } else {
250 debugging('Can not find any guest role!');
251 return false;
252 }
8f8ed475 253 } else {
ebce32b5 254 if ($guestrole = get_record('role','id', $CFG->guestroleid)) {
255 return $guestrole;
256 } else {
257 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
258 set_config('guestroleid', '');
259 return get_guest_role();
260 }
8f8ed475 261 }
262}
263
264
bbbf2d40 265/**
266 * This functions get all the course categories in proper order
40a2a15f 267 * (!)note this only gets course category contexts, and not the site
268 * context
d963740d 269 * @param object $context
bbbf2d40 270 * @return array of contextids
271 */
3bf618ce 272function get_parent_cats($context) {
273 global $COURSE;
eef868d1 274
3bf618ce 275 switch ($context->contextlevel) {
40a2a15f 276 // a category can be the parent of another category
277 // there is no limit of depth in this case
98882637 278 case CONTEXT_COURSECAT:
3bf618ce 279 static $categoryparents = null; // cache for parent categories
280 if (!isset($categoryparents)) {
281 $categoryparents = array();
282 }
283 if (array_key_exists($context->instanceid, $categoryparents)) {
284 return $categoryparents[$context->instanceid];
c5ddc3fd 285 }
286
3bf618ce 287 if (!$cat = get_record('course_categories','id',$context->instanceid)) {
288 //error?
289 return array();
290 }
291 $parents = array();
c5ddc3fd 292 while (!empty($cat->parent)) {
3bf618ce 293 if (!$catcontext = get_context_instance(CONTEXT_COURSECAT, $cat->parent)) {
294 debugging('Incorrect category parent');
c5ddc3fd 295 break;
296 }
3bf618ce 297 $parents[] = $catcontext->id;
98882637 298 $cat = get_record('course_categories','id',$cat->parent);
299 }
3bf618ce 300 return $categoryparents[$context->instanceid] = array_reverse($parents);
98882637 301 break;
c421ad4b 302
40a2a15f 303 // a course always fall into a category, unless it's a site course
8ba412da 304 // this happens when SITEID == $course->id
40a2a15f 305 // in this case the parent of the course is site context
98882637 306 case CONTEXT_COURSE:
3bf618ce 307 static $courseparents = null; // cache course parents
308 if (!isset($courseparents)) {
309 $courseparents = array();
c5ddc3fd 310 }
3bf618ce 311 if (array_key_exists($context->instanceid, $courseparents)) {
312 return $courseparents[$context->instanceid];
c5ddc3fd 313 }
47ba005d 314
315 if (count($courseparents) > 1000) {
316 $courseparents = array(); // max cache size when looping through thousands of courses
317 }
318
3bf618ce 319 if ($context->instanceid == SITEID) {
320 return $courseparents[$context->instanceid] = array(); // frontpage course does not have parent cats
c5ddc3fd 321 }
3bf618ce 322 if ($context->instanceid == $COURSE->id) {
323 $course = $COURSE;
324 } else if (!$course = get_record('course', 'id', $context->instanceid)) {
325 //error?
326 return array();;
40a2a15f 327 }
c5ddc3fd 328
3bf618ce 329 if (empty($course->category)) {
330 // this should not happen
331 return $courseparents[$context->instanceid] = array();
332 }
c421ad4b 333
3bf618ce 334 if (!$catcontext = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
335 debugging('Incorect course category');
336 return array();;
98882637 337 }
3bf618ce 338
339 return $courseparents[$context->instanceid] = array_merge(get_parent_cats($catcontext), array($catcontext->id)); //recursion :-)
98882637 340 break;
eef868d1 341
98882637 342 default:
3bf618ce 343 // something is very wrong!
344 return array();
98882637 345 break;
98882637 346 }
bbbf2d40 347}
348
349
7f97ea29 350function has_capability($capability, $context=NULL, $userid=NULL, $doanything=true) {
351 global $USER, $CONTEXT, $CFG;
352
353 /// Make sure we know the current context
354 if (empty($context)) { // Use default CONTEXT if none specified
355 if (empty($CONTEXT)) {
356 return false;
357 } else {
358 $context = $CONTEXT;
359 }
360 }
361
362 if (is_null($userid) || $userid===0) {
363 $userid = $USER->id;
364 }
365
366 $contexts = array();
367 if ($context->path === '') {
368 $contexts(SITECONTEXTID, $context->id);
369 } else {
370 $contexts = explode('/', $context->path);
371 array_shift($contexts);
372 }
373
374 if ($USER->id === $userid) {
375 if ($context->contextlevel <= CONTEXT_COURSE) {
376 // Course and above are always preloaded
377 return has_cap_fromsess($capability, $context, $USER->access, $doanything);
378 }
379 ///$coursepath = get_course_from_path($context->path);
380 /// if ($USER->access) {
381 /// $USER->access['courses'] = get_course_access($context, $userid);
cee0901c 382
7f97ea29 383 }
384 error_log("not implemented $userid $capability {$context->contextlevel} {$context->path} ");
385 return has_capability_old($capability, $context, $userid, $doanything);
386 /*
387 if ($context->contextlevel === CONTEXT_COURSE) {
388 if (in_array($context->id, $USER->access_courses)) {
389 }
390 return
391 }
392 if () {
393 }
394
395 return false;*/
396}
397
398function get_course_from_path ($path) {
399 // assume that nothing is more than 1 course deep
400 if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
401 return $matches[1];
402 }
403 return false;
404}
405
406function has_cap_fromsess($capability, $context, $sess, $doanything) {
407
408 $path = $context->path;
409
410 // build $contexts as a list of "paths" of the current
411 // contexts and parents with the order top-to-bottom
412 $contexts = array($path);
413 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
414 $path = $matches[1];
415 array_unshift($contexts, $path);
416 }
417 $cc = count($contexts);
418
419 $can = false;
420 // From the bottom up...
421 for ($n=$cc-1;$n>=0;$n--) {
422 $ctxp = $contexts[$n];
423 if (isset($USER->access['ra'][$ctxp])) {
424 // Found a role assignment
425 $roleid = $sess['ra'][$ctxp];
426 error_log("found ra $roleid for $ctxp");
427 // Walk the path for capabilities
428 // from the bottom up...
429 for ($m=$cc-1;$m>=0;$m--) {
430 $capctxp = $contexts[$m];
431 if (isset($sess['rdef']["{$capctxp}:$roleid"][$capability])) {
432 $perm = $sess['rdef']["{$capctxp}:$roleid"][$capability];
433 error_log("found rc for $roleid for $ctxp in {$capctxp}:$roleid $capability $perm");
434 if ($perm === CAP_PROHIBIT) {
435 return false;
436 } else {
437 $can += $perm;
438 }
439 }
440 }
441 }
442 }
443
444 if ($can < 1) {
445 if ($doanything) {
446 // didn't find it as an explicit cap,
447 // but maybe the user candoanything in this context...
448 return has_cap_fromsess('moodle/site:doanything', $context, $sess, false);
449 } else {
450 return false;
451 }
452 } else {
453 return true;
454 }
455
456}
0468976c 457/**
458 * This function checks for a capability assertion being true. If it isn't
459 * then the page is terminated neatly with a standard error message
460 * @param string $capability - name of the capability
461 * @param object $context - a context object (record from context table)
462 * @param integer $userid - a userid number
d74067e8 463 * @param bool $doanything - if false, ignore do anything
0468976c 464 * @param string $errorstring - an errorstring
d74067e8 465 * @param string $stringfile - which stringfile to get it from
0468976c 466 */
eef868d1 467function require_capability($capability, $context=NULL, $userid=NULL, $doanything=true,
71483894 468 $errormessage='nopermissions', $stringfile='') {
a9e1c058 469
71483894 470 global $USER, $CFG;
a9e1c058 471
71483894 472/// If the current user is not logged in, then make sure they are (if needed)
a9e1c058 473
6605128e 474 if (empty($userid) and empty($USER->capabilities)) {
aad2ba95 475 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
a9e1c058 476 require_login($context->instanceid);
11ac79ff 477 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
478 if ($cm = get_record('course_modules','id',$context->instanceid)) {
71483894 479 if (!$course = get_record('course', 'id', $cm->course)) {
480 error('Incorrect course.');
481 }
482 require_course_login($course, true, $cm);
483
11ac79ff 484 } else {
485 require_login();
486 }
71483894 487 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
488 if (!empty($CFG->forcelogin)) {
489 require_login();
490 }
491
a9e1c058 492 } else {
493 require_login();
494 }
495 }
eef868d1 496
a9e1c058 497/// OK, if they still don't have the capability then print a nice error message
498
d74067e8 499 if (!has_capability($capability, $context, $userid, $doanything)) {
0468976c 500 $capabilityname = get_capability_string($capability);
501 print_error($errormessage, $stringfile, '', $capabilityname);
502 }
503}
504
e6260a45 505/**
506 * Cheks if current user has allowed permission for any of submitted capabilities
507 * in given or child contexts.
508 * @param object $context - a context object (record from context table)
509 * @param array $capabilitynames array of strings, capability names
510 * @return boolean
511 */
512function has_capability_including_child_contexts($context, $capabilitynames) {
513 global $USER;
514
515 foreach ($capabilitynames as $capname) {
516 if (has_capability($capname, $context)) {
517 return true;
518 }
519 }
520
521 if ($children = get_child_contexts($context)) {
522 foreach ($capabilitynames as $capname) {
523 foreach ($children as $child) {
dda63707 524 if (isset($USER->capabilities[$child][$capname]) and $USER->capabilities[$child][$capname] > 0) {
e6260a45 525 // extra check for inherited prevent and prohibit
526 if (has_capability($capname, get_context_instance_by_id($child), $USER->id, false)) {
527 return true;
528 }
529 }
530 }
531 }
532 }
533
534 return false;
535}
0468976c 536
bbbf2d40 537/**
538 * This function returns whether the current user has the capability of performing a function
7d8ea286 539 * For example, we can do has_capability('mod/forum:replypost',$context) in forum
540 * This is a recursive function.
bbbf2d40 541 * @uses $USER
caac8977 542 * @param string $capability - name of the capability (or debugcache or clearcache)
0468976c 543 * @param object $context - a context object (record from context table)
544 * @param integer $userid - a userid number
20aeb4b8 545 * @param bool $doanything - if false, ignore do anything
bbbf2d40 546 * @return bool
547 */
7f97ea29 548function has_capability_old($capability, $context=NULL, $userid=NULL, $doanything=true) {
bbbf2d40 549
20aeb4b8 550 global $USER, $CONTEXT, $CFG;
bbbf2d40 551
c421ad4b 552 static $capcache = array(); // Cache of capabilities
922633bd 553
caac8977 554
555/// Cache management
556
557 if ($capability == 'clearcache') {
558 $capcache = array(); // Clear ALL the capability cache
559 return false;
560 }
561
922633bd 562/// Some sanity checks
6d2d91d6 563 if (debugging('',DEBUG_DEVELOPER)) {
922633bd 564 if ($capability == 'debugcache') {
565 print_object($capcache);
566 return true;
567 }
568 if (!record_exists('capabilities', 'name', $capability)) {
569 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
570 }
571 if ($doanything != true and $doanything != false) {
572 debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
573 }
574 if (!is_object($context) && $context !== NULL) {
575 debugging('Incorrect context parameter "'.$context.'" for has_capability(), object expected! This should be fixed in code.');
576 }
a8a7300a 577 }
578
922633bd 579/// Make sure we know the current context
580 if (empty($context)) { // Use default CONTEXT if none specified
581 if (empty($CONTEXT)) {
582 return false;
583 } else {
584 $context = $CONTEXT;
585 }
586 } else { // A context was given to us
587 if (empty($CONTEXT)) {
588 $CONTEXT = $context; // Store FIRST used context in this global as future default
589 }
590 }
591
592/// Check and return cache in case we've processed this one before.
8d2b18a8 593 $requsteduser = empty($userid) ? $USER->id : $userid; // find out the requested user id, $USER->id might have been changed
594 $cachekey = $capability.'_'.$context->id.'_'.intval($requsteduser).'_'.intval($doanything);
caac8977 595
922633bd 596 if (isset($capcache[$cachekey])) {
597 return $capcache[$cachekey];
598 }
599
20aeb4b8 600
922633bd 601/// Load up the capabilities list or item as necessary
8d2b18a8 602 if ($userid) {
603 if (empty($USER->id) or ($userid != $USER->id) or empty($USER->capabilities)) {
8d2b18a8 604
eef879ec 605 //caching - helps user switching in cron
606 static $guestuserid = false; // guest user id
607 static $guestcaps = false; // guest caps
608 static $defcaps = false; // default user caps - this might help cron
609
610 if ($guestuserid === false) {
8d2b18a8 611 $guestuserid = get_field('user', 'id', 'username', 'guest');
612 }
613
614 if ($userid == $guestuserid) {
eef879ec 615 if ($guestcaps === false) {
616 $guestcaps = load_guest_role(true);
617 }
618 $capabilities = $guestcaps;
8d2b18a8 619
620 } else {
6eaa3f09 621 // This big SQL is expensive! We reduce it a little by avoiding checking for changed enrolments (false)
c421ad4b 622 $capabilities = load_user_capability($capability, $context, $userid, false);
eef879ec 623 if ($defcaps === false) {
8d2b18a8 624 $defcaps = load_defaultuser_role(true);
625 }
eef879ec 626 $capabilities = merge_role_caps($capabilities, $defcaps);
8d2b18a8 627 }
eef879ec 628
629 } else { //$USER->id == $userid and needed capabilities already present
8d2b18a8 630 $capabilities = $USER->capabilities;
9425b25f 631 }
eef879ec 632
9425b25f 633 } else { // no userid
8d2b18a8 634 if (empty($USER->capabilities)) {
eef879ec 635 load_all_capabilities(); // expensive - but we have to do it once anyway
8d2b18a8 636 }
637 $capabilities = $USER->capabilities;
922633bd 638 $userid = $USER->id;
98882637 639 }
9425b25f 640
caac8977 641/// We act a little differently when switchroles is active
642
643 $switchroleactive = false; // Assume it isn't active in this context
644
bbbf2d40 645
922633bd 646/// First deal with the "doanything" capability
5fe9a11d 647
20aeb4b8 648 if ($doanything) {
2d07587b 649
f4e2d38a 650 /// First make sure that we aren't in a "switched role"
651
f4e2d38a 652 if (!empty($USER->switchrole)) { // Switchrole is active somewhere!
653 if (!empty($USER->switchrole[$context->id])) { // Because of current context
c421ad4b 654 $switchroleactive = true;
f4e2d38a 655 } else { // Check parent contexts
656 if ($parentcontextids = get_parent_contexts($context)) {
657 foreach ($parentcontextids as $parentcontextid) {
658 if (!empty($USER->switchrole[$parentcontextid])) { // Yep, switchroles active here
c421ad4b 659 $switchroleactive = true;
f4e2d38a 660 break;
661 }
662 }
663 }
664 }
665 }
666
c421ad4b 667 /// Check the site context for doanything (most common) first
f4e2d38a 668
669 if (empty($switchroleactive)) { // Ignore site setting if switchrole is active
21c9bace 670 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2d07587b 671 if (isset($capabilities[$sitecontext->id]['moodle/site:doanything'])) {
922633bd 672 $result = (0 < $capabilities[$sitecontext->id]['moodle/site:doanything']);
673 $capcache[$cachekey] = $result;
674 return $result;
2d07587b 675 }
20aeb4b8 676 }
40a2a15f 677 /// If it's not set at site level, it is possible to be set on other levels
678 /// Though this usage is not common and can cause risks
aad2ba95 679 switch ($context->contextlevel) {
eef868d1 680
20aeb4b8 681 case CONTEXT_COURSECAT:
682 // Check parent cats.
3bf618ce 683 $parentcats = get_parent_cats($context);
20aeb4b8 684 foreach ($parentcats as $parentcat) {
685 if (isset($capabilities[$parentcat]['moodle/site:doanything'])) {
922633bd 686 $result = (0 < $capabilities[$parentcat]['moodle/site:doanything']);
687 $capcache[$cachekey] = $result;
688 return $result;
20aeb4b8 689 }
cee0901c 690 }
20aeb4b8 691 break;
bbbf2d40 692
20aeb4b8 693 case CONTEXT_COURSE:
694 // Check parent cat.
3bf618ce 695 $parentcats = get_parent_cats($context);
98882637 696
20aeb4b8 697 foreach ($parentcats as $parentcat) {
698 if (isset($capabilities[$parentcat]['do_anything'])) {
922633bd 699 $result = (0 < $capabilities[$parentcat]['do_anything']);
700 $capcache[$cachekey] = $result;
701 return $result;
20aeb4b8 702 }
9425b25f 703 }
20aeb4b8 704 break;
bbbf2d40 705
20aeb4b8 706 case CONTEXT_GROUP:
707 // Find course.
5bf243d1 708 $courseid = get_field('groups', 'courseid', 'id', $context->instanceid);
f3f7610c 709 $courseinstance = get_context_instance(CONTEXT_COURSE, $courseid);
9425b25f 710
3bf618ce 711 $parentcats = get_parent_cats($courseinstance);
20aeb4b8 712 foreach ($parentcats as $parentcat) {
b4a1805a 713 if (isset($capabilities[$parentcat]['do_anything'])) {
714 $result = (0 < $capabilities[$parentcat]['do_anything']);
922633bd 715 $capcache[$cachekey] = $result;
716 return $result;
20aeb4b8 717 }
9425b25f 718 }
9425b25f 719
20aeb4b8 720 $coursecontext = '';
721 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
922633bd 722 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
723 $capcache[$cachekey] = $result;
724 return $result;
20aeb4b8 725 }
9425b25f 726
20aeb4b8 727 break;
bbbf2d40 728
20aeb4b8 729 case CONTEXT_MODULE:
730 // Find course.
731 $cm = get_record('course_modules', 'id', $context->instanceid);
732 $courseinstance = get_context_instance(CONTEXT_COURSE, $cm->course);
9425b25f 733
3bf618ce 734 if ($parentcats = get_parent_cats($courseinstance)) {
20aeb4b8 735 foreach ($parentcats as $parentcat) {
736 if (isset($capabilities[$parentcat]['do_anything'])) {
922633bd 737 $result = (0 < $capabilities[$parentcat]['do_anything']);
738 $capcache[$cachekey] = $result;
739 return $result;
20aeb4b8 740 }
cee0901c 741 }
9425b25f 742 }
98882637 743
20aeb4b8 744 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
922633bd 745 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
746 $capcache[$cachekey] = $result;
747 return $result;
20aeb4b8 748 }
bbbf2d40 749
20aeb4b8 750 break;
bbbf2d40 751
20aeb4b8 752 case CONTEXT_BLOCK:
2d95f702 753 // not necessarily 1 to 1 to course.
20aeb4b8 754 $block = get_record('block_instance','id',$context->instanceid);
2d95f702 755 if ($block->pagetype == 'course-view') {
756 $courseinstance = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
3bf618ce 757 $parentcats = get_parent_cats($courseinstance);
c421ad4b 758
2d95f702 759 foreach ($parentcats as $parentcat) {
760 if (isset($capabilities[$parentcat]['do_anything'])) {
761 $result = (0 < $capabilities[$parentcat]['do_anything']);
762 $capcache[$cachekey] = $result;
763 return $result;
764 }
765 }
c421ad4b 766
2d95f702 767 if (isset($capabilities[$courseinstance->id]['do_anything'])) {
768 $result = (0 < $capabilities[$courseinstance->id]['do_anything']);
769 $capcache[$cachekey] = $result;
770 return $result;
771 }
20aeb4b8 772 }
c331cf23 773 // blocks that do not have course as parent do not need to do any more checks - already done above
774
20aeb4b8 775 break;
bbbf2d40 776
20aeb4b8 777 default:
4b10f08b 778 // CONTEXT_SYSTEM: CONTEXT_PERSONAL: CONTEXT_USER:
40a2a15f 779 // Do nothing, because the parents are site context
780 // which has been checked already
20aeb4b8 781 break;
782 }
bbbf2d40 783
20aeb4b8 784 // Last: check self.
785 if (isset($capabilities[$context->id]['do_anything'])) {
922633bd 786 $result = (0 < $capabilities[$context->id]['do_anything']);
787 $capcache[$cachekey] = $result;
788 return $result;
20aeb4b8 789 }
98882637 790 }
caac8977 791 // do_anything has not been set, we now look for it the normal way.
792 $result = (0 < capability_search($capability, $context, $capabilities, $switchroleactive));
922633bd 793 $capcache[$cachekey] = $result;
794 return $result;
bbbf2d40 795
9425b25f 796}
bbbf2d40 797
798
799/**
800 * In a separate function so that we won't have to deal with do_anything.
40a2a15f 801 * again. Used by function has_capability().
bbbf2d40 802 * @param $capability - capability string
0468976c 803 * @param $context - the context object
40a2a15f 804 * @param $capabilities - either $USER->capability or loaded array (for other users)
bbbf2d40 805 * @return permission (int)
806 */
caac8977 807function capability_search($capability, $context, $capabilities, $switchroleactive=false) {
759ac72d 808
3bf618ce 809 global $USER, $CFG, $COURSE;
0468976c 810
11ac79ff 811 if (!isset($context->id)) {
812 return 0;
813 }
c421ad4b 814 // if already set in the array explicitly, no need to look for it in parent
40a2a15f 815 // context any longer
0468976c 816 if (isset($capabilities[$context->id][$capability])) {
817 return ($capabilities[$context->id][$capability]);
bbbf2d40 818 }
9425b25f 819
bbbf2d40 820 /* Then, we check the cache recursively */
9425b25f 821 $permission = 0;
822
aad2ba95 823 switch ($context->contextlevel) {
bbbf2d40 824
825 case CONTEXT_SYSTEM: // by now it's a definite an inherit
826 $permission = 0;
827 break;
828
829 case CONTEXT_PERSONAL:
21c9bace 830 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
a2b6ee75 831 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 832 break;
9425b25f 833
4b10f08b 834 case CONTEXT_USER:
21c9bace 835 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
a2b6ee75 836 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 837 break;
9425b25f 838
3bf618ce 839 case CONTEXT_COURSE:
840 if ($switchroleactive) {
841 // if switchrole active, do not check permissions above the course context, blocks are an exception
842 break;
bbbf2d40 843 }
3bf618ce 844 // break is not here intentionally - because the code is the same for category and course
845 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
846 $parents = get_parent_cats($context); // cached internally
bbbf2d40 847
3bf618ce 848 // non recursive - should be faster
849 foreach ($parents as $parentid) {
850 $parentcontext = get_context_instance_by_id($parentid);
851 if (isset($capabilities[$parentcontext->id][$capability])) {
852 return ($capabilities[$parentcontext->id][$capability]);
caac8977 853 }
40a2a15f 854 }
3bf618ce 855 // finally check system context
856 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
857 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 858 break;
859
860 case CONTEXT_GROUP: // 1 to 1 to course
5bf243d1 861 $courseid = get_field('groups', 'courseid', 'id', $context->instanceid);
f3f7610c 862 $parentcontext = get_context_instance(CONTEXT_COURSE, $courseid);
a2b6ee75 863 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 864 break;
865
866 case CONTEXT_MODULE: // 1 to 1 to course
867 $cm = get_record('course_modules','id',$context->instanceid);
0468976c 868 $parentcontext = get_context_instance(CONTEXT_COURSE, $cm->course);
a2b6ee75 869 $permission = capability_search($capability, $parentcontext, $capabilities, $switchroleactive);
bbbf2d40 870 break;
871
2d95f702 872 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
bbbf2d40 873 $block = get_record('block_instance','id',$context->instanceid);
2d95f702 874 if ($block->pagetype == 'course-view') {
875 $parentcontext = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
876 } else {
c421ad4b 877 $parentcontext = get_context_instance(CONTEXT_SYSTEM);
c331cf23 878 }
879 // ignore the $switchroleactive beause we want the real block view capability defined in system context
880 $permission = capability_search($capability, $parentcontext, $capabilities, false);
bbbf2d40 881 break;
882
883 default:
8388ade8 884 error ('This is an unknown context (' . $context->contextlevel . ') in capability_search!');
bbbf2d40 885 return false;
886 }
9425b25f 887
98882637 888 return $permission;
bbbf2d40 889}
890
40a2a15f 891/**
892 * auxillary function for load_user_capabilities()
893 * checks if context c1 is a parent (or itself) of context c2
894 * @param int $c1 - context id of context 1
895 * @param int $c2 - context id of context 2
896 * @return bool
897 */
9fccc080 898function is_parent_context($c1, $c2) {
899 static $parentsarray;
c421ad4b 900
9fccc080 901 // context can be itself and this is ok
902 if ($c1 == $c2) {
c421ad4b 903 return true;
9fccc080 904 }
905 // hit in cache?
906 if (isset($parentsarray[$c1][$c2])) {
907 return $parentsarray[$c1][$c2];
908 }
c421ad4b 909
9fccc080 910 if (!$co2 = get_record('context', 'id', $c2)) {
911 return false;
912 }
913
914 if (!$parents = get_parent_contexts($co2)) {
915 return false;
916 }
c421ad4b 917
9fccc080 918 foreach ($parents as $parent) {
919 $parentsarray[$parent][$c2] = true;
920 }
921
922 if (in_array($c1, $parents)) {
c421ad4b 923 return true;
9fccc080 924 } else { // else not a parent, set the cache anyway
925 $parentsarray[$c1][$c2] = false;
926 return false;
927 }
928}
929
930
efe12f6c 931/**
9fccc080 932 * auxillary function for load_user_capabilities()
933 * handler in usort() to sort contexts according to level
40a2a15f 934 * @param object contexta
935 * @param object contextb
936 * @return int
9fccc080 937 */
938function roles_context_cmp($contexta, $contextb) {
939 if ($contexta->contextlevel == $contextb->contextlevel) {
940 return 0;
941 }
942 return ($contexta->contextlevel < $contextb->contextlevel) ? -1 : 1;
943}
944
bbbf2d40 945/**
bbbf2d40 946 * It will build an array of all the capabilities at each level
947 * i.e. site/metacourse/course_category/course/moduleinstance
948 * Note we should only load capabilities if they are explicitly assigned already,
949 * we should not load all module's capability!
21c9bace 950 *
bbbf2d40 951 * [Capabilities] => [26][forum_post] = 1
952 * [26][forum_start] = -8990
953 * [26][forum_edit] = -1
954 * [273][blah blah] = 1
955 * [273][blah blah blah] = 2
21c9bace 956 *
957 * @param $capability string - Only get a specific capability (string)
958 * @param $context object - Only get capabilities for a specific context object
959 * @param $userid integer - the id of the user whose capabilities we want to load
c3d1fbe9 960 * @param $checkenrolments boolean - Should we check enrolment plugins (potentially expensive)
21c9bace 961 * @return array of permissions (or nothing if they get assigned to $USER)
bbbf2d40 962 */
6eaa3f09 963function load_user_capability($capability='', $context=NULL, $userid=NULL, $checkenrolments=true) {
d140ad3f 964
98882637 965 global $USER, $CFG;
55526eee 966
c421ad4b 967 // this flag has not been set!
40a2a15f 968 // (not clean install, or upgraded successfully to 1.7 and up)
2f1a4248 969 if (empty($CFG->rolesactive)) {
970 return false;
971 }
972
bbbf2d40 973 if (empty($userid)) {
dc411d1b 974 if (empty($USER->id)) { // We have no user to get capabilities for
64026e8c 975 debugging('User not logged in for load_user_capability!');
dc411d1b 976 return false;
977 }
64026e8c 978 unset($USER->capabilities); // We don't want possible older capabilites hanging around
979
6eaa3f09 980 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
c421ad4b 981 check_enrolment_plugins($USER);
6eaa3f09 982 }
8f8ed475 983
bbbf2d40 984 $userid = $USER->id;
dc411d1b 985 $otheruserid = false;
bbbf2d40 986 } else {
64026e8c 987 if (!$user = get_record('user', 'id', $userid)) {
988 debugging('Non-existent userid in load_user_capability!');
989 return false;
990 }
991
6eaa3f09 992 if ($checkenrolments) { // Call "enrol" system to ensure that we have the correct picture
993 check_enrolment_plugins($user);
994 }
64026e8c 995
9425b25f 996 $otheruserid = $userid;
bbbf2d40 997 }
9425b25f 998
5f70bcc3 999
1000/// First we generate a list of all relevant contexts of the user
1001
1002 $usercontexts = array();
bbbf2d40 1003
0468976c 1004 if ($context) { // if context is specified
eef868d1 1005 $usercontexts = get_parent_contexts($context);
9343a733 1006 $usercontexts[] = $context->id; // Add the current context as well
98882637 1007 } else { // else, we load everything
5f70bcc3 1008 if ($userroles = get_records('role_assignments','userid',$userid)) {
1009 foreach ($userroles as $userrole) {
0db6adc9 1010 if (!in_array($userrole->contextid, $usercontexts)) {
1011 $usercontexts[] = $userrole->contextid;
1012 }
5f70bcc3 1013 }
98882637 1014 }
5f70bcc3 1015 }
1016
1017/// Set up SQL fragments for searching contexts
1018
1019 if ($usercontexts) {
0468976c 1020 $listofcontexts = '('.implode(',', $usercontexts).')';
5f70bcc3 1021 $searchcontexts1 = "c1.id IN $listofcontexts AND";
5f70bcc3 1022 } else {
c76e095f 1023 $searchcontexts1 = '';
bbbf2d40 1024 }
3ca2dea5 1025
64026e8c 1026 if ($capability) {
afe41398 1027 // the doanything may override the requested capability
1028 $capsearch = " AND (rc.capability = '$capability' OR rc.capability = 'moodle/site:doanything') ";
64026e8c 1029 } else {
eef868d1 1030 $capsearch ="";
64026e8c 1031 }
1032
5f70bcc3 1033/// Then we use 1 giant SQL to bring out all relevant capabilities.
1034/// The first part gets the capabilities of orginal role.
1035/// The second part gets the capabilities of overriden roles.
bbbf2d40 1036
21c9bace 1037 $siteinstance = get_context_instance(CONTEXT_SYSTEM);
9fccc080 1038 $capabilities = array(); // Reinitialize.
c421ad4b 1039
9fccc080 1040 // SQL for normal capabilities
1041 $SQL1 = "SELECT rc.capability, c1.id as id1, c1.id as id2, (c1.contextlevel * 100) AS aggrlevel,
bbbf2d40 1042 SUM(rc.permission) AS sum
1043 FROM
eef868d1 1044 {$CFG->prefix}role_assignments ra,
42ac3ecf 1045 {$CFG->prefix}role_capabilities rc,
1046 {$CFG->prefix}context c1
bbbf2d40 1047 WHERE
d4649c76 1048 ra.contextid=c1.id AND
1049 ra.roleid=rc.roleid AND
bbbf2d40 1050 ra.userid=$userid AND
5f70bcc3 1051 $searchcontexts1
eef868d1 1052 rc.contextid=$siteinstance->id
98882637 1053 $capsearch
bbbf2d40 1054 GROUP BY
55526eee 1055 rc.capability, c1.id, c1.contextlevel * 100
bbbf2d40 1056 HAVING
c421ad4b 1057 SUM(rc.permission) != 0
1058
0db6adc9 1059 UNION ALL
c421ad4b 1060
1061 SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
0db6adc9 1062 SUM(rc.permission) AS sum
1063 FROM
cd54510d 1064 {$CFG->prefix}role_assignments ra INNER JOIN
1065 {$CFG->prefix}role_capabilities rc on ra.roleid = rc.roleid INNER JOIN
1066 {$CFG->prefix}context c1 on ra.contextid = c1.id INNER JOIN
1067 {$CFG->prefix}context c2 on rc.contextid = c2.id INNER JOIN
1068 {$CFG->prefix}context_rel cr on cr.c1 = c2.id AND cr.c2 = c1.id
0db6adc9 1069 WHERE
1070 ra.userid=$userid AND
1071 $searchcontexts1
1072 rc.contextid != $siteinstance->id
1073 $capsearch
0db6adc9 1074 GROUP BY
55526eee 1075 rc.capability, c1.id, c2.id, c1.contextlevel * 100 + c2.contextlevel
0db6adc9 1076 HAVING
1077 SUM(rc.permission) != 0
9fccc080 1078 ORDER BY
1079 aggrlevel ASC";
0db6adc9 1080
9fccc080 1081 if (!$rs = get_recordset_sql($SQL1)) {
1082 error("Query failed in load_user_capability.");
1083 }
bbbf2d40 1084
9fccc080 1085 if ($rs && $rs->RecordCount() > 0) {
bcf88cbb 1086 while ($caprec = rs_fetch_next_record($rs)) {
1087 $array = (array)$caprec;
9fccc080 1088 $temprecord = new object;
1089
1090 foreach ($array as $key=>$val) {
1091 if ($key == 'aggrlevel') {
1092 $temprecord->contextlevel = $val;
1093 } else {
1094 $temprecord->{$key} = $val;
1095 }
1096 }
9fccc080 1097 $capabilities[] = $temprecord;
9fccc080 1098 }
bcf88cbb 1099 rs_close($rs);
b7e40271 1100 }
bcf88cbb 1101
9fccc080 1102 // SQL for overrides
1103 // this is take out because we have no way of making sure c1 is indeed related to c2 (parent)
1104 // if we do not group by sum, it is possible to have multiple records of rc.capability, c1.id, c2.id, tuple having
1105 // different values, we can maually sum it when we go through the list
c421ad4b 1106
1107 /*
1108
9fccc080 1109 $SQL2 = "SELECT rc.capability, c1.id as id1, c2.id as id2, (c1.contextlevel * 100 + c2.contextlevel) AS aggrlevel,
1110 rc.permission AS sum
bbbf2d40 1111 FROM
42ac3ecf 1112 {$CFG->prefix}role_assignments ra,
1113 {$CFG->prefix}role_capabilities rc,
1114 {$CFG->prefix}context c1,
1115 {$CFG->prefix}context c2
bbbf2d40 1116 WHERE
d4649c76 1117 ra.contextid=c1.id AND
eef868d1 1118 ra.roleid=rc.roleid AND
1119 ra.userid=$userid AND
1120 rc.contextid=c2.id AND
5f70bcc3 1121 $searchcontexts1
5f70bcc3 1122 rc.contextid != $siteinstance->id
bbbf2d40 1123 $capsearch
eef868d1 1124
bbbf2d40 1125 GROUP BY
21c9bace 1126 rc.capability, (c1.contextlevel * 100 + c2.contextlevel), c1.id, c2.id, rc.permission
bbbf2d40 1127 ORDER BY
75e84883 1128 aggrlevel ASC
0db6adc9 1129 ";*/
9fccc080 1130
0db6adc9 1131/*
9fccc080 1132 if (!$rs = get_recordset_sql($SQL2)) {
75e84883 1133 error("Query failed in load_user_capability.");
1134 }
5cf38a57 1135
bbbf2d40 1136 if ($rs && $rs->RecordCount() > 0) {
bcf88cbb 1137 while ($caprec = rs_fetch_next_record($rs)) {
1138 $array = (array)$caprec;
75e84883 1139 $temprecord = new object;
eef868d1 1140
98882637 1141 foreach ($array as $key=>$val) {
75e84883 1142 if ($key == 'aggrlevel') {
aad2ba95 1143 $temprecord->contextlevel = $val;
75e84883 1144 } else {
1145 $temprecord->{$key} = $val;
1146 }
98882637 1147 }
9fccc080 1148 // for overrides, we have to make sure that context2 is a child of context1
1149 // otherwise the combination makes no sense
0db6adc9 1150 //if (is_parent_context($temprecord->id1, $temprecord->id2)) {
9fccc080 1151 $capabilities[] = $temprecord;
0db6adc9 1152 //} // only write if relevant
bbbf2d40 1153 }
bcf88cbb 1154 rs_close($rs);
bbbf2d40 1155 }
0db6adc9 1156
9fccc080 1157 // this step sorts capabilities according to the contextlevel
c421ad4b 1158 // it is very important because the order matters when we
9fccc080 1159 // go through each capabilities later. (i.e. higher level contextlevel
1160 // will override lower contextlevel settings
1161 usort($capabilities, 'roles_context_cmp');
0db6adc9 1162*/
bbbf2d40 1163 /* so up to this point we should have somethign like this
aad2ba95 1164 * $capabilities[1] ->contextlevel = 1000
8ba412da 1165 ->module = 0 // changed from SITEID in 1.8 (??)
bbbf2d40 1166 ->capability = do_anything
1167 ->id = 1 (id is the context id)
1168 ->sum = 0
eef868d1 1169
aad2ba95 1170 * $capabilities[2] ->contextlevel = 1000
8ba412da 1171 ->module = 0 // changed from SITEID in 1.8 (??)
bbbf2d40 1172 ->capability = post_messages
1173 ->id = 1
1174 ->sum = -9000
1175
aad2ba95 1176 * $capabilittes[3] ->contextlevel = 3000
bbbf2d40 1177 ->module = course
1178 ->capability = view_course_activities
1179 ->id = 25
1180 ->sum = 1
1181
aad2ba95 1182 * $capabilittes[4] ->contextlevel = 3000
bbbf2d40 1183 ->module = course
1184 ->capability = view_course_activities
1185 ->id = 26
1186 ->sum = 0 (this is another course)
eef868d1 1187
aad2ba95 1188 * $capabilities[5] ->contextlevel = 3050
bbbf2d40 1189 ->module = course
1190 ->capability = view_course_activities
1191 ->id = 25 (override in course 25)
1192 ->sum = -1
1193 * ....
1194 * now we proceed to write the session array, going from top to bottom
1195 * at anypoint, we need to go up and check parent to look for prohibit
1196 */
1197 // print_object($capabilities);
1198
1199 /* This is where we write to the actualy capabilities array
1200 * what we need to do from here on is
1201 * going down the array from lowest level to highest level
1202 * 1) recursively check for prohibit,
1203 * if any, we write prohibit
1204 * else, we write the value
1205 * 2) at an override level, we overwrite current level
1206 * if it's not set to prohibit already, and if different
1207 * ........ that should be it ........
1208 */
c421ad4b 1209
efb58884 1210 // This is the flag used for detecting the current context level. Since we are going through
c421ad4b 1211 // the array in ascending order of context level. For normal capabilities, there should only
1212 // be 1 value per (capability, contextlevel, context), because they are already summed. But,
1213 // for overrides, since we are processing them separate, we need to sum the relevcant entries.
efb58884 1214 // We set this flag when we hit a new level.
c421ad4b 1215 // If the flag is already set, we keep adding (summing), otherwise, we just override previous
1216 // settings (from lower level contexts)
efb58884 1217 $capflags = array(); // (contextid, contextlevel, capability)
98882637 1218 $usercap = array(); // for other user's capabilities
bbbf2d40 1219 foreach ($capabilities as $capability) {
1220
9fccc080 1221 if (!$context = get_context_instance_by_id($capability->id2)) {
7bfa3101 1222 continue; // incorrect stale context
1223 }
0468976c 1224
41811960 1225 if (!empty($otheruserid)) { // we are pulling out other user's capabilities, do not write to session
eef868d1 1226
0468976c 1227 if (capability_prohibits($capability->capability, $context, $capability->sum, $usercap)) {
9fccc080 1228 $usercap[$capability->id2][$capability->capability] = CAP_PROHIBIT;
98882637 1229 continue;
1230 }
efb58884 1231 if (isset($usercap[$capability->id2][$capability->capability])) { // use isset because it can be sum 0
1232 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1233 $usercap[$capability->id2][$capability->capability] += $capability->sum;
1234 } else { // else we override, and update flag
1235 $usercap[$capability->id2][$capability->capability] = $capability->sum;
1236 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1237 }
9fccc080 1238 } else {
1239 $usercap[$capability->id2][$capability->capability] = $capability->sum;
efb58884 1240 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
9fccc080 1241 }
eef868d1 1242
98882637 1243 } else {
1244
0468976c 1245 if (capability_prohibits($capability->capability, $context, $capability->sum)) { // if any parent or parent's parent is set to prohibit
9fccc080 1246 $USER->capabilities[$capability->id2][$capability->capability] = CAP_PROHIBIT;
98882637 1247 continue;
1248 }
eef868d1 1249
98882637 1250 // if no parental prohibit set
1251 // just write to session, i am not sure this is correct yet
1252 // since 3050 shows up after 3000, and 3070 shows up after 3050,
1253 // it should be ok just to overwrite like this, provided that there's no
1254 // parental prohibits
98882637 1255 // we need to write even if it's 0, because it could be an inherit override
efb58884 1256 if (isset($USER->capabilities[$capability->id2][$capability->capability])) {
1257 if (!empty($capflags[$capability->id2][$capability->contextlevel][$capability->capability])) {
1258 $USER->capabilities[$capability->id2][$capability->capability] += $capability->sum;
1259 } else { // else we override, and update flag
1260 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
1261 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
1262 }
9fccc080 1263 } else {
1264 $USER->capabilities[$capability->id2][$capability->capability] = $capability->sum;
efb58884 1265 $capflags[$capability->id2][$capability->contextlevel][$capability->capability] = true;
9fccc080 1266 }
98882637 1267 }
bbbf2d40 1268 }
eef868d1 1269
bbbf2d40 1270 // now we don't care about the huge array anymore, we can dispose it.
1271 unset($capabilities);
efb58884 1272 unset($capflags);
eef868d1 1273
dbe7e582 1274 if (!empty($otheruserid)) {
eef868d1 1275 return $usercap; // return the array
bbbf2d40 1276 }
2f1a4248 1277}
1278
a9bee37e 1279/**
1280 * It will return 2 arrays showing role assignments
1281 * all relevant role capabilities for the user at
1282 * site/metacourse/course_category/course levels
1283 *
1284 * We do _not_ delve deeper than courses because the number of
1285 * overrides at the module/block levels is HUGE.
1286 *
1287 * [ra] => [/path/] = roleid
1288 * [rdef] => [/path/:roleid][capability]=permission
1289 *
1290 * @param $userid integer - the id of the user
1291 *
1292 */
1293function get_user_sitewide_access($userid) {
1294
1295 global $CFG;
1296
1297 // this flag has not been set!
1298 // (not clean install, or upgraded successfully to 1.7 and up)
1299 if (empty($CFG->rolesactive)) {
1300 return false;
1301 }
1302
1303 /* Get in 3 cheap DB queries...
1304 * - role assignments - with role_caps
1305 * - relevant role caps
1306 * - above this user's RAs
1307 * - below this user's RAs - limited to course level
1308 */
1309
1310 $sw = array(); // named list
1311 $sw['ra'] = array();
1312 $sw['rdef'] = array();
1313
1314 $sitectx = get_field('context', 'id','contextlevel', CONTEXT_SYSTEM);
1315 $base = "/$sitectx";
1316
1317 //
1318 // Role assignments - and any rolecaps directly linked
1319 // because it's cheap to read rolecaps here over many
1320 // RAs
1321 //
1322 $sql = "SELECT ctx.path, ra.roleid, rc.capability, rc.permission
1323 FROM {$CFG->prefix}role_assignments ra
1324 JOIN {$CFG->prefix}context ctx
1325 ON ra.contextid=ctx.id
1326 LEFT OUTER JOIN {$CFG->prefix}role_capabilities rc
1327 ON (rc.roleid=ra.roleid AND rc.contextid=ra.contextid)
1328 WHERE ra.userid = $userid AND ctx.contextlevel <= ".CONTEXT_COURSE."
1329 ORDER BY ctx.depth, ctx.path";
1330 $rs = get_recordset_sql($sql);
1331 // parent paths & roles we need to walk up
1332 // this array will bulk up quite a bit with dups
1333 // which we'll later clear up
1334 $raparents = array();
1335 if ($rs->RecordCount()) {
1336 while ($ra = rs_fetch_next_record($rs)) {
1337 $sw['ra'][$ra->path] = $ra->roleid;
1338 if (!empty($ra->capability)) {
1339 $k = "{$ra->path}:{$ra->roleid}";
1340 $sw['rdef'][$k][$ra->capability] = $ra->permission;
1341 }
1342 $parentids = explode('/', $ra->path);
1343 array_pop($parentids); array_shift($parentids);
1344 if (isset($raparents[$ra->roleid])) {
1345 $raparents[$ra->roleid] = array_merge($raparents[$ra->roleid], $parentids);
1346 } else {
1347 $raparents[$ra->roleid] = $parentids;
1348 }
1349 }
1350 }
1351 rs_close($rs);
1352
1353 // Walk up the tree to grab all the roledefs
1354 // of interest to our user...
1355 // NOTE: we use a series of IN clauses here - which
1356 // might explode on huge sites with very convoluted nesting of
1357 // categories... - extremely unlikely that the number of categories
1358 // and roletypes is so large that we hit the limits of IN()
1359 $clauses = array();
1360 foreach ($raparents as $roleid=>$contexts) {
1361 $contexts = sql_intarray_to_in(array_unique($contexts));
1362 if ($contexts ==! '') {
1363 $clauses[] = "(roleid=$roleid AND contextid IN ($contexts))";
1364 }
1365 }
1366 $clauses = join(" OR ", $clauses);
1367 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1368 FROM {$CFG->prefix}role_capabilities rc
1369 JOIN {$CFG->prefix}context ctx
1370 ON rc.contextid=ctx.id
1371 WHERE $clauses
1372 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1373
1374 $rs = get_recordset_sql($sql);
1375
1376 if ($rs->RecordCount()) {
1377 while ($rd = rs_fetch_next_record($rs)) {
1378 $k = "{$rd->path}:{$rd->roleid}";
1379 $sw['rdef'][$k][$rd->capability] = $rd->permission;
1380 }
1381 }
1382 rs_close($rs);
1383
1384 //
1385 // Overrides for the role assignments IN SUBCONTEXTS
1386 // (though we still do _not_ go below the course level.
1387 //
1388 // NOTE that the JOIN w sctx is with 3-way triangulation to
1389 // catch overrides to the applicable role in any subcontext, based
1390 // on the path field of the parent.
1391 //
1392 $sql = "SELECT sctx.path, ra.roleid,
1393 ctx.path AS parentpath,
1394 rco.capability, rco.permission
1395 FROM {$CFG->prefix}role_assignments ra
1396 JOIN {$CFG->prefix}context ctx
1397 ON ra.contextid=ctx.id
1398 JOIN {$CFG->prefix}context sctx
1399 ON (sctx.path LIKE ctx.path||'/%')
1400 JOIN {$CFG->prefix}role_capabilities rco
1401 ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
1402 WHERE ra.userid = $userid
1403 AND sctx.contextlevel <= ".CONTEXT_COURSE."
1404 ORDER BY sctx.depth, sctx.path, $ra.roleid";
1405 if ($rs->RecordCount()) {
1406 while ($rd = rs_fetch_next_record($rs)) {
1407 $k = "{$rd->path}:{$rd->roleid}";
1408 $sw['rdef'][$k][$rd->capability] = $rd->permission;
1409 }
1410 }
1411 rs_close($rs);
1412
1413 // TODO: compact capsets?
1414
1415 return $sw;
1416}
1417
2f1a4248 1418
eef879ec 1419/**
c421ad4b 1420 * A convenience function to completely load all the capabilities
2f1a4248 1421 * for the current user. This is what gets called from login, for example.
1422 */
1423function load_all_capabilities() {
1424 global $USER;
1425
eef879ec 1426 //caching - helps user switching in cron
1427 static $defcaps = false;
bbbf2d40 1428
8e82745a 1429 unset($USER->mycourses); // Reset a cache used by get_my_courses
1430
eef879ec 1431 if (isguestuser()) {
2f1a4248 1432 load_guest_role(); // All non-guest users get this by default
eef879ec 1433
1434 } else if (isloggedin()) {
1435 if ($defcaps === false) {
1436 $defcaps = load_defaultuser_role(true);
1437 }
1438
3887fe4a 1439 load_user_capability();
7f97ea29 1440 $USER->access=get_user_sitewide_access($USER->id);
3887fe4a 1441
1442 // when in "course login as" - load only course caqpabilitites (it may not always work as expected)
1443 if (!empty($USER->realuser) and $USER->loginascontext->contextlevel != CONTEXT_SYSTEM) {
19bb8a05 1444 $children = array_keys(get_child_contexts($USER->loginascontext));
3887fe4a 1445 $children[] = $USER->loginascontext->id;
1446 foreach ($USER->capabilities as $conid => $caps) {
1447 if (!in_array($conid, $children)) {
1448 unset($USER->capabilities[$conid]);
c16ec802 1449 }
f6f66b03 1450 }
1451 }
eef879ec 1452
3887fe4a 1453 // handle role switching in courses
de5e137a 1454 if (!empty($USER->switchrole)) {
de5e137a 1455 foreach ($USER->switchrole as $contextid => $roleid) {
1456 $context = get_context_instance_by_id($contextid);
1457
1458 // first prune context and any child contexts
19bb8a05 1459 $children = array_keys(get_child_contexts($context));
de5e137a 1460 foreach ($children as $childid) {
1461 unset($USER->capabilities[$childid]);
1462 }
1463 unset($USER->capabilities[$contextid]);
1464
1465 // now merge all switched role caps in context and bellow
1466 $swithccaps = get_role_context_caps($roleid, $context);
1467 $USER->capabilities = merge_role_caps($USER->capabilities, $swithccaps);
1468 }
eef879ec 1469 }
1470
c0aa9f09 1471 if (isset($USER->capabilities)) {
1472 $USER->capabilities = merge_role_caps($USER->capabilities, $defcaps);
1473 } else {
1474 $USER->capabilities = $defcaps;
1475 }
de5e137a 1476
2f1a4248 1477 } else {
eef879ec 1478 load_notloggedin_role();
2f1a4248 1479 }
bbbf2d40 1480}
1481
2f1a4248 1482
efe12f6c 1483/**
64026e8c 1484 * Check all the login enrolment information for the given user object
eef868d1 1485 * by querying the enrolment plugins
64026e8c 1486 */
1487function check_enrolment_plugins(&$user) {
1488 global $CFG;
1489
e4ec4e41 1490 static $inprogress; // To prevent this function being called more than once in an invocation
1491
218eb651 1492 if (!empty($inprogress[$user->id])) {
e4ec4e41 1493 return;
1494 }
1495
218eb651 1496 $inprogress[$user->id] = true; // Set the flag
e4ec4e41 1497
64026e8c 1498 require_once($CFG->dirroot .'/enrol/enrol.class.php');
eef868d1 1499
64026e8c 1500 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
1501 $plugins = array($CFG->enrol);
1502 }
1503
1504 foreach ($plugins as $plugin) {
1505 $enrol = enrolment_factory::factory($plugin);
1506 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1507 $enrol->setup_enrolments($user);
1508 } else { /// Run legacy enrolment methods
1509 if (method_exists($enrol, 'get_student_courses')) {
1510 $enrol->get_student_courses($user);
1511 }
1512 if (method_exists($enrol, 'get_teacher_courses')) {
1513 $enrol->get_teacher_courses($user);
1514 }
1515
1516 /// deal with $user->students and $user->teachers stuff
1517 unset($user->student);
1518 unset($user->teacher);
1519 }
1520 unset($enrol);
1521 }
e4ec4e41 1522
218eb651 1523 unset($inprogress[$user->id]); // Unset the flag
64026e8c 1524}
1525
bbbf2d40 1526
1527/**
1528 * This is a recursive function that checks whether the capability in this
1529 * context, or the parent capabilities are set to prohibit.
1530 *
1531 * At this point, we can probably just use the values already set in the
1532 * session variable, since we are going down the level. Any prohit set in
1533 * parents would already reflect in the session.
1534 *
1535 * @param $capability - capability name
1536 * @param $sum - sum of all capabilities values
0468976c 1537 * @param $context - the context object
bbbf2d40 1538 * @param $array - when loading another user caps, their caps are not stored in session but an array
1539 */
0468976c 1540function capability_prohibits($capability, $context, $sum='', $array='') {
bbbf2d40 1541 global $USER;
0468976c 1542
0db6adc9 1543 // caching, mainly to save unnecessary sqls
1544 static $prohibits; //[capability][contextid]
1545 if (isset($prohibits[$capability][$context->id])) {
1546 return $prohibits[$capability][$context->id];
1547 }
c421ad4b 1548
2176adf1 1549 if (empty($context->id)) {
0db6adc9 1550 $prohibits[$capability][$context->id] = false;
2176adf1 1551 return false;
1552 }
1553
1554 if (empty($capability)) {
0db6adc9 1555 $prohibits[$capability][$context->id] = false;
2176adf1 1556 return false;
1557 }
1558
819e5a70 1559 if ($sum < (CAP_PROHIBIT/2)) {
bbbf2d40 1560 // If this capability is set to prohibit.
0db6adc9 1561 $prohibits[$capability][$context->id] = true;
bbbf2d40 1562 return true;
1563 }
eef868d1 1564
819e5a70 1565 if (!empty($array)) {
eef868d1 1566 if (isset($array[$context->id][$capability])
819e5a70 1567 && $array[$context->id][$capability] < (CAP_PROHIBIT/2)) {
0db6adc9 1568 $prohibits[$capability][$context->id] = true;
98882637 1569 return true;
eef868d1 1570 }
bbbf2d40 1571 } else {
98882637 1572 // Else if set in session.
eef868d1 1573 if (isset($USER->capabilities[$context->id][$capability])
819e5a70 1574 && $USER->capabilities[$context->id][$capability] < (CAP_PROHIBIT/2)) {
0db6adc9 1575 $prohibits[$capability][$context->id] = true;
98882637 1576 return true;
1577 }
bbbf2d40 1578 }
aad2ba95 1579 switch ($context->contextlevel) {
eef868d1 1580
bbbf2d40 1581 case CONTEXT_SYSTEM:
1582 // By now it's a definite an inherit.
1583 return 0;
1584 break;
1585
1586 case CONTEXT_PERSONAL:
2176adf1 1587 $parent = get_context_instance(CONTEXT_SYSTEM);
0db6adc9 1588 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1589 return $prohibits[$capability][$context->id];
bbbf2d40 1590 break;
1591
4b10f08b 1592 case CONTEXT_USER:
2176adf1 1593 $parent = get_context_instance(CONTEXT_SYSTEM);
0db6adc9 1594 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1595 return $prohibits[$capability][$context->id];
bbbf2d40 1596 break;
1597
1598 case CONTEXT_COURSECAT:
bbbf2d40 1599 case CONTEXT_COURSE:
3bf618ce 1600 $parents = get_parent_cats($context); // cached internally
1601 // no workaround for recursion now - it needs some more work and maybe fixing
1602
1603 if (empty($parents)) {
1604 // system context - this is either top category or frontpage course
40a2a15f 1605 $parent = get_context_instance(CONTEXT_SYSTEM);
1606 } else {
3bf618ce 1607 // parent context - recursion
1608 $parentid = array_pop($parents);
1609 $parent = get_context_instance_by_id($parentid);
40a2a15f 1610 }
0db6adc9 1611 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1612 return $prohibits[$capability][$context->id];
bbbf2d40 1613 break;
1614
1615 case CONTEXT_GROUP:
1616 // 1 to 1 to course.
5bf243d1 1617 if (!$courseid = get_field('groups', 'courseid', 'id', $context->instanceid)) {
0db6adc9 1618 $prohibits[$capability][$context->id] = false;
2176adf1 1619 return false;
1620 }
f3f7610c 1621 $parent = get_context_instance(CONTEXT_COURSE, $courseid);
0db6adc9 1622 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1623 return $prohibits[$capability][$context->id];
bbbf2d40 1624 break;
1625
1626 case CONTEXT_MODULE:
1627 // 1 to 1 to course.
2176adf1 1628 if (!$cm = get_record('course_modules','id',$context->instanceid)) {
0db6adc9 1629 $prohibits[$capability][$context->id] = false;
2176adf1 1630 return false;
1631 }
bbbf2d40 1632 $parent = get_context_instance(CONTEXT_COURSE, $cm->course);
0db6adc9 1633 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1634 return $prohibits[$capability][$context->id];
bbbf2d40 1635 break;
1636
1637 case CONTEXT_BLOCK:
c331cf23 1638 // not necessarily 1 to 1 to course.
2176adf1 1639 if (!$block = get_record('block_instance','id',$context->instanceid)) {
0db6adc9 1640 $prohibits[$capability][$context->id] = false;
2176adf1 1641 return false;
1642 }
6ceebc1f 1643 if ($block->pagetype == 'course-view') {
1644 $parent = get_context_instance(CONTEXT_COURSE, $block->pageid); // needs check
1645 } else {
c421ad4b 1646 $parent = get_context_instance(CONTEXT_SYSTEM);
1647 }
0db6adc9 1648 $prohibits[$capability][$context->id] = capability_prohibits($capability, $parent);
1649 return $prohibits[$capability][$context->id];
bbbf2d40 1650 break;
1651
1652 default:
2176adf1 1653 print_error('unknowncontext');
1654 return false;
bbbf2d40 1655 }
1656}
1657
1658
1659/**
1660 * A print form function. This should either grab all the capabilities from
1661 * files or a central table for that particular module instance, then present
1662 * them in check boxes. Only relevant capabilities should print for known
1663 * context.
1664 * @param $mod - module id of the mod
1665 */
1666function print_capabilities($modid=0) {
1667 global $CFG;
eef868d1 1668
bbbf2d40 1669 $capabilities = array();
1670
1671 if ($modid) {
1672 // We are in a module specific context.
1673
1674 // Get the mod's name.
1675 // Call the function that grabs the file and parse.
1676 $cm = get_record('course_modules', 'id', $modid);
1677 $module = get_record('modules', 'id', $cm->module);
eef868d1 1678
bbbf2d40 1679 } else {
1680 // Print all capabilities.
1681 foreach ($capabilities as $capability) {
1682 // Prints the check box component.
1683 }
1684 }
1685}
1686
1687
1688/**
1afecc03 1689 * Installs the roles system.
1690 * This function runs on a fresh install as well as on an upgrade from the old
1691 * hard-coded student/teacher/admin etc. roles to the new roles system.
bbbf2d40 1692 */
1afecc03 1693function moodle_install_roles() {
bbbf2d40 1694
1afecc03 1695 global $CFG, $db;
eef868d1 1696
459c1ff1 1697/// Create a system wide context for assignemnt.
21c9bace 1698 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
bbbf2d40 1699
1afecc03 1700
459c1ff1 1701/// Create default/legacy roles and capabilities.
1702/// (1 legacy capability per legacy role at system level).
1703
69aaada0 1704 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1705 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1706 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1707 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1708 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1709 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1710 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1711 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1712 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1713 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1714 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1715 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
c785d40a 1716 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1717 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
c421ad4b 1718
17e5635c 1719/// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
459c1ff1 1720
98882637 1721 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
bbbf2d40 1722 error('Could not assign moodle/site:doanything to the admin role');
1723 }
250934b8 1724 if (!update_capabilities()) {
1725 error('Had trouble upgrading the core capabilities for the Roles System');
1726 }
1afecc03 1727
459c1ff1 1728/// Look inside user_admin, user_creator, user_teachers, user_students and
1729/// assign above new roles. If a user has both teacher and student role,
1730/// only teacher role is assigned. The assignment should be system level.
1731
1afecc03 1732 $dbtables = $db->MetaTables('TABLES');
eef868d1 1733
72da5046 1734/// Set up the progress bar
1735
1736 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1737
1738 $totalcount = $progresscount = 0;
1739 foreach ($usertables as $usertable) {
1740 if (in_array($CFG->prefix.$usertable, $dbtables)) {
1741 $totalcount += count_records($usertable);
1742 }
1743 }
1744
aae37b63 1745 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1746
459c1ff1 1747/// Upgrade the admins.
1748/// Sort using id ASC, first one is primary admin.
1749
1afecc03 1750 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
f1dcf000 1751 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
0f5dafff 1752 while ($admin = rs_fetch_next_record($rs)) {
1afecc03 1753 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
72da5046 1754 $progresscount++;
aae37b63 1755 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1756 }
0f5dafff 1757 rs_close($rs);
1afecc03 1758 }
1759 } else {
1760 // This is a fresh install.
bbbf2d40 1761 }
1afecc03 1762
1763
459c1ff1 1764/// Upgrade course creators.
1afecc03 1765 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
f1dcf000 1766 if ($rs = get_recordset('user_coursecreators')) {
0f5dafff 1767 while ($coursecreator = rs_fetch_next_record($rs)) {
56b4d70d 1768 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
72da5046 1769 $progresscount++;
aae37b63 1770 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1771 }
0f5dafff 1772 rs_close($rs);
1afecc03 1773 }
bbbf2d40 1774 }
1775
1afecc03 1776
459c1ff1 1777/// Upgrade editting teachers and non-editting teachers.
1afecc03 1778 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
f1dcf000 1779 if ($rs = get_recordset('user_teachers')) {
0f5dafff 1780 while ($teacher = rs_fetch_next_record($rs)) {
c421ad4b 1781
d5511451 1782 // removed code here to ignore site level assignments
1783 // since the contexts are separated now
c421ad4b 1784
17d6a25e 1785 // populate the user_lastaccess table
ece4945b 1786 $access = new object();
17d6a25e 1787 $access->timeaccess = $teacher->timeaccess;
1788 $access->userid = $teacher->userid;
1789 $access->courseid = $teacher->course;
1790 insert_record('user_lastaccess', $access);
f1dcf000 1791
17d6a25e 1792 // assign the default student role
1afecc03 1793 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
3fe54e51 1794 // hidden teacher
1795 if ($teacher->authority == 0) {
c421ad4b 1796 $hiddenteacher = 1;
3fe54e51 1797 } else {
c421ad4b 1798 $hiddenteacher = 0;
1799 }
1800
1afecc03 1801 if ($teacher->editall) { // editting teacher
3fe54e51 1802 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1afecc03 1803 } else {
3fe54e51 1804 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id, 0, 0, $hiddenteacher);
1afecc03 1805 }
72da5046 1806 $progresscount++;
aae37b63 1807 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1808 }
0f5dafff 1809 rs_close($rs);
bbbf2d40 1810 }
1811 }
1afecc03 1812
1813
459c1ff1 1814/// Upgrade students.
1afecc03 1815 if (in_array($CFG->prefix.'user_students', $dbtables)) {
f1dcf000 1816 if ($rs = get_recordset('user_students')) {
0f5dafff 1817 while ($student = rs_fetch_next_record($rs)) {
f1dcf000 1818
17d6a25e 1819 // populate the user_lastaccess table
f1dcf000 1820 $access = new object;
17d6a25e 1821 $access->timeaccess = $student->timeaccess;
1822 $access->userid = $student->userid;
1823 $access->courseid = $student->course;
1824 insert_record('user_lastaccess', $access);
f1dcf000 1825
17d6a25e 1826 // assign the default student role
1afecc03 1827 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
1828 role_assign($studentrole, $student->userid, 0, $coursecontext->id);
72da5046 1829 $progresscount++;
aae37b63 1830 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1831 }
0f5dafff 1832 rs_close($rs);
1afecc03 1833 }
bbbf2d40 1834 }
1afecc03 1835
1836
459c1ff1 1837/// Upgrade guest (only 1 entry).
1afecc03 1838 if ($guestuser = get_record('user', 'username', 'guest')) {
1839 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
1840 }
aae37b63 1841 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1afecc03 1842
459c1ff1 1843
1844/// Insert the correct records for legacy roles
945f88ca 1845 allow_assign($adminrole, $adminrole);
1846 allow_assign($adminrole, $coursecreatorrole);
1847 allow_assign($adminrole, $noneditteacherrole);
eef868d1 1848 allow_assign($adminrole, $editteacherrole);
945f88ca 1849 allow_assign($adminrole, $studentrole);
1850 allow_assign($adminrole, $guestrole);
eef868d1 1851
945f88ca 1852 allow_assign($coursecreatorrole, $noneditteacherrole);
1853 allow_assign($coursecreatorrole, $editteacherrole);
eef868d1 1854 allow_assign($coursecreatorrole, $studentrole);
945f88ca 1855 allow_assign($coursecreatorrole, $guestrole);
eef868d1 1856
1857 allow_assign($editteacherrole, $noneditteacherrole);
1858 allow_assign($editteacherrole, $studentrole);
945f88ca 1859 allow_assign($editteacherrole, $guestrole);
eef868d1 1860
459c1ff1 1861/// Set up default permissions for overrides
945f88ca 1862 allow_override($adminrole, $adminrole);
1863 allow_override($adminrole, $coursecreatorrole);
1864 allow_override($adminrole, $noneditteacherrole);
eef868d1 1865 allow_override($adminrole, $editteacherrole);
945f88ca 1866 allow_override($adminrole, $studentrole);
eef868d1 1867 allow_override($adminrole, $guestrole);
c785d40a 1868 allow_override($adminrole, $userrole);
1afecc03 1869
746a04c5 1870
459c1ff1 1871/// Delete the old user tables when we are done
1872
83ea392e 1873 drop_table(new XMLDBTable('user_students'));
1874 drop_table(new XMLDBTable('user_teachers'));
1875 drop_table(new XMLDBTable('user_coursecreators'));
1876 drop_table(new XMLDBTable('user_admins'));
459c1ff1 1877
bbbf2d40 1878}
1879
3562486b 1880/**
1881 * Returns array of all legacy roles.
1882 */
1883function get_legacy_roles() {
1884 return array(
a83addc5 1885 'admin' => 'moodle/legacy:admin',
3562486b 1886 'coursecreator' => 'moodle/legacy:coursecreator',
a83addc5 1887 'editingteacher' => 'moodle/legacy:editingteacher',
1888 'teacher' => 'moodle/legacy:teacher',
1889 'student' => 'moodle/legacy:student',
efe12f6c 1890 'guest' => 'moodle/legacy:guest',
1891 'user' => 'moodle/legacy:user'
3562486b 1892 );
1893}
1894
b357ed13 1895function get_legacy_type($roleid) {
1896 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1897 $legacyroles = get_legacy_roles();
1898
1899 $result = '';
1900 foreach($legacyroles as $ltype=>$lcap) {
1901 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
1902 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
1903 //choose first selected legacy capability - reset the rest
1904 if (empty($result)) {
1905 $result = $ltype;
1906 } else {
66a27728 1907 unassign_capability($lcap, $roleid);
c421ad4b 1908 }
b357ed13 1909 }
1910 }
1911
1912 return $result;
1913}
1914
bbbf2d40 1915/**
1916 * Assign the defaults found in this capabality definition to roles that have
1917 * the corresponding legacy capabilities assigned to them.
1918 * @param $legacyperms - an array in the format (example):
1919 * 'guest' => CAP_PREVENT,
1920 * 'student' => CAP_ALLOW,
1921 * 'teacher' => CAP_ALLOW,
1922 * 'editingteacher' => CAP_ALLOW,
1923 * 'coursecreator' => CAP_ALLOW,
1924 * 'admin' => CAP_ALLOW
1925 * @return boolean - success or failure.
1926 */
1927function assign_legacy_capabilities($capability, $legacyperms) {
eef868d1 1928
3562486b 1929 $legacyroles = get_legacy_roles();
1930
bbbf2d40 1931 foreach ($legacyperms as $type => $perm) {
eef868d1 1932
21c9bace 1933 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
eef868d1 1934
3562486b 1935 if (!array_key_exists($type, $legacyroles)) {
1936 error('Incorrect legacy role definition for type: '.$type);
1937 }
eef868d1 1938
3562486b 1939 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW)) {
2e85fffe 1940 foreach ($roles as $role) {
1941 // Assign a site level capability.
1942 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1943 return false;
1944 }
bbbf2d40 1945 }
1946 }
1947 }
1948 return true;
1949}
1950
1951
cee0901c 1952/**
1953 * Checks to see if a capability is a legacy capability.
1954 * @param $capabilityname
1955 * @return boolean
1956 */
bbbf2d40 1957function islegacy($capabilityname) {
d67de0ca 1958 if (strpos($capabilityname, 'moodle/legacy') === 0) {
eef868d1 1959 return true;
d67de0ca 1960 } else {
1961 return false;
98882637 1962 }
bbbf2d40 1963}
1964
cee0901c 1965
1966
1967/**********************************
bbbf2d40 1968 * Context Manipulation functions *
1969 **********************************/
1970
bbbf2d40 1971/**
9991d157 1972 * Create a new context record for use by all roles-related stuff
bbbf2d40 1973 * @param $level
1974 * @param $instanceid
3ca2dea5 1975 *
1976 * @return object newly created context (or existing one with a debug warning)
bbbf2d40 1977 */
aad2ba95 1978function create_context($contextlevel, $instanceid) {
3ca2dea5 1979 if (!$context = get_record('context','contextlevel',$contextlevel,'instanceid',$instanceid)) {
1980 if (!validate_context($contextlevel, $instanceid)) {
1981 debugging('Error: Invalid context creation request for level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1982 return NULL;
1983 }
8ba412da 1984 if ($contextlevel == CONTEXT_SYSTEM) {
1985 return create_system_context();
c421ad4b 1986
8ba412da 1987 }
3ca2dea5 1988 $context = new object();
aad2ba95 1989 $context->contextlevel = $contextlevel;
bbbf2d40 1990 $context->instanceid = $instanceid;
3ca2dea5 1991 if ($id = insert_record('context',$context)) {
c421ad4b 1992 $c = get_record('context','id',$id);
0db6adc9 1993 return $c;
3ca2dea5 1994 } else {
1995 debugging('Error: could not insert new context level "'.s($contextlevel).'", instance "'.s($instanceid).'".');
1996 return NULL;
1997 }
1998 } else {
1999 debugging('Warning: Context id "'.s($context->id).'" not created, because it already exists.');
2000 return $context;
bbbf2d40 2001 }
2002}
2003
efe12f6c 2004/**
8ba412da 2005 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
2006 */
2007function create_system_context() {
2008 if ($context = get_record('context', 'contextlevel', CONTEXT_SYSTEM, 'instanceid', SITEID)) {
2009 // we are going to change instanceid of system context to 0 now
2010 $context->instanceid = 0;
2011 update_record('context', $context);
2012 //context rel not affected
2013 return $context;
2014
2015 } else {
2016 $context = new object();
2017 $context->contextlevel = CONTEXT_SYSTEM;
2018 $context->instanceid = 0;
2019 if ($context->id = insert_record('context',$context)) {
2020 // we need not to populate context_rel for system context
2021 return $context;
2022 } else {
2023 debugging('Can not create system context');
2024 return NULL;
2025 }
2026 }
2027}
9991d157 2028/**
17b0efae 2029 * Remove a context record and any dependent entries
9991d157 2030 * @param $level
2031 * @param $instanceid
3ca2dea5 2032 *
17b0efae 2033 * @return bool properly deleted
9991d157 2034 */
2035function delete_context($contextlevel, $instanceid) {
c421ad4b 2036 if ($context = get_context_instance($contextlevel, $instanceid)) {
0db6adc9 2037 delete_records('context_rel', 'c2', $context->id); // might not be a parent
9991d157 2038 return delete_records('context', 'id', $context->id) &&
2039 delete_records('role_assignments', 'contextid', $context->id) &&
c421ad4b 2040 delete_records('role_capabilities', 'contextid', $context->id) &&
0db6adc9 2041 delete_records('context_rel', 'c1', $context->id);
9991d157 2042 }
2043 return true;
2044}
2045
17b0efae 2046/**
2047 * Remove stale context records
2048 *
2049 * @return bool
2050 */
2051function cleanup_contexts() {
2052 global $CFG;
2053
2054 $sql = " SELECT " . CONTEXT_COURSECAT . " AS level,
2055 c.instanceid AS instanceid
2056 FROM {$CFG->prefix}context c
2057 LEFT OUTER JOIN {$CFG->prefix}course_categories AS t
2058 ON c.instanceid = t.id
2059 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSECAT . "
2060 UNION
2061 SELECT " . CONTEXT_COURSE . " AS level,
2062 c.instanceid AS instanceid
2063 FROM {$CFG->prefix}context c
2064 LEFT OUTER JOIN {$CFG->prefix}course AS t
2065 ON c.instanceid = t.id
2066 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSE . "
2067 UNION
2068 SELECT " . CONTEXT_MODULE . " AS level,
2069 c.instanceid AS instanceid
2070 FROM {$CFG->prefix}context c
2071 LEFT OUTER JOIN {$CFG->prefix}course_modules AS t
2072 ON c.instanceid = t.id
2073 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_MODULE . "
2074 UNION
2075 SELECT " . CONTEXT_USER . " AS level,
2076 c.instanceid AS instanceid
2077 FROM {$CFG->prefix}context c
2078 LEFT OUTER JOIN {$CFG->prefix}user AS t
2079 ON c.instanceid = t.id
2080 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_USER . "
2081 UNION
2082 SELECT " . CONTEXT_BLOCK . " AS level,
2083 c.instanceid AS instanceid
2084 FROM {$CFG->prefix}context c
2085 LEFT OUTER JOIN {$CFG->prefix}block_instance AS t
2086 ON c.instanceid = t.id
2087 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_BLOCK . "
2088 UNION
2089 SELECT " . CONTEXT_GROUP . " AS level,
2090 c.instanceid AS instanceid
2091 FROM {$CFG->prefix}context c
2092 LEFT OUTER JOIN {$CFG->prefix}groups AS t
2093 ON c.instanceid = t.id
2094 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_GROUP . "
2095 ";
2096 $rs = get_recordset_sql($sql);
2097 if ($rs->RecordCount()) {
2098 begin_sql();
2099 $tx = true;
2100 while ($tx && $ctx = rs_fetch_next_record($rs)) {
2101 $tx = $tx && delete_context($ctx->level, $ctx->instanceid);
2102 }
2103 rs_close($rs);
2104 if ($tx) {
2105 commit_sql();
2106 return true;
2107 }
2108 rollback_sql();
2109 return false;
2110 }
2111 return true;
2112}
2113
3ca2dea5 2114/**
2115 * Validate that object with instanceid really exists in given context level.
2116 *
2117 * return if instanceid object exists
2118 */
2119function validate_context($contextlevel, $instanceid) {
2120 switch ($contextlevel) {
2121
2122 case CONTEXT_SYSTEM:
8ba412da 2123 return ($instanceid == 0);
3ca2dea5 2124
2125 case CONTEXT_PERSONAL:
2126 return (boolean)count_records('user', 'id', $instanceid);
2127
2128 case CONTEXT_USER:
2129 return (boolean)count_records('user', 'id', $instanceid);
2130
2131 case CONTEXT_COURSECAT:
1cd3eba9 2132 if ($instanceid == 0) {
2133 return true; // site course category
2134 }
3ca2dea5 2135 return (boolean)count_records('course_categories', 'id', $instanceid);
2136
2137 case CONTEXT_COURSE:
2138 return (boolean)count_records('course', 'id', $instanceid);
2139
2140 case CONTEXT_GROUP:
f3f7610c 2141 return groups_group_exists($instanceid);
3ca2dea5 2142
2143 case CONTEXT_MODULE:
2144 return (boolean)count_records('course_modules', 'id', $instanceid);
2145
2146 case CONTEXT_BLOCK:
2147 return (boolean)count_records('block_instance', 'id', $instanceid);
2148
2149 default:
2150 return false;
2151 }
2152}
bbbf2d40 2153
2154/**
2155 * Get the context instance as an object. This function will create the
2156 * context instance if it does not exist yet.
e765b5d3 2157 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2158 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
2159 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
2160 * @return object The context object.
bbbf2d40 2161 */
8ba412da 2162function get_context_instance($contextlevel=NULL, $instance=0) {
e5605780 2163
51195e6f 2164 global $context_cache, $context_cache_id, $CONTEXT;
a36a3a3f 2165 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_PERSONAL, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_GROUP, CONTEXT_MODULE, CONTEXT_BLOCK);
d9a35e12 2166
8ba412da 2167 // Yu: Separating site and site course context - removed CONTEXT_COURSE override when SITEID
c421ad4b 2168
9251b26f 2169 // fix for MDL-9016
2170 if ($contextlevel == 'clearcache') {
2171 // Clear ALL cache
2172 $context_cache = array();
2173 $context_cache_id = array();
c421ad4b 2174 $CONTEXT = '';
9251b26f 2175 return false;
2176 }
b7cec865 2177
340ea4e8 2178/// If no level is supplied then return the current global context if there is one
aad2ba95 2179 if (empty($contextlevel)) {
340ea4e8 2180 if (empty($CONTEXT)) {
a36a3a3f 2181 //fatal error, code must be fixed
2182 error("Error: get_context_instance() called without a context");
340ea4e8 2183 } else {
2184 return $CONTEXT;
2185 }
e5605780 2186 }
2187
8ba412da 2188/// Backwards compatibility with obsoleted (CONTEXT_SYSTEM, SITEID)
2189 if ($contextlevel == CONTEXT_SYSTEM) {
2190 $instance = 0;
2191 }
2192
a36a3a3f 2193/// check allowed context levels
2194 if (!in_array($contextlevel, $allowed_contexts)) {
7bfa3101 2195 // fatal error, code must be fixed - probably typo or switched parameters
a36a3a3f 2196 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
2197 }
2198
340ea4e8 2199/// Check the cache
aad2ba95 2200 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2201 return $context_cache[$contextlevel][$instance];
e5605780 2202 }
2203
340ea4e8 2204/// Get it from the database, or create it
aad2ba95 2205 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
2206 create_context($contextlevel, $instance);
2207 $context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance);
e5605780 2208 }
2209
ccfc5ecc 2210/// Only add to cache if context isn't empty.
2211 if (!empty($context)) {
aad2ba95 2212 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
ccfc5ecc 2213 $context_cache_id[$context->id] = $context; // Cache it for later
2214 }
0468976c 2215
bbbf2d40 2216 return $context;
2217}
2218
cee0901c 2219
340ea4e8 2220/**
e765b5d3 2221 * Get a context instance as an object, from a given context id.
2222 * @param $id a context id.
2223 * @return object The context object.
340ea4e8 2224 */
2225function get_context_instance_by_id($id) {
2226
d9a35e12 2227 global $context_cache, $context_cache_id;
2228
340ea4e8 2229 if (isset($context_cache_id[$id])) { // Already cached
75e84883 2230 return $context_cache_id[$id];
340ea4e8 2231 }
2232
2233 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
aad2ba95 2234 $context_cache[$context->contextlevel][$context->instanceid] = $context;
340ea4e8 2235 $context_cache_id[$context->id] = $context;
2236 return $context;
2237 }
2238
2239 return false;
2240}
2241
bbbf2d40 2242
8737be58 2243/**
2244 * Get the local override (if any) for a given capability in a role in a context
2245 * @param $roleid
0468976c 2246 * @param $contextid
2247 * @param $capability
8737be58 2248 */
2249function get_local_override($roleid, $contextid, $capability) {
2250 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
2251}
2252
2253
bbbf2d40 2254
2255/************************************
2256 * DB TABLE RELATED FUNCTIONS *
2257 ************************************/
2258
cee0901c 2259/**
bbbf2d40 2260 * function that creates a role
2261 * @param name - role name
31f26796 2262 * @param shortname - role short name
bbbf2d40 2263 * @param description - role description
2264 * @param legacy - optional legacy capability
2265 * @return id or false
2266 */
8420bee9 2267function create_role($name, $shortname, $description, $legacy='') {
eef868d1 2268
98882637 2269 // check for duplicate role name
eef868d1 2270
98882637 2271 if ($role = get_record('role','name', $name)) {
eef868d1 2272 error('there is already a role with this name!');
98882637 2273 }
eef868d1 2274
31f26796 2275 if ($role = get_record('role','shortname', $shortname)) {
eef868d1 2276 error('there is already a role with this shortname!');
31f26796 2277 }
2278
b5959f30 2279 $role = new object();
98882637 2280 $role->name = $name;
31f26796 2281 $role->shortname = $shortname;
98882637 2282 $role->description = $description;
eef868d1 2283
8420bee9 2284 //find free sortorder number
2285 $role->sortorder = count_records('role');
2286 while (get_record('role','sortorder', $role->sortorder)) {
2287 $role->sortorder += 1;
b5959f30 2288 }
2289
21c9bace 2290 if (!$context = get_context_instance(CONTEXT_SYSTEM)) {
2291 return false;
2292 }
eef868d1 2293
98882637 2294 if ($id = insert_record('role', $role)) {
eef868d1 2295 if ($legacy) {
2296 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
98882637 2297 }
eef868d1 2298
ec7a8b79 2299 /// By default, users with role:manage at site level
2300 /// should be able to assign users to this new role, and override this new role's capabilities
eef868d1 2301
ec7a8b79 2302 // find all admin roles
e46c0987 2303 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
2304 // foreach admin role
2305 foreach ($adminroles as $arole) {
2306 // write allow_assign and allow_overrid
2307 allow_assign($arole->id, $id);
eef868d1 2308 allow_override($arole->id, $id);
e46c0987 2309 }
ec7a8b79 2310 }
eef868d1 2311
98882637 2312 return $id;
2313 } else {
eef868d1 2314 return false;
98882637 2315 }
eef868d1 2316
bbbf2d40 2317}
2318
8420bee9 2319/**
2320 * function that deletes a role and cleanups up after it
2321 * @param roleid - id of role to delete
2322 * @return success
2323 */
2324function delete_role($roleid) {
c345bb58 2325 global $CFG;
8420bee9 2326 $success = true;
2327
60ace1e1 2328// mdl 10149, check if this is the last active admin role
2329// if we make the admin role not deletable then this part can go
c421ad4b 2330
60ace1e1 2331 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
c421ad4b 2332
60ace1e1 2333 if ($role = get_record('role', 'id', $roleid)) {
2334 if (record_exists('role_capabilities', 'contextid', $systemcontext->id, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
2335 // deleting an admin role
2336 $status = false;
2337 if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext)) {
2338 foreach ($adminroles as $adminrole) {
2339 if ($adminrole->id != $roleid) {
2340 // some other admin role
2341 if (record_exists('role_assignments', 'roleid', $adminrole->id, 'contextid', $systemcontext->id)) {
c421ad4b 2342 // found another admin role with at least 1 user assigned
60ace1e1 2343 $status = true;
2344 break;
2345 }
2346 }
c421ad4b 2347 }
2348 }
60ace1e1 2349 if ($status !== true) {
c421ad4b 2350 error ('You can not delete this role because there is no other admin roles with users assigned');
60ace1e1 2351 }
c421ad4b 2352 }
60ace1e1 2353 }
2354
8420bee9 2355// first unssign all users
2356 if (!role_unassign($roleid)) {
2357 debugging("Error while unassigning all users from role with ID $roleid!");
2358 $success = false;
2359 }
2360
2361// cleanup all references to this role, ignore errors
2362 if ($success) {
c421ad4b 2363
c345bb58 2364 // MDL-10679 find all contexts where this role has an override
c421ad4b 2365 $contexts = get_records_sql("SELECT contextid, contextid
c345bb58 2366 FROM {$CFG->prefix}role_capabilities
2367 WHERE roleid = $roleid");
c421ad4b 2368
8420bee9 2369 delete_records('role_capabilities', 'roleid', $roleid);
c421ad4b 2370
c345bb58 2371 // MDL-10679, delete from context_rel if this role holds the last override in these contexts
2372 if ($contexts) {
2373 foreach ($contexts as $context) {
2374 if (!record_exists('role_capabilities', 'contextid', $context->contextid)) {
c421ad4b 2375 delete_records('context_rel', 'c1', $context->contextid);
2376 }
c345bb58 2377 }
2378 }
2379
8420bee9 2380 delete_records('role_allow_assign', 'roleid', $roleid);
2381 delete_records('role_allow_assign', 'allowassign', $roleid);
2382 delete_records('role_allow_override', 'roleid', $roleid);
2383 delete_records('role_allow_override', 'allowoverride', $roleid);
c421ad4b 2384 delete_records('role_names', 'roleid', $roleid);
8420bee9 2385 }
2386
2387// finally delete the role itself
2388 if ($success and !delete_records('role', 'id', $roleid)) {
ece4945b 2389 debugging("Could not delete role record with ID $roleid!");
8420bee9 2390 $success = false;
2391 }
2392
2393 return $success;
2394}
2395
bbbf2d40 2396/**
2397 * Function to write context specific overrides, or default capabilities.
2398 * @param module - string name
2399 * @param capability - string name
2400 * @param contextid - context id
2401 * @param roleid - role id
2402 * @param permission - int 1,-1 or -1000
96986241 2403 * should not be writing if permission is 0
bbbf2d40 2404 */
e7876c1e 2405function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
eef868d1 2406
98882637 2407 global $USER;
eef868d1 2408
96986241 2409 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
eef868d1 2410 unassign_capability($capability, $roleid, $contextid);
96986241 2411 return true;
98882637 2412 }
eef868d1 2413
2e85fffe 2414 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
e7876c1e 2415
2416 if ($existing and !$overwrite) { // We want to keep whatever is there already
2417 return true;
2418 }
2419
bbbf2d40 2420 $cap = new object;
2421 $cap->contextid = $contextid;
2422 $cap->roleid = $roleid;
2423 $cap->capability = $capability;
2424 $cap->permission = $permission;
2425 $cap->timemodified = time();
9db12da7 2426 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
e7876c1e 2427
2428 if ($existing) {
2429 $cap->id = $existing->id;
2430 return update_record('role_capabilities', $cap);
2431 } else {
c345bb58 2432 $c = get_record('context', 'id', $contextid);
2433 /// MDL-10679 insert context rel here
2434 insert_context_rel ($c);
e7876c1e 2435 return insert_record('role_capabilities', $cap);
2436 }
bbbf2d40 2437}
2438
2439
2440/**
2441 * Unassign a capability from a role.
2442 * @param $roleid - the role id
2443 * @param $capability - the name of the capability
2444 * @return boolean - success or failure
2445 */
2446function unassign_capability($capability, $roleid, $contextid=NULL) {
eef868d1 2447
98882637 2448 if (isset($contextid)) {
c345bb58 2449 // delete from context rel, if this is the last override in this context
98882637 2450 $status = delete_records('role_capabilities', 'capability', $capability,
2451 'roleid', $roleid, 'contextid', $contextid);
c421ad4b 2452
c345bb58 2453 // MDL-10679, if this is no more overrides for this context
2454 // delete entries from context where this context is a child
2455 if (!record_exists('role_capabilities', 'contextid', $contextid)) {
c421ad4b 2456 delete_records('context_rel', 'c1', $contextid);
2457 }
2458
98882637 2459 } else {
c345bb58 2460 // There is no need to delete from context_rel here because
2461 // this is only used for legacy, for now
98882637 2462 $status = delete_records('role_capabilities', 'capability', $capability,
2463 'roleid', $roleid);
2464 }
2465 return $status;
bbbf2d40 2466}
2467
2468
2469/**
759ac72d 2470 * Get the roles that have a given capability assigned to it. This function
2471 * does not resolve the actual permission of the capability. It just checks
2472 * for assignment only.
bbbf2d40 2473 * @param $capability - capability name (string)
2474 * @param $permission - optional, the permission defined for this capability
2475 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2476 * @return array or role objects
2477 */
ec7a8b79 2478function get_roles_with_capability($capability, $permission=NULL, $context='') {
2479
bbbf2d40 2480 global $CFG;
eef868d1 2481
ec7a8b79 2482 if ($context) {
2483 if ($contexts = get_parent_contexts($context)) {
2484 $listofcontexts = '('.implode(',', $contexts).')';
2485 } else {
21c9bace 2486 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
eef868d1 2487 $listofcontexts = '('.$sitecontext->id.')'; // must be site
2488 }
42ac3ecf 2489 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
ec7a8b79 2490 } else {
2491 $contextstr = '';
2492 }
eef868d1 2493
2494 $selectroles = "SELECT r.*
42ac3ecf 2495 FROM {$CFG->prefix}role r,
2496 {$CFG->prefix}role_capabilities rc
bbbf2d40 2497 WHERE rc.capability = '$capability'
ec7a8b79 2498 AND rc.roleid = r.id $contextstr";
bbbf2d40 2499
2500 if (isset($permission)) {
2501 $selectroles .= " AND rc.permission = '$permission'";
2502 }
2503 return get_records_sql($selectroles);
2504}
2505
2506
2507/**
a9e1c058 2508 * This function makes a role-assignment (a role for a user or group in a particular context)
bbbf2d40 2509 * @param $roleid - the role of the id
2510 * @param $userid - userid
2511 * @param $groupid - group id
2512 * @param $contextid - id of the context
2513 * @param $timestart - time this assignment becomes effective
2514 * @param $timeend - time this assignemnt ceases to be effective
2515 * @uses $USER
2516 * @return id - new id of the assigment
2517 */
69b0088c 2518function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
aa311411 2519 global $USER, $CFG;
bbbf2d40 2520
7eb0b60a 2521 debugging("Assign roleid $roleid userid $userid contextid $contextid", DEBUG_DEVELOPER);
bbbf2d40 2522
a9e1c058 2523/// Do some data validation
2524
bbbf2d40 2525 if (empty($roleid)) {
9d829c68 2526 debugging('Role ID not provided');
a9e1c058 2527 return false;
bbbf2d40 2528 }
2529
2530 if (empty($userid) && empty($groupid)) {
9d829c68 2531 debugging('Either userid or groupid must be provided');
a9e1c058 2532 return false;
bbbf2d40 2533 }
eef868d1 2534
7700027f 2535 if ($userid && !record_exists('user', 'id', $userid)) {
82396e5b 2536 debugging('User ID '.intval($userid).' does not exist!');
7700027f 2537 return false;
2538 }
bbbf2d40 2539
f3f7610c 2540 if ($groupid && !groups_group_exists($groupid)) {
82396e5b 2541 debugging('Group ID '.intval($groupid).' does not exist!');
dc411d1b 2542 return false;
2543 }
2544
7700027f 2545 if (!$context = get_context_instance_by_id($contextid)) {
82396e5b 2546 debugging('Context ID '.intval($contextid).' does not exist!');
a9e1c058 2547 return false;
bbbf2d40 2548 }
2549
a9e1c058 2550 if (($timestart and $timeend) and ($timestart > $timeend)) {
9d829c68 2551 debugging('The end time can not be earlier than the start time');
a9e1c058 2552 return false;
2553 }
2554
69b0088c 2555 if (!$timemodified) {
c421ad4b 2556 $timemodified = time();
69b0088c 2557 }
7700027f 2558
a9e1c058 2559/// Check for existing entry
2560 if ($userid) {
7700027f 2561 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
a9e1c058 2562 } else {
7700027f 2563 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
a9e1c058 2564 }
2565
9ebcb4d2 2566
a9e1c058 2567 $newra = new object;
bbbf2d40 2568
a9e1c058 2569 if (empty($ra)) { // Create a new entry
2570 $newra->roleid = $roleid;
7700027f 2571 $newra->contextid = $context->id;
a9e1c058 2572 $newra->userid = $userid;
a9e1c058 2573 $newra->hidden = $hidden;
f44152f4 2574 $newra->enrol = $enrol;
c421ad4b 2575 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
0616d3e8 2576 /// by repeating queries with the same exact parameters in a 100 secs time window
2577 $newra->timestart = round($timestart, -2);
a9e1c058 2578 $newra->timeend = $timeend;
69b0088c 2579 $newra->timemodified = $timemodified;
115faa2f 2580 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
a9e1c058 2581
9ebcb4d2 2582 $success = insert_record('role_assignments', $newra);
a9e1c058 2583
2584 } else { // We already have one, just update it
2585
2586 $newra->id = $ra->id;
2587 $newra->hidden = $hidden;
f44152f4 2588 $newra->enrol = $enrol;
c421ad4b 2589 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
0616d3e8 2590 /// by repeating queries with the same exact parameters in a 100 secs time window
2591 $newra->timestart = round($timestart, -2);
a9e1c058 2592 $newra->timeend = $timeend;
69b0088c 2593 $newra->timemodified = $timemodified;
115faa2f 2594 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
a9e1c058 2595
9ebcb4d2 2596 $success = update_record('role_assignments', $newra);
2597 }
2598
7700027f 2599 if ($success) { /// Role was assigned, so do some other things
2600
2601 /// If the user is the current user, then reload the capabilities too.
2602 if (!empty($USER->id) && $USER->id == $userid) {
2f1a4248 2603 load_all_capabilities();
7700027f 2604 }
c421ad4b 2605
0f161e1f 2606 /// Ask all the modules if anything needs to be done for this user
2607 if ($mods = get_list_of_plugins('mod')) {
2608 foreach ($mods as $mod) {
2609 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2610 $functionname = $mod.'_role_assign';
2611 if (function_exists($functionname)) {
a7bb9b8f 2612 $functionname($userid, $context, $roleid);
0f161e1f 2613 }
2614 }
2615 }
2616
2617 /// Make sure they have an entry in user_lastaccess for courses they can access
2618 // role_add_lastaccess_entries($userid, $context);
a9e1c058 2619 }
eef868d1 2620
4e5f3064 2621 /// now handle metacourse role assignments if in course context
aad2ba95 2622 if ($success and $context->contextlevel == CONTEXT_COURSE) {
4e5f3064 2623 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2624 foreach ($parents as $parent) {
1aad4310 2625 sync_metacourse($parent->parent_course);
4e5f3064 2626 }
2627 }
2628 }
6eb4f823 2629
2630 return $success;
bbbf2d40 2631}
2632
2633
2634/**
1dc1f037 2635 * Deletes one or more role assignments. You must specify at least one parameter.
bbbf2d40 2636 * @param $roleid
2637 * @param $userid
2638 * @param $groupid
2639 * @param $contextid
6bc1e5d5 2640 * @param $enrol unassign only if enrolment type matches, NULL means anything
bbbf2d40 2641 * @return boolean - success or failure
2642 */
6bc1e5d5 2643function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
d74067e8 2644
2645 global $USER, $CFG;
eef868d1 2646
4e5f3064 2647 $success = true;
d74067e8 2648
1dc1f037 2649 $args = array('roleid', 'userid', 'groupid', 'contextid');
2650 $select = array();
2651 foreach ($args as $arg) {
2652 if ($$arg) {
2653 $select[] = $arg.' = '.$$arg;
2654 }
2655 }
6bc1e5d5 2656 if (!empty($enrol)) {
2657 $select[] = "enrol='$enrol'";
2658 }
d74067e8 2659
1dc1f037 2660 if ($select) {
4e5f3064 2661 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2662 $mods = get_list_of_plugins('mod');
2663 foreach($ras as $ra) {
86e2c51d 2664 /// infinite loop protection when deleting recursively
2665 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
2666 continue;
2667 }
4e5f3064 2668 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
86e2c51d 2669
4e5f3064 2670 /// If the user is the current user, then reload the capabilities too.
2671 if (!empty($USER->id) && $USER->id == $ra->userid) {
2f1a4248 2672 load_all_capabilities();
4e5f3064 2673 }
2674 $context = get_record('context', 'id', $ra->contextid);
0f161e1f 2675
2676 /// Ask all the modules if anything needs to be done for this user
4e5f3064 2677 foreach ($mods as $mod) {
2678 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2679 $functionname = $mod.'_role_unassign';
2680 if (function_exists($functionname)) {
2681 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
2682 }
2683 }
2684
2685 /// now handle metacourse role unassigment and removing from goups if in course context
aad2ba95 2686 if (!empty($context) and $context->contextlevel == CONTEXT_COURSE) {
2515adf9 2687
c421ad4b 2688 // cleanup leftover course groups/subscriptions etc when user has
2515adf9 2689 // no capability to view course
35274646 2690 // this may be slow, but this is the proper way of doing it
2691 if (!has_capability('moodle/course:view', $context, $ra->userid)) {
2515adf9 2692 // remove from groups
2c386f82 2693 if ($groups = groups_get_all_groups($context->instanceid)) {
4e5f3064 2694 foreach ($groups as $group) {
2695 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
2696 }
2697 }
2515adf9 2698
2515adf9 2699 // delete lastaccess records
2700 delete_records('user_lastaccess', 'userid', $ra->userid, 'courseid', $context->instanceid);
4e5f3064 2701 }
2515adf9 2702
1aad4310 2703 //unassign roles in metacourses if needed
4e5f3064 2704 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2705 foreach ($parents as $parent) {
1aad4310 2706 sync_metacourse($parent->parent_course);
0f161e1f 2707 }
2708 }
0f161e1f 2709 }
2710 }
d74067e8 2711 }
1dc1f037 2712 }
4e5f3064 2713
2714 return $success;
bbbf2d40 2715}
2716
efe12f6c 2717/**
eef868d1 2718 * A convenience function to take care of the common case where you
b963384f 2719 * just want to enrol someone using the default role into a course
2720 *
2721 * @param object $course
2722 * @param object $user
2723 * @param string $enrol - the plugin used to do this enrolment
2724 */
2725function enrol_into_course($course, $user, $enrol) {
2726
9492291c 2727 $timestart = time();
898d7119 2728 // remove time part from the timestamp and keep only the date part
2729 $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
b963384f 2730 if ($course->enrolperiod) {
898d7119 2731 $timeend = $timestart + $course->enrolperiod;
b963384f 2732 } else {
9492291c 2733 $timeend = 0;
b963384f 2734 }
2735
2736 if ($role = get_default_course_role($course)) {
c4381ef5 2737
2738 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2739
e2183037 2740 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
b963384f 2741 return false;
2742 }
eef868d1 2743
b963384f 2744 email_welcome_message_to_user($course, $user);
eef868d1 2745
b963384f 2746 add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
2747
2748 return true;
2749 }
2750
2751 return false;
2752}
2753
0f161e1f 2754/**
2755 * Add last access times to user_lastaccess as required
2756 * @param $userid
2757 * @param $context
2758 * @return boolean - success or failure
2759 */
2760function role_add_lastaccess_entries($userid, $context) {
2761
2762 global $USER, $CFG;
2763
aad2ba95 2764 if (empty($context->contextlevel)) {
0f161e1f 2765 return false;
2766 }
2767
2768 $lastaccess = new object; // Reusable object below
2769 $lastaccess->userid = $userid;
2770 $lastaccess->timeaccess = 0;
2771
aad2ba95 2772 switch ($context->contextlevel) {
0f161e1f 2773
2774 case CONTEXT_SYSTEM: // For the whole site
2775 if ($courses = get_record('course')) {
2776 foreach ($courses as $course) {
2777 $lastaccess->courseid = $course->id;
2778 role_set_lastaccess($lastaccess);
2779 }
2780 }
2781 break;
2782
2783 case CONTEXT_CATEGORY: // For a whole category
2784 if ($courses = get_record('course', 'category', $context->instanceid)) {
2785 foreach ($courses as $course) {
2786 $lastaccess->courseid = $course->id;
2787 role_set_lastaccess($lastaccess);
2788 }
2789 }
2790 if ($categories = get_record('course_categories', 'parent', $context->instanceid)) {
2791 foreach ($categories as $category) {
2792 $subcontext = get_context_instance(CONTEXT_CATEGORY, $category->id);
2793 role_add_lastaccess_entries($userid, $subcontext);
2794 }
2795 }
2796 break;
eef868d1 2797
0f161e1f 2798
2799 case CONTEXT_COURSE: // For a whole course
2800 if ($course = get_record('course', 'id', $context->instanceid)) {
2801 $lastaccess->courseid = $course->id;
2802 role_set_lastaccess($lastaccess);
2803 }
2804 break;
2805 }
2806}
2807
2808/**
2809 * Delete last access times from user_lastaccess as required
2810 * @param $userid
2811 * @param $context
2812 * @return boolean - success or failure
2813 */
2814function role_remove_lastaccess_entries($userid, $context) {
2815
2816 global $USER, $CFG;
2817
2818}
2819
bbbf2d40 2820
2821/**
2822 * Loads the capability definitions for the component (from file). If no
2823 * capabilities are defined for the component, we simply return an empty array.
2824 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2825 * @return array of capabilities
2826 */
2827function load_capability_def($component) {
2828 global $CFG;
2829
2830 if ($component == 'moodle') {
2831 $defpath = $CFG->libdir.'/db/access.php';
2832 $varprefix = 'moodle';
2833 } else {
0c4d9f49 2834 $compparts = explode('/', $component);
eef868d1 2835
0c4d9f49 2836 if ($compparts[0] == 'block') {
2837 // Blocks are an exception. Blocks directory is 'blocks', and not
2838 // 'block'. So we need to jump through hoops.
2839 $defpath = $CFG->dirroot.'/'.$compparts[0].
2840 's/'.$compparts[1].'/db/access.php';
2841 $varprefix = $compparts[0].'_'.$compparts[1];
89bd8357 2842
ae628043 2843 } else if ($compparts[0] == 'format') {
ce34ed3a 2844 // Similar to the above, course formats are 'format' while they
ae628043 2845 // are stored in 'course/format'.
2846 $defpath = $CFG->dirroot.'/course/'.$component.'/db/access.php';
2847 $varprefix = $compparts[0].'_'.$compparts[1];
89bd8357 2848
ce34ed3a 2849 } else if ($compparts[0] == 'gradeimport') {
89bd8357 2850 $defpath = $CFG->dirroot.'/grade/import/'.$compparts[1].'/db/access.php';
2851 $varprefix = $compparts[0].'_'.$compparts[1];
2852
ce34ed3a 2853 } else if ($compparts[0] == 'gradeexport') {
89bd8357 2854 $defpath = $CFG->dirroot.'/grade/export/'.$compparts[1].'/db/access.php';
2855 $varprefix = $compparts[0].'_'.$compparts[1];
2856
ce34ed3a 2857 } else if ($compparts[0] == 'gradereport') {
89bd8357 2858 $defpath = $CFG->dirroot.'/grade/report/'.$compparts[1].'/db/access.php';
2859 $varprefix = $compparts[0].'_'.$compparts[1];
2860
0c4d9f49 2861 } else {
2862 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
2863 $varprefix = str_replace('/', '_', $component);
2864 }
bbbf2d40 2865 }
2866 $capabilities = array();
eef868d1 2867
bbbf2d40 2868 if (file_exists($defpath)) {
dc268b2f 2869 require($defpath);
bbbf2d40 2870 $capabilities = ${$varprefix.'_capabilities'};
2871 }
2872 return $capabilities;
2873}
2874
2875
2876/**
2877 * Gets the capabilities that have been cached in the database for this
2878 * component.
2879 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2880 * @return array of capabilities
2881 */
2882function get_cached_capabilities($component='moodle') {
2883 if ($component == 'moodle') {
2884 $storedcaps = get_records_select('capabilities',
2885 "name LIKE 'moodle/%:%'");
2886 } else {
2887 $storedcaps = get_records_select('capabilities',
2888 "name LIKE '$component:%'");
2889 }
2890 return $storedcaps;
2891}
2892
3562486b 2893/**
2894 * Returns default capabilities for given legacy role type.
2895 *
2896 * @param string legacy role name
2897 * @return array
2898 */
2899function get_default_capabilities($legacyrole) {
2900 if (!$allcaps = get_records('capabilities')) {
2901 error('Error: no capabilitites defined!');
2902 }
2903 $alldefs = array();
2904 $defaults = array();
2905 $components = array();
2906 foreach ($allcaps as $cap) {
efe12f6c 2907 if (!in_array($cap->component, $components)) {
3562486b 2908 $components[] = $cap->component;
2909 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2910 }
2911 }
2912 foreach($alldefs as $name=>$def) {
2913 if (isset($def['legacy'][$legacyrole])) {
2914 $defaults[$name] = $def['legacy'][$legacyrole];
2915 }
2916 }
2917
2918 //some exceptions
2919 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW;
2920 if ($legacyrole == 'admin') {
2921 $defaults['moodle/site:doanything'] = CAP_ALLOW;
2922 }
2923 return $defaults;
2924}
bbbf2d40 2925
efe12f6c 2926/**
2927 * Reset role capabilitites to default according to selected legacy capability.
2928 * If several legacy caps selected, use the first from get_default_capabilities.
2929 * If no legacy selected, removes all capabilities.
2930 *
2931 * @param int @roleid
2932 */
2933function reset_role_capabilities($roleid) {
2934 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2935 $legacyroles = get_legacy_roles();
2936
2937 $defaultcaps = array();
2938 foreach($legacyroles as $ltype=>$lcap) {
2939 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
2940 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
2941 //choose first selected legacy capability
2942 $defaultcaps = get_default_capabilities($ltype);
2943 break;
2944 }
2945 }
2946
2947 delete_records('role_capabilities', 'roleid', $roleid);
2948 if (!empty($defaultcaps)) {
2949 foreach($defaultcaps as $cap=>$permission) {
2950 assign_capability($cap, $permission, $roleid, $sitecontext->id);
2951 }
2952 }
2953}
2954
bbbf2d40 2955/**
2956 * Updates the capabilities table with the component capability definitions.
2957 * If no parameters are given, the function updates the core moodle
2958 * capabilities.
2959 *
2960 * Note that the absence of the db/access.php capabilities definition file
2961 * will cause any stored capabilities for the component to be removed from
eef868d1 2962 * the database.
bbbf2d40 2963 *
2964 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2965 * @return boolean
2966 */
2967function update_capabilities($component='moodle') {
eef868d1 2968
bbbf2d40 2969 $storedcaps = array();
be4486da 2970
2971 $filecaps = load_capability_def($component);
bbbf2d40 2972 $cachedcaps = get_cached_capabilities($component);
2973 if ($cachedcaps) {
2974 foreach ($cachedcaps as $cachedcap) {
2975 array_push($storedcaps, $cachedcap->name);
5e992f56 2976 // update risk bitmasks and context levels in existing capabilities if needed
be4486da 2977 if (array_key_exists($cachedcap->name, $filecaps)) {
2978 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2b531945 2979 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
be4486da 2980 }
2981 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
5e992f56 2982 $updatecap = new object();
be4486da 2983 $updatecap->id = $cachedcap->id;
2984 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2985 if (!update_record('capabilities', $updatecap)) {
5e992f56 2986 return false;
2987 }
2988 }
2989
2990 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2991 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2992 }
2993 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2994 $updatecap = new object();
2995 $updatecap->id = $cachedcap->id;
2996 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2997 if (!update_record('capabilities', $updatecap)) {
be4486da 2998 return false;
2999 }
3000 }
3001 }
bbbf2d40 3002 }
3003 }
be4486da 3004
bbbf2d40 3005 // Are there new capabilities in the file definition?
3006 $newcaps = array();
eef868d1 3007
bbbf2d40 3008 foreach ($filecaps as $filecap => $def) {
eef868d1 3009 if (!$storedcaps ||
bbbf2d40 3010 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2b531945 3011 if (!array_key_exists('riskbitmask', $def)) {
3012 $def['riskbitmask'] = 0; // no risk if not specified
3013 }
bbbf2d40 3014 $newcaps[$filecap] = $def;
3015 }
3016 }
3017 // Add new capabilities to the stored definition.
3018 foreach ($newcaps as $capname => $capdef) {
3019 $capability = new object;
3020 $capability->name = $capname;
3021 $capability->captype = $capdef['captype'];
3022 $capability->contextlevel = $capdef['contextlevel'];
3023 $capability->component = $component;
be4486da 3024 $capability->riskbitmask = $capdef['riskbitmask'];
eef868d1 3025
bbbf2d40 3026 if (!insert_record('capabilities', $capability, false, 'id')) {
3027 return false;
3028 }
eef868d1 3029
c421ad4b 3030
7d8ea286 3031 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
3032 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
3033 foreach ($rolecapabilities as $rolecapability){
3034 //assign_capability will update rather than insert if capability exists
c421ad4b 3035 if (!assign_capability($capname, $rolecapability->permission,
7d8ea286 3036 $rolecapability->roleid, $rolecapability->contextid, true)){
3037 notify('Could not clone capabilities for '.$capname);
c421ad4b 3038 }
7d8ea286 3039 }
c421ad4b 3040 }
bbbf2d40 3041 // Do we need to assign the new capabilities to roles that have the
3042 // legacy capabilities moodle/legacy:* as well?
7d8ea286 3043 // we ignore legacy key if we have cloned permissions
3044 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
bbbf2d40 3045 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
2e85fffe 3046 notify('Could not assign legacy capabilities for '.$capname);
bbbf2d40 3047 }
3048 }
3049 // Are there any capabilities that have been removed from the file
3050 // definition that we need to delete from the stored capabilities and
3051 // role assignments?
3052 capabilities_cleanup($component, $filecaps);
eef868d1 3053
bbbf2d40 3054 return true;
3055}
3056
3057
3058/**
3059 * Deletes cached capabilities that are no longer needed by the component.
3060 * Also unassigns these capabilities from any roles that have them.
3061 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3062 * @param $newcapdef - array of the new capability definitions that will be
3063 * compared with the cached capabilities
3064 * @return int - number of deprecated capabilities that have been removed
3065 */
3066function capabilities_cleanup($component, $newcapdef=NULL) {
eef868d1 3067
bbbf2d40 3068 $removedcount = 0;
eef868d1 3069
bbbf2d40 3070 if ($cachedcaps = get_cached_capabilities($component)) {
3071 foreach ($cachedcaps as $cachedcap) {
3072 if (empty($newcapdef) ||
3073 array_key_exists($cachedcap->name, $newcapdef) === false) {
eef868d1 3074
bbbf2d40 3075 // Remove from capabilities cache.
3076 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
3077 error('Could not delete deprecated capability '.$cachedcap->name);
3078 } else {
3079 $removedcount++;
3080 }
3081 // Delete from roles.
3082 if($roles = get_roles_with_capability($cachedcap->name)) {
3083 foreach($roles as $role) {
46943f7b 3084 if (!unassign_capability($cachedcap->name, $role->id)) {
bbbf2d40 3085 error('Could not unassign deprecated capability '.
3086 $cachedcap->name.' from role '.$role->name);
3087 }
3088 }
3089 }
3090 } // End if.
3091 }
3092 }
3093 return $removedcount;
3094}
3095
3096
3097
cee0901c 3098/****************
3099 * UI FUNCTIONS *
3100 ****************/
bbbf2d40 3101
3102
3103/**
3104 * prints human readable context identifier.
3105 */
cd26d8e0 3106function print_context_name($context, $withprefix = true, $short = false) {
340ea4e8 3107
ec0810ee 3108 $name = '';
aad2ba95 3109 switch ($context->contextlevel) {
ec0810ee 3110
bbbf2d40 3111 case CONTEXT_SYSTEM: // by now it's a definite an inherit
8cf990bc 3112 $name = get_string('coresystem');
340ea4e8 3113 break;
bbbf2d40 3114
3115 case CONTEXT_PERSONAL:
ec0810ee 3116 $name = get_string('personal');
340ea4e8 3117 break;
3118
4b10f08b 3119 case CONTEXT_USER:
ec0810ee 3120 if ($user = get_record('user', 'id', $context->instanceid)) {
cd26d8e0 3121 if ($withprefix){
3122 $name = get_string('user').': ';
3123 }
3124 $name .= fullname($user);
ec0810ee 3125 }
340ea4e8 3126 break;
3127
bbbf2d40 3128 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
ec0810ee 3129 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
cd26d8e0 3130 if ($withprefix){
3131 $name = get_string('category').': ';
3132 }
3133 $name .=format_string($category->name);
ec0810ee 3134 }
340ea4e8 3135 break;
bbbf2d40 3136
3137 case CONTEXT_COURSE: // 1 to 1 to course cat
ec0810ee 3138 if ($course = get_record('course', 'id', $context->instanceid)) {
cd26d8e0 3139 if ($withprefix){
3140 if ($context->instanceid == SITEID) {
3141 $name = get_string('site').': ';
3142 } else {
3143 $name = get_string('course').': ';
3144 }
8cf990bc 3145 }
cd26d8e0 3146 if ($short){
3147 $name .=format_string($course->shortname);
3148 } else {
3149 $name .=format_string($course->fullname);
3150 }
3151
ec0810ee 3152 }
340ea4e8 3153 break;
bbbf2d40 3154
3155 case CONTEXT_GROUP: // 1 to 1 to course
f3f7610c 3156 if ($name = groups_get_group_name($context->instanceid)) {
cd26d8e0 3157 if ($withprefix){
3158 $name = get_string('group').': '. $name;
c421ad4b 3159 }
ec0810ee 3160 }
340ea4e8 3161 break;
bbbf2d40 3162
3163 case CONTEXT_MODULE: // 1 to 1 to course
98882637 3164 if ($cm = get_record('course_modules','id',$context->instanceid)) {
3165 if ($module = get_record('modules','id',$cm->module)) {
3166 if ($mod = get_record($module->name, 'id', $cm->instance)) {
cd26d8e0 3167 if ($withprefix){
3168 $name = get_string('activitymodule').': ';
3169 }
3170 $name .= $mod->name;
98882637 3171 }
ec0810ee 3172 }
3173 }
340ea4e8 3174 break;
bbbf2d40 3175
c331cf23 3176 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
98882637 3177 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
3178 if ($block = get_record('block','id',$blockinstance->blockid)) {
91be52d7 3179 global $CFG;
3180 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
3181 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
3182 $blockname = "block_$block->name";
3183 if ($blockobject = new $blockname()) {
cd26d8e0 3184 if ($withprefix){
3185 $name = get_string('block').': ';
3186 }
3187 $name .= $blockobject->title;
91be52d7 3188 }
ec0810ee 3189 }
3190 }
340ea4e8 3191 break;
bbbf2d40 3192
3193 default:
8388ade8 3194 error ('This is an unknown context (' . $context->contextlevel . ') in print_context_name!');
340ea4e8 3195 return false;
3196
3197 }
340ea4e8 3198 return $name;
bbbf2d40 3199}
3200
3201
3202/**
eef868d1 3203 * Extracts the relevant capabilities given a contextid.
bbbf2d40 3204 * All case based, example an instance of forum context.
3205 * Will fetch all forum related capabilities, while course contexts
3206 * Will fetch all capabilities
0468976c 3207 * @param object context
bbbf2d40 3208 * @return array();
3209 *
3210