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