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