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