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