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