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