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