Added LinuxChix theme
[moodle-linuxchix.git] / lib / accesslib.php
blobf7c5fa66cc93c3c32ed936eeb1416d60f9dfc5a9
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
9 // //
10 // Copyright (C) 1999 onwards 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 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * Public API vs internals
28 * -----------------------
30 * General users probably only care about
32 * Context handling
33 * - get_context_instance()
34 * - get_context_instance_by_id()
35 * - get_parent_contexts()
36 * - get_child_contexts()
38 * Whether the user can do something...
39 * - has_capability()
40 * - require_capability()
41 * - require_login() (from moodlelib)
43 * What courses has this user access to?
44 * - get_user_courses_bycap()
46 * What users can do X in this context?
47 * - get_users_by_capability()
49 * Enrol/unenrol
50 * - enrol_into_course()
51 * - role_assign()/role_unassign()
54 * Advanced use
55 * - load_all_capabilities()
56 * - reload_all_capabilities()
57 * - $ACCESS global
58 * - has_capability_in_accessdata()
59 * - is_siteadmin()
60 * - get_user_access_sitewide()
61 * - load_subcontext()
62 * - get_role_access_bycontext()
64 * Name conventions
65 * ----------------
67 * - "ctx" means context
69 * accessdata
70 * ----------
72 * Access control data is held in the "accessdata" array
73 * which - for the logged-in user, will be in $USER->access
75 * For other users can be generated and passed around (but see
76 * the $ACCESS global).
78 * $accessdata is a multidimensional array, holding
79 * role assignments (RAs), role-capabilities-perm sets
80 * (role defs) and a list of courses we have loaded
81 * data for.
83 * Things are keyed on "contextpaths" (the path field of
84 * the context table) for fast walking up/down the tree.
86 * $accessdata[ra][$contextpath]= array($roleid)
87 * [$contextpath]= array($roleid)
88 * [$contextpath]= array($roleid)
90 * Role definitions are stored like this
91 * (no cap merge is done - so it's compact)
93 * $accessdata[rdef][$contextpath:$roleid][mod/forum:viewpost] = 1
94 * [mod/forum:editallpost] = -1
95 * [mod/forum:startdiscussion] = -1000
97 * See how has_capability_in_accessdata() walks up/down the tree.
99 * Normally - specially for the logged-in user, we only load
100 * rdef and ra down to the course level, but not below. This
101 * keeps accessdata small and compact. Below-the-course ra/rdef
102 * are loaded as needed. We keep track of which courses we
103 * have loaded ra/rdef in
105 * $accessdata[loaded] = array($contextpath, $contextpath)
107 * Stale accessdata
108 * ----------------
110 * For the logged-in user, accessdata is long-lived.
112 * On each pageload we load $DIRTYPATHS which lists
113 * context paths affected by changes. Any check at-or-below
114 * a dirty context will trigger a transparent reload of accessdata.
116 * Changes at the sytem level will force the reload for everyone.
118 * Default role caps
119 * -----------------
120 * The default role assignment is not in the DB, so we
121 * add it manually to accessdata.
123 * This means that functions that work directly off the
124 * DB need to ensure that the default role caps
125 * are dealt with appropriately.
129 require_once $CFG->dirroot.'/lib/blocklib.php';
131 // permission definitions
132 define('CAP_INHERIT', 0);
133 define('CAP_ALLOW', 1);
134 define('CAP_PREVENT', -1);
135 define('CAP_PROHIBIT', -1000);
137 // context definitions
138 define('CONTEXT_SYSTEM', 10);
139 define('CONTEXT_USER', 30);
140 define('CONTEXT_COURSECAT', 40);
141 define('CONTEXT_COURSE', 50);
142 define('CONTEXT_GROUP', 60);
143 define('CONTEXT_MODULE', 70);
144 define('CONTEXT_BLOCK', 80);
146 // capability risks - see http://docs.moodle.org/en/Hardening_new_Roles_system
147 define('RISK_MANAGETRUST', 0x0001);
148 define('RISK_CONFIG', 0x0002);
149 define('RISK_XSS', 0x0004);
150 define('RISK_PERSONAL', 0x0008);
151 define('RISK_SPAM', 0x0010);
153 // rolename displays
154 define('ROLENAME_ORIGINAL', 0);// the name as defined in the role definition
155 define('ROLENAME_ALIAS', 1); // the name as defined by a role alias
156 define('ROLENAME_BOTH', 2); // Both, like this: Role alias (Original)
158 require_once($CFG->dirroot.'/group/lib.php');
160 $context_cache = array(); // Cache of all used context objects for performance (by level and instance)
161 $context_cache_id = array(); // Index to above cache by id
163 $DIRTYCONTEXTS = null; // dirty contexts cache
164 $ACCESS = array(); // cache of caps for cron user switching and has_capability for other users (==not $USER)
165 $RDEFS = array(); // role definitions cache - helps a lot with mem usage in cron
167 function get_role_context_caps($roleid, $context) {
168 //this is really slow!!!! - do not use above course context level!
169 $result = array();
170 $result[$context->id] = array();
172 // first emulate the parent context capabilities merging into context
173 $searchcontexts = array_reverse(get_parent_contexts($context));
174 array_push($searchcontexts, $context->id);
175 foreach ($searchcontexts as $cid) {
176 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
177 foreach ($capabilities as $cap) {
178 if (!array_key_exists($cap->capability, $result[$context->id])) {
179 $result[$context->id][$cap->capability] = 0;
181 $result[$context->id][$cap->capability] += $cap->permission;
186 // now go through the contexts bellow given context
187 $searchcontexts = array_keys(get_child_contexts($context));
188 foreach ($searchcontexts as $cid) {
189 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
190 foreach ($capabilities as $cap) {
191 if (!array_key_exists($cap->contextid, $result)) {
192 $result[$cap->contextid] = array();
194 $result[$cap->contextid][$cap->capability] = $cap->permission;
199 return $result;
203 * Gets the accessdata for role "sitewide"
204 * (system down to course)
206 * @return array
208 function get_role_access($roleid, $accessdata=NULL) {
210 global $CFG;
212 /* Get it in 1 cheap DB query...
213 * - relevant role caps at the root and down
214 * to the course level - but not below
216 if (is_null($accessdata)) {
217 $accessdata = array(); // named list
218 $accessdata['ra'] = array();
219 $accessdata['rdef'] = array();
220 $accessdata['loaded'] = array();
224 // Overrides for the role IN ANY CONTEXTS
225 // down to COURSE - not below -
227 $sql = "SELECT ctx.path,
228 rc.capability, rc.permission
229 FROM {$CFG->prefix}context ctx
230 JOIN {$CFG->prefix}role_capabilities rc
231 ON rc.contextid=ctx.id
232 WHERE rc.roleid = {$roleid}
233 AND ctx.contextlevel <= ".CONTEXT_COURSE."
234 ORDER BY ctx.depth, ctx.path";
236 // we need extra caching in cron only
237 if (defined('FULLME') and FULLME === 'cron') {
238 static $cron_cache = array();
240 if (!isset($cron_cache[$roleid])) {
241 $cron_cache[$roleid] = array();
242 if ($rs = get_recordset_sql($sql)) {
243 while ($rd = rs_fetch_next_record($rs)) {
244 $cron_cache[$roleid][] = $rd;
246 rs_close($rs);
250 foreach ($cron_cache[$roleid] as $rd) {
251 $k = "{$rd->path}:{$roleid}";
252 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
255 } else {
256 if ($rs = get_recordset_sql($sql)) {
257 while ($rd = rs_fetch_next_record($rs)) {
258 $k = "{$rd->path}:{$roleid}";
259 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
261 unset($rd);
262 rs_close($rs);
266 return $accessdata;
270 * Gets the accessdata for role "sitewide"
271 * (system down to course)
273 * @return array
275 function get_default_frontpage_role_access($roleid, $accessdata=NULL) {
277 global $CFG;
279 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
280 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
283 // Overrides for the role in any contexts related to the course
285 $sql = "SELECT ctx.path,
286 rc.capability, rc.permission
287 FROM {$CFG->prefix}context ctx
288 JOIN {$CFG->prefix}role_capabilities rc
289 ON rc.contextid=ctx.id
290 WHERE rc.roleid = {$roleid}
291 AND (ctx.id = ".SYSCONTEXTID." OR ctx.path LIKE '$base/%')
292 AND ctx.contextlevel <= ".CONTEXT_COURSE."
293 ORDER BY ctx.depth, ctx.path";
295 if ($rs = get_recordset_sql($sql)) {
296 while ($rd = rs_fetch_next_record($rs)) {
297 $k = "{$rd->path}:{$roleid}";
298 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
300 unset($rd);
301 rs_close($rs);
304 return $accessdata;
309 * Get the default guest role
310 * @return object role
312 function get_guest_role() {
313 global $CFG;
315 if (empty($CFG->guestroleid)) {
316 if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
317 $guestrole = array_shift($roles); // Pick the first one
318 set_config('guestroleid', $guestrole->id);
319 return $guestrole;
320 } else {
321 debugging('Can not find any guest role!');
322 return false;
324 } else {
325 if ($guestrole = get_record('role','id', $CFG->guestroleid)) {
326 return $guestrole;
327 } else {
328 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
329 set_config('guestroleid', '');
330 return get_guest_role();
336 * This function returns whether the current user has the capability of performing a function
337 * For example, we can do has_capability('mod/forum:replypost',$context) in forum
338 * @param string $capability - name of the capability (or debugcache or clearcache)
339 * @param object $context - a context object (record from context table)
340 * @param integer $userid - a userid number, empty if current $USER
341 * @param bool $doanything - if false, ignore do anything
342 * @return bool
344 function has_capability($capability, $context, $userid=NULL, $doanything=true) {
345 global $USER, $ACCESS, $CFG, $DIRTYCONTEXTS;
347 // the original $CONTEXT here was hiding serious errors
348 // for security reasons do not reuse previous context
349 if (empty($context)) {
350 debugging('Incorrect context specified');
351 return false;
354 /// Some sanity checks
355 if (debugging('',DEBUG_DEVELOPER)) {
356 static $capsnames = null; // one request per page only
358 if (is_null($capsnames)) {
359 if ($caps = get_records('capabilities', '', '', '', 'id, name')) {
360 $capsnames = array();
361 foreach ($caps as $cap) {
362 $capsnames[$cap->name] = true;
366 if ($capsnames) { // ignore if can not fetch caps
367 if (!isset($capsnames[$capability])) {
368 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
371 if (!is_bool($doanything)) {
372 debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
376 if (empty($userid)) { // we must accept null, 0, '0', '' etc. in $userid
377 $userid = $USER->id;
380 if (is_null($context->path) or $context->depth == 0) {
381 //this should not happen
382 $contexts = array(SYSCONTEXTID, $context->id);
383 $context->path = '/'.SYSCONTEXTID.'/'.$context->id;
384 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()', DEBUG_DEVELOPER);
386 } else {
387 $contexts = explode('/', $context->path);
388 array_shift($contexts);
391 if (defined('FULLME') && FULLME === 'cron' && !isset($USER->access)) {
392 // In cron, some modules setup a 'fake' $USER,
393 // ensure we load the appropriate accessdata.
394 if (isset($ACCESS[$userid])) {
395 $DIRTYCONTEXTS = NULL; //load fresh dirty contexts
396 } else {
397 load_user_accessdata($userid);
398 $DIRTYCONTEXTS = array();
400 $USER->access = $ACCESS[$userid];
402 } else if ($USER->id == $userid && !isset($USER->access)) {
403 // caps not loaded yet - better to load them to keep BC with 1.8
404 // not-logged-in user or $USER object set up manually first time here
405 load_all_capabilities();
406 $ACCESS = array(); // reset the cache for other users too, the dirty contexts are empty now
407 $RDEFS = array();
410 // Load dirty contexts list if needed
411 if (!isset($DIRTYCONTEXTS)) {
412 if (isset($USER->access['time'])) {
413 $DIRTYCONTEXTS = get_dirty_contexts($USER->access['time']);
415 else {
416 $DIRTYCONTEXTS = array();
420 // Careful check for staleness...
421 if (count($DIRTYCONTEXTS) !== 0 and is_contextpath_dirty($contexts, $DIRTYCONTEXTS)) {
422 // reload all capabilities - preserving loginas, roleswitches, etc
423 // and then cleanup any marks of dirtyness... at least from our short
424 // term memory! :-)
425 $ACCESS = array();
426 $RDEFS = array();
428 if (defined('FULLME') && FULLME === 'cron') {
429 load_user_accessdata($userid);
430 $USER->access = $ACCESS[$userid];
431 $DIRTYCONTEXTS = array();
433 } else {
434 reload_all_capabilities();
438 // divulge how many times we are called
439 //// error_log("has_capability: id:{$context->id} path:{$context->path} userid:$userid cap:$capability");
441 if ($USER->id == $userid) { // we must accept strings and integers in $userid
443 // For the logged in user, we have $USER->access
444 // which will have all RAs and caps preloaded for
445 // course and above contexts.
447 // Contexts below courses && contexts that do not
448 // hang from courses are loaded into $USER->access
449 // on demand, and listed in $USER->access[loaded]
451 if ($context->contextlevel <= CONTEXT_COURSE) {
452 // Course and above are always preloaded
453 return has_capability_in_accessdata($capability, $context, $USER->access, $doanything);
455 // Load accessdata for below-the-course contexts
456 if (!path_inaccessdata($context->path,$USER->access)) {
457 // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
458 // $bt = debug_backtrace();
459 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
460 load_subcontext($USER->id, $context, $USER->access);
462 return has_capability_in_accessdata($capability, $context, $USER->access, $doanything);
465 if (!isset($ACCESS[$userid])) {
466 load_user_accessdata($userid);
468 if ($context->contextlevel <= CONTEXT_COURSE) {
469 // Course and above are always preloaded
470 return has_capability_in_accessdata($capability, $context, $ACCESS[$userid], $doanything);
472 // Load accessdata for below-the-course contexts as needed
473 if (!path_inaccessdata($context->path, $ACCESS[$userid])) {
474 // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
475 // $bt = debug_backtrace();
476 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
477 load_subcontext($userid, $context, $ACCESS[$userid]);
479 return has_capability_in_accessdata($capability, $context, $ACCESS[$userid], $doanything);
483 * This function returns whether the current user has any of the capabilities in the
484 * $capabilities array. This is a simple wrapper around has_capability for convinience.
486 * There are probably tricks that could be done to improve the performance here, for example,
487 * check the capabilities that are already cached first.
489 * @param array $capabilities - an array of capability names.
490 * @param object $context - a context object (record from context table)
491 * @param integer $userid - a userid number, empty if current $USER
492 * @param bool $doanything - if false, ignore do anything
493 * @return bool
495 function has_any_capability($capabilities, $context, $userid=NULL, $doanything=true) {
496 foreach ($capabilities as $capability) {
497 if (has_capability($capability, $context, $userid, $doanything)) {
498 return true;
501 return false;
505 * Uses 1 DB query to answer whether a user is an admin at the sitelevel.
506 * It depends on DB schema >=1.7 but does not depend on the new datastructures
507 * in v1.9 (context.path, or $USER->access)
509 * Will return true if the userid has any of
510 * - moodle/site:config
511 * - moodle/legacy:admin
512 * - moodle/site:doanything
514 * @param int $userid
515 * @returns bool $isadmin
517 function is_siteadmin($userid) {
518 global $CFG;
520 $sql = "SELECT SUM(rc.permission)
521 FROM " . $CFG->prefix . "role_capabilities rc
522 JOIN " . $CFG->prefix . "context ctx
523 ON ctx.id=rc.contextid
524 JOIN " . $CFG->prefix . "role_assignments ra
525 ON ra.roleid=rc.roleid AND ra.contextid=ctx.id
526 WHERE ctx.contextlevel=10
527 AND ra.userid={$userid}
528 AND rc.capability IN ('moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything')
529 GROUP BY rc.capability
530 HAVING SUM(rc.permission) > 0";
532 $isadmin = record_exists_sql($sql);
533 return $isadmin;
536 function get_course_from_path ($path) {
537 // assume that nothing is more than 1 course deep
538 if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
539 return $matches[1];
541 return false;
544 function path_inaccessdata($path, $accessdata) {
546 // assume that contexts hang from sys or from a course
547 // this will only work well with stuff that hangs from a course
548 if (in_array($path, $accessdata['loaded'], true)) {
549 // error_log("found it!");
550 return true;
552 $base = '/' . SYSCONTEXTID;
553 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
554 $path = $matches[1];
555 if ($path === $base) {
556 return false;
558 if (in_array($path, $accessdata['loaded'], true)) {
559 return true;
562 return false;
566 * Walk the accessdata array and return true/false.
567 * Deals with prohibits, roleswitching, aggregating
568 * capabilities, etc.
570 * The main feature of here is being FAST and with no
571 * side effects.
573 * Notes:
575 * Switch Roles exits early
576 * -----------------------
577 * cap checks within a switchrole need to exit early
578 * in our bottom up processing so they don't "see" that
579 * there are real RAs that can do all sorts of things.
581 * Switch Role merges with default role
582 * ------------------------------------
583 * If you are a teacher in course X, you have at least
584 * teacher-in-X + defaultloggedinuser-sitewide. So in the
585 * course you'll have techer+defaultloggedinuser.
586 * We try to mimic that in switchrole.
588 * Local-most role definition and role-assignment wins
589 * ---------------------------------------------------
590 * So if the local context has said 'allow', it wins
591 * over a high-level context that says 'deny'.
592 * This is applied when walking rdefs, and RAs.
593 * Only at the same context the values are SUM()med.
595 * The exception is CAP_PROHIBIT.
597 * "Guest default role" exception
598 * ------------------------------
600 * See MDL-7513 and $ignoreguest below for details.
602 * The rule is that
604 * IF we are being asked about moodle/legacy:guest
605 * OR moodle/course:view
606 * FOR a real, logged-in user
607 * AND we reached the top of the path in ra and rdef
608 * AND that role has moodle/legacy:guest === 1...
609 * THEN we act as if we hadn't seen it.
612 * To Do:
614 * - Document how it works
615 * - Rewrite in ASM :-)
618 function has_capability_in_accessdata($capability, $context, $accessdata, $doanything) {
620 global $CFG;
622 $path = $context->path;
624 // build $contexts as a list of "paths" of the current
625 // contexts and parents with the order top-to-bottom
626 $contexts = array($path);
627 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
628 $path = $matches[1];
629 array_unshift($contexts, $path);
632 $ignoreguest = false;
633 if (isset($accessdata['dr'])
634 && ($capability == 'moodle/course:view'
635 || $capability == 'moodle/legacy:guest')) {
636 // At the base, ignore rdefs where moodle/legacy:guest
637 // is set
638 $ignoreguest = $accessdata['dr'];
641 // Coerce it to an int
642 $CAP_PROHIBIT = (int)CAP_PROHIBIT;
644 $cc = count($contexts);
646 $can = 0;
647 $capdepth = 0;
650 // role-switches loop
652 if (isset($accessdata['rsw'])) {
653 // check for isset() is fast
654 // empty() is slow...
655 if (empty($accessdata['rsw'])) {
656 unset($accessdata['rsw']); // keep things fast and unambiguous
657 break;
659 // From the bottom up...
660 for ($n=$cc-1;$n>=0;$n--) {
661 $ctxp = $contexts[$n];
662 if (isset($accessdata['rsw'][$ctxp])) {
663 // Found a switchrole assignment
664 // check for that role _plus_ the default user role
665 $ras = array($accessdata['rsw'][$ctxp],$CFG->defaultuserroleid);
666 for ($rn=0;$rn<2;$rn++) {
667 $roleid = (int)$ras[$rn];
668 // Walk the path for capabilities
669 // from the bottom up...
670 for ($m=$cc-1;$m>=0;$m--) {
671 $capctxp = $contexts[$m];
672 if (isset($accessdata['rdef']["{$capctxp}:$roleid"][$capability])) {
673 $perm = (int)$accessdata['rdef']["{$capctxp}:$roleid"][$capability];
675 // The most local permission (first to set) wins
676 // the only exception is CAP_PROHIBIT
677 if ($can === 0) {
678 $can = $perm;
679 } elseif ($perm === $CAP_PROHIBIT) {
680 $can = $perm;
681 break;
686 // As we are dealing with a switchrole,
687 // we return _here_, do _not_ walk up
688 // the hierarchy any further
689 if ($can < 1) {
690 if ($doanything) {
691 // didn't find it as an explicit cap,
692 // but maybe the user candoanything in this context...
693 return has_capability_in_accessdata('moodle/site:doanything', $context, $accessdata, false);
694 } else {
695 return false;
697 } else {
698 return true;
706 // Main loop for normal RAs
707 // From the bottom up...
709 for ($n=$cc-1;$n>=0;$n--) {
710 $ctxp = $contexts[$n];
711 if (isset($accessdata['ra'][$ctxp])) {
712 // Found role assignments on this leaf
713 $ras = $accessdata['ra'][$ctxp];
715 $rc = count($ras);
716 $ctxcan = 0;
717 $ctxcapdepth = 0;
718 for ($rn=0;$rn<$rc;$rn++) {
719 $roleid = (int)$ras[$rn];
720 $rolecan = 0;
721 $rolecapdepth = 0;
722 // Walk the path for capabilities
723 // from the bottom up...
724 for ($m=$cc-1;$m>=0;$m--) {
725 $capctxp = $contexts[$m];
726 // ignore some guest caps
727 // at base ra and rdef
728 if ($ignoreguest == $roleid
729 && $n === 0
730 && $m === 0
731 && isset($accessdata['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'])
732 && $accessdata['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'] > 0) {
733 continue;
735 if (isset($accessdata['rdef']["{$capctxp}:$roleid"][$capability])) {
736 $perm = (int)$accessdata['rdef']["{$capctxp}:$roleid"][$capability];
737 // The most local permission (first to set) wins
738 // the only exception is CAP_PROHIBIT
739 if ($rolecan === 0) {
740 $rolecan = $perm;
741 $rolecapdepth = $m;
742 } elseif ($perm === $CAP_PROHIBIT) {
743 $rolecan = $perm;
744 $rolecapdepth = $m;
745 break;
749 // Rules for RAs at the same context...
750 // - prohibits always wins
751 // - permissions at the same ctxlevel & capdepth are added together
752 // - deeper capdepth wins
753 if ($ctxcan === $CAP_PROHIBIT || $rolecan === $CAP_PROHIBIT) {
754 $ctxcan = $CAP_PROHIBIT;
755 $ctxcapdepth = 0;
756 } elseif ($ctxcapdepth === $rolecapdepth) {
757 $ctxcan += $rolecan;
758 } elseif ($ctxcapdepth < $rolecapdepth) {
759 $ctxcan = $rolecan;
760 $ctxcapdepth = $rolecapdepth;
761 } else { // ctxcaptdepth is deeper
762 // rolecap ignored
765 // The most local RAs with a defined
766 // permission ($ctxcan) win, except
767 // for CAP_PROHIBIT
768 // NOTE: If we want the deepest RDEF to
769 // win regardless of the depth of the RA,
770 // change the elseif below to read
771 // ($can === 0 || $capdepth < $ctxcapdepth) {
772 if ($ctxcan === $CAP_PROHIBIT) {
773 $can = $ctxcan;
774 break;
775 } elseif ($can === 0) { // see note above
776 $can = $ctxcan;
777 $capdepth = $ctxcapdepth;
782 if ($can < 1) {
783 if ($doanything) {
784 // didn't find it as an explicit cap,
785 // but maybe the user candoanything in this context...
786 return has_capability_in_accessdata('moodle/site:doanything', $context, $accessdata, false);
787 } else {
788 return false;
790 } else {
791 return true;
796 function aggregate_roles_from_accessdata($context, $accessdata) {
798 $path = $context->path;
800 // build $contexts as a list of "paths" of the current
801 // contexts and parents with the order top-to-bottom
802 $contexts = array($path);
803 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
804 $path = $matches[1];
805 array_unshift($contexts, $path);
808 $cc = count($contexts);
810 $roles = array();
811 // From the bottom up...
812 for ($n=$cc-1;$n>=0;$n--) {
813 $ctxp = $contexts[$n];
814 if (isset($accessdata['ra'][$ctxp]) && count($accessdata['ra'][$ctxp])) {
815 // Found assignments on this leaf
816 $addroles = $accessdata['ra'][$ctxp];
817 $roles = array_merge($roles, $addroles);
821 return array_unique($roles);
825 * This is an easy to use function, combining has_capability() with require_course_login().
826 * And will call those where needed.
828 * It checks for a capability assertion being true. If it isn't
829 * then the page is terminated neatly with a standard error message.
831 * If the user is not logged in, or is using 'guest' access or other special "users,
832 * it provides a logon prompt.
834 * @param string $capability - name of the capability
835 * @param object $context - a context object (record from context table)
836 * @param integer $userid - a userid number
837 * @param bool $doanything - if false, ignore do anything
838 * @param string $errorstring - an errorstring
839 * @param string $stringfile - which stringfile to get it from
841 function require_capability($capability, $context, $userid=NULL, $doanything=true,
842 $errormessage='nopermissions', $stringfile='') {
844 global $USER, $CFG;
846 /* Empty $userid means current user, if the current user is not logged in,
847 * then make sure they are (if needed).
848 * Originally there was a check for loaded permissions - it is not needed here.
849 * Context is now required parameter, the cached $CONTEXT was only hiding errors.
851 $errorlink = '';
853 if (empty($userid)) {
854 if ($context->contextlevel == CONTEXT_COURSE) {
855 require_login($context->instanceid);
857 } else if ($context->contextlevel == CONTEXT_MODULE) {
858 if (!$cm = get_record('course_modules', 'id', $context->instanceid)) {
859 error('Incorrect module');
861 if (!$course = get_record('course', 'id', $cm->course)) {
862 error('Incorrect course.');
864 require_course_login($course, true, $cm);
865 $errorlink = $CFG->wwwroot.'/course/view.php?id='.$cm->course;
867 } else if ($context->contextlevel == CONTEXT_SYSTEM) {
868 if (!empty($CFG->forcelogin)) {
869 require_login();
872 } else {
873 require_login();
877 /// OK, if they still don't have the capability then print a nice error message
879 if (!has_capability($capability, $context, $userid, $doanything)) {
880 $capabilityname = get_capability_string($capability);
881 print_error($errormessage, $stringfile, $errorlink, $capabilityname);
886 * Get an array of courses (with magic extra bits)
887 * where the accessdata and in DB enrolments show
888 * that the cap requested is available.
890 * The main use is for get_my_courses().
892 * Notes
894 * - $fields is an array of fieldnames to ADD
895 * so name the fields you really need, which will
896 * be added and uniq'd
898 * - the course records have $c->context which is a fully
899 * valid context object. Saves you a query per course!
901 * - the course records have $c->categorypath to make
902 * category lookups cheap
904 * - current implementation is split in -
906 * - if the user has the cap systemwide, stupidly
907 * grab *every* course for a capcheck. This eats
908 * a TON of bandwidth, specially on large sites
909 * with separate DBs...
911 * - otherwise, fetch "likely" courses with a wide net
912 * that should get us _cheaply_ at least the courses we need, and some
913 * we won't - we get courses that...
914 * - are in a category where user has the cap
915 * - or where use has a role-assignment (any kind)
916 * - or where the course has an override on for this cap
918 * - walk the courses recordset checking the caps oneach one
919 * the checks are all in memory and quite fast
920 * (though we could implement a specialised variant of the
921 * has_capability_in_accessdata() code to speed it up)
923 * @param string $capability - name of the capability
924 * @param array $accessdata - accessdata session array
925 * @param bool $doanything - if false, ignore do anything
926 * @param string $sort - sorting fields - prefix each fieldname with "c."
927 * @param array $fields - additional fields you are interested in...
928 * @param int $limit - set if you want to limit the number of courses
929 * @return array $courses - ordered array of course objects - see notes above
932 function get_user_courses_bycap($userid, $cap, $accessdata, $doanything, $sort='c.sortorder ASC', $fields=NULL, $limit=0) {
934 global $CFG;
936 // Slim base fields, let callers ask for what they need...
937 $basefields = array('id', 'sortorder', 'shortname', 'idnumber');
939 if (!is_null($fields)) {
940 $fields = array_merge($basefields, $fields);
941 $fields = array_unique($fields);
942 } else {
943 $fields = $basefields;
945 $coursefields = 'c.' .implode(',c.', $fields);
947 $sort = trim($sort);
948 if ($sort !== '') {
949 $sort = "ORDER BY $sort";
952 $sysctx = get_context_instance(CONTEXT_SYSTEM);
953 if (has_capability_in_accessdata($cap, $sysctx, $accessdata, $doanything)) {
955 // Apparently the user has the cap sitewide, so walk *every* course
956 // (the cap checks are moderately fast, but this moves massive bandwidth w the db)
957 // Yuck.
959 $sql = "SELECT $coursefields,
960 ctx.id AS ctxid, ctx.path AS ctxpath,
961 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel,
962 cc.path AS categorypath
963 FROM {$CFG->prefix}course c
964 JOIN {$CFG->prefix}course_categories cc
965 ON c.category=cc.id
966 JOIN {$CFG->prefix}context ctx
967 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
968 $sort ";
969 $rs = get_recordset_sql($sql);
970 } else {
972 // narrow down where we have the caps to a few contexts
973 // this will be a combination of
974 // - categories where we have the rights
975 // - courses where we have an explicit enrolment OR that have an override
977 $sql = "SELECT ctx.*
978 FROM {$CFG->prefix}context ctx
979 WHERE ctx.contextlevel=".CONTEXT_COURSECAT."
980 ORDER BY ctx.depth";
981 $rs = get_recordset_sql($sql);
982 $catpaths = array();
983 while ($catctx = rs_fetch_next_record($rs)) {
984 if ($catctx->path != ''
985 && has_capability_in_accessdata($cap, $catctx, $accessdata, $doanything)) {
986 $catpaths[] = $catctx->path;
989 rs_close($rs);
990 $catclause = '';
991 if (count($catpaths)) {
992 $cc = count($catpaths);
993 for ($n=0;$n<$cc;$n++) {
994 $catpaths[$n] = "ctx.path LIKE '{$catpaths[$n]}/%'";
996 $catclause = 'OR (' . implode(' OR ', $catpaths) .')';
998 unset($catpaths);
1000 $capany = '';
1001 if ($doanything) {
1002 $capany = " OR rc.capability='moodle/site:doanything'";
1005 // Note here that we *have* to have the compound clauses
1006 // in the LEFT OUTER JOIN condition for them to return NULL
1007 // appropriately and narrow things down...
1009 $sql = "SELECT $coursefields,
1010 ctx.id AS ctxid, ctx.path AS ctxpath,
1011 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel,
1012 cc.path AS categorypath
1013 FROM {$CFG->prefix}course c
1014 JOIN {$CFG->prefix}course_categories cc
1015 ON c.category=cc.id
1016 JOIN {$CFG->prefix}context ctx
1017 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
1018 LEFT OUTER JOIN {$CFG->prefix}role_assignments ra
1019 ON (ra.contextid=ctx.id AND ra.userid=$userid)
1020 LEFT OUTER JOIN {$CFG->prefix}role_capabilities rc
1021 ON (rc.contextid=ctx.id AND (rc.capability='$cap' $capany))
1022 WHERE ra.id IS NOT NULL
1023 OR rc.id IS NOT NULL
1024 $catclause
1025 $sort ";
1026 $rs = get_recordset_sql($sql);
1028 $courses = array();
1029 $cc = 0; // keep count
1030 while ($c = rs_fetch_next_record($rs)) {
1031 // build the context obj
1032 $c = make_context_subobj($c);
1034 if (has_capability_in_accessdata($cap, $c->context, $accessdata, $doanything)) {
1035 $courses[] = $c;
1036 if ($limit > 0 && $cc++ > $limit) {
1037 break;
1041 rs_close($rs);
1042 return $courses;
1047 * It will return a nested array showing role assignments
1048 * all relevant role capabilities for the user at
1049 * site/metacourse/course_category/course levels
1051 * We do _not_ delve deeper than courses because the number of
1052 * overrides at the module/block levels is HUGE.
1054 * [ra] => [/path/] = array(roleid, roleid)
1055 * [rdef] => [/path/:roleid][capability]=permission
1056 * [loaded] => array('/path', '/path')
1058 * @param $userid integer - the id of the user
1061 function get_user_access_sitewide($userid) {
1063 global $CFG;
1065 // this flag has not been set!
1066 // (not clean install, or upgraded successfully to 1.7 and up)
1067 if (empty($CFG->rolesactive)) {
1068 return false;
1071 /* Get in 3 cheap DB queries...
1072 * - role assignments - with role_caps
1073 * - relevant role caps
1074 * - above this user's RAs
1075 * - below this user's RAs - limited to course level
1078 $accessdata = array(); // named list
1079 $accessdata['ra'] = array();
1080 $accessdata['rdef'] = array();
1081 $accessdata['loaded'] = array();
1083 $sitectx = get_system_context();
1084 $base = '/'.$sitectx->id;
1087 // Role assignments - and any rolecaps directly linked
1088 // because it's cheap to read rolecaps here over many
1089 // RAs
1091 $sql = "SELECT ctx.path, ra.roleid, rc.capability, rc.permission
1092 FROM {$CFG->prefix}role_assignments ra
1093 JOIN {$CFG->prefix}context ctx
1094 ON ra.contextid=ctx.id
1095 LEFT OUTER JOIN {$CFG->prefix}role_capabilities rc
1096 ON (rc.roleid=ra.roleid AND rc.contextid=ra.contextid)
1097 WHERE ra.userid = $userid AND ctx.contextlevel <= ".CONTEXT_COURSE."
1098 ORDER BY ctx.depth, ctx.path";
1099 $rs = get_recordset_sql($sql);
1101 // raparents collects paths & roles we need to walk up
1102 // the parenthood to build the rdef
1104 // the array will bulk up a bit with dups
1105 // which we'll later clear up
1107 $raparents = array();
1108 $lastseen = '';
1109 if ($rs) {
1110 while ($ra = rs_fetch_next_record($rs)) {
1111 // RAs leafs are arrays to support multi
1112 // role assignments...
1113 if (!isset($accessdata['ra'][$ra->path])) {
1114 $accessdata['ra'][$ra->path] = array();
1116 // only add if is not a repeat caused
1117 // by capability join...
1118 // (this check is cheaper than in_array())
1119 if ($lastseen !== $ra->path.':'.$ra->roleid) {
1120 $lastseen = $ra->path.':'.$ra->roleid;
1121 array_push($accessdata['ra'][$ra->path], $ra->roleid);
1122 $parentids = explode('/', $ra->path);
1123 array_shift($parentids); // drop empty leading "context"
1124 array_pop($parentids); // drop _this_ context
1126 if (isset($raparents[$ra->roleid])) {
1127 $raparents[$ra->roleid] = array_merge($raparents[$ra->roleid],
1128 $parentids);
1129 } else {
1130 $raparents[$ra->roleid] = $parentids;
1133 // Always add the roleded
1134 if (!empty($ra->capability)) {
1135 $k = "{$ra->path}:{$ra->roleid}";
1136 $accessdata['rdef'][$k][$ra->capability] = $ra->permission;
1139 unset($ra);
1140 rs_close($rs);
1143 // Walk up the tree to grab all the roledefs
1144 // of interest to our user...
1145 // NOTE: we use a series of IN clauses here - which
1146 // might explode on huge sites with very convoluted nesting of
1147 // categories... - extremely unlikely that the number of categories
1148 // and roletypes is so large that we hit the limits of IN()
1149 $clauses = array();
1150 foreach ($raparents as $roleid=>$contexts) {
1151 $contexts = implode(',', array_unique($contexts));
1152 if ($contexts ==! '') {
1153 $clauses[] = "(roleid=$roleid AND contextid IN ($contexts))";
1156 $clauses = implode(" OR ", $clauses);
1157 if ($clauses !== '') {
1158 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1159 FROM {$CFG->prefix}role_capabilities rc
1160 JOIN {$CFG->prefix}context ctx
1161 ON rc.contextid=ctx.id
1162 WHERE $clauses
1163 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1165 $rs = get_recordset_sql($sql);
1166 unset($clauses);
1168 if ($rs) {
1169 while ($rd = rs_fetch_next_record($rs)) {
1170 $k = "{$rd->path}:{$rd->roleid}";
1171 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1173 unset($rd);
1174 rs_close($rs);
1179 // Overrides for the role assignments IN SUBCONTEXTS
1180 // (though we still do _not_ go below the course level.
1182 // NOTE that the JOIN w sctx is with 3-way triangulation to
1183 // catch overrides to the applicable role in any subcontext, based
1184 // on the path field of the parent.
1186 $sql = "SELECT sctx.path, ra.roleid,
1187 ctx.path AS parentpath,
1188 rco.capability, rco.permission
1189 FROM {$CFG->prefix}role_assignments ra
1190 JOIN {$CFG->prefix}context ctx
1191 ON ra.contextid=ctx.id
1192 JOIN {$CFG->prefix}context sctx
1193 ON (sctx.path LIKE " . sql_concat('ctx.path',"'/%'"). " )
1194 JOIN {$CFG->prefix}role_capabilities rco
1195 ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
1196 WHERE ra.userid = $userid
1197 AND sctx.contextlevel <= ".CONTEXT_COURSE."
1198 ORDER BY sctx.depth, sctx.path, ra.roleid";
1200 $rs = get_recordset_sql($sql);
1201 if ($rs) {
1202 while ($rd = rs_fetch_next_record($rs)) {
1203 $k = "{$rd->path}:{$rd->roleid}";
1204 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1206 unset($rd);
1207 rs_close($rs);
1209 return $accessdata;
1213 * It add to the access ctrl array the data
1214 * needed by a user for a given context
1216 * @param $userid integer - the id of the user
1217 * @param $context context obj - needs path!
1218 * @param $accessdata array accessdata array
1220 function load_subcontext($userid, $context, &$accessdata) {
1222 global $CFG;
1226 /* Get the additional RAs and relevant rolecaps
1227 * - role assignments - with role_caps
1228 * - relevant role caps
1229 * - above this user's RAs
1230 * - below this user's RAs - limited to course level
1233 $base = "/" . SYSCONTEXTID;
1236 // Replace $context with the target context we will
1237 // load. Normally, this will be a course context, but
1238 // may be a different top-level context.
1240 // We have 3 cases
1242 // - Course
1243 // - BLOCK/PERSON/USER/COURSE(sitecourse) hanging from SYSTEM
1244 // - BLOCK/MODULE/GROUP hanging from a course
1246 // For course contexts, we _already_ have the RAs
1247 // but the cost of re-fetching is minimal so we don't care.
1249 if ($context->contextlevel !== CONTEXT_COURSE
1250 && $context->path !== "$base/{$context->id}") {
1251 // Case BLOCK/MODULE/GROUP hanging from a course
1252 // Assumption: the course _must_ be our parent
1253 // If we ever see stuff nested further this needs to
1254 // change to do 1 query over the exploded path to
1255 // find out which one is the course
1256 $courses = explode('/',get_course_from_path($context->path));
1257 $targetid = array_pop($courses);
1258 $context = get_context_instance_by_id($targetid);
1263 // Role assignments in the context and below
1265 $sql = "SELECT ctx.path, ra.roleid
1266 FROM {$CFG->prefix}role_assignments ra
1267 JOIN {$CFG->prefix}context ctx
1268 ON ra.contextid=ctx.id
1269 WHERE ra.userid = $userid
1270 AND (ctx.path = '{$context->path}' OR ctx.path LIKE '{$context->path}/%')
1271 ORDER BY ctx.depth, ctx.path";
1272 $rs = get_recordset_sql($sql);
1275 // Read in the RAs
1277 $localroles = array();
1278 while ($ra = rs_fetch_next_record($rs)) {
1279 if (!isset($accessdata['ra'][$ra->path])) {
1280 $accessdata['ra'][$ra->path] = array();
1282 array_push($accessdata['ra'][$ra->path], $ra->roleid);
1283 array_push($localroles, $ra->roleid);
1285 rs_close($rs);
1288 // Walk up and down the tree to grab all the roledefs
1289 // of interest to our user...
1291 // NOTES
1292 // - we use IN() but the number of roles is very limited.
1294 $courseroles = aggregate_roles_from_accessdata($context, $accessdata);
1296 // Do we have any interesting "local" roles?
1297 $localroles = array_diff($localroles,$courseroles); // only "new" local roles
1298 $wherelocalroles='';
1299 if (count($localroles)) {
1300 // Role defs for local roles in 'higher' contexts...
1301 $contexts = substr($context->path, 1); // kill leading slash
1302 $contexts = str_replace('/', ',', $contexts);
1303 $localroleids = implode(',',$localroles);
1304 $wherelocalroles="OR (rc.roleid IN ({$localroleids})
1305 AND ctx.id IN ($contexts))" ;
1308 // We will want overrides for all of them
1309 $whereroles = '';
1310 if ($roleids = implode(',',array_merge($courseroles,$localroles))) {
1311 $whereroles = "rc.roleid IN ($roleids) AND";
1313 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1314 FROM {$CFG->prefix}role_capabilities rc
1315 JOIN {$CFG->prefix}context ctx
1316 ON rc.contextid=ctx.id
1317 WHERE ($whereroles
1318 (ctx.id={$context->id} OR ctx.path LIKE '{$context->path}/%'))
1319 $wherelocalroles
1320 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1322 $newrdefs = array();
1323 if ($rs = get_recordset_sql($sql)) {
1324 while ($rd = rs_fetch_next_record($rs)) {
1325 $k = "{$rd->path}:{$rd->roleid}";
1326 if (!array_key_exists($k, $newrdefs)) {
1327 $newrdefs[$k] = array();
1329 $newrdefs[$k][$rd->capability] = $rd->permission;
1331 rs_close($rs);
1332 } else {
1333 debugging('Bad SQL encountered!');
1336 compact_rdefs($newrdefs);
1337 foreach ($newrdefs as $key=>$value) {
1338 $accessdata['rdef'][$key] =& $newrdefs[$key];
1341 // error_log("loaded {$context->path}");
1342 $accessdata['loaded'][] = $context->path;
1346 * It add to the access ctrl array the data
1347 * needed by a role for a given context.
1349 * The data is added in the rdef key.
1351 * This role-centric function is useful for role_switching
1352 * and to get an overview of what a role gets under a
1353 * given context and below...
1355 * @param $roleid integer - the id of the user
1356 * @param $context context obj - needs path!
1357 * @param $accessdata accessdata array
1360 function get_role_access_bycontext($roleid, $context, $accessdata=NULL) {
1362 global $CFG;
1364 /* Get the relevant rolecaps into rdef
1365 * - relevant role caps
1366 * - at ctx and above
1367 * - below this ctx
1370 if (is_null($accessdata)) {
1371 $accessdata = array(); // named list
1372 $accessdata['ra'] = array();
1373 $accessdata['rdef'] = array();
1374 $accessdata['loaded'] = array();
1377 $contexts = substr($context->path, 1); // kill leading slash
1378 $contexts = str_replace('/', ',', $contexts);
1381 // Walk up and down the tree to grab all the roledefs
1382 // of interest to our role...
1384 // NOTE: we use an IN clauses here - which
1385 // might explode on huge sites with very convoluted nesting of
1386 // categories... - extremely unlikely that the number of nested
1387 // categories is so large that we hit the limits of IN()
1389 $sql = "SELECT ctx.path, rc.capability, rc.permission
1390 FROM {$CFG->prefix}role_capabilities rc
1391 JOIN {$CFG->prefix}context ctx
1392 ON rc.contextid=ctx.id
1393 WHERE rc.roleid=$roleid AND
1394 ( ctx.id IN ($contexts) OR
1395 ctx.path LIKE '{$context->path}/%' )
1396 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1398 $rs = get_recordset_sql($sql);
1399 while ($rd = rs_fetch_next_record($rs)) {
1400 $k = "{$rd->path}:{$roleid}";
1401 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1403 rs_close($rs);
1405 return $accessdata;
1409 * Load accessdata for a user
1410 * into the $ACCESS global
1412 * Used by has_capability() - but feel free
1413 * to call it if you are about to run a BIG
1414 * cron run across a bazillion users.
1417 function load_user_accessdata($userid) {
1418 global $ACCESS,$CFG;
1420 $base = '/'.SYSCONTEXTID;
1422 $accessdata = get_user_access_sitewide($userid);
1423 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1425 // provide "default role" & set 'dr'
1427 if (!empty($CFG->defaultuserroleid)) {
1428 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1429 if (!isset($accessdata['ra'][$base])) {
1430 $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
1431 } else {
1432 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
1434 $accessdata['dr'] = $CFG->defaultuserroleid;
1438 // provide "default frontpage role"
1440 if (!empty($CFG->defaultfrontpageroleid)) {
1441 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1442 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1443 if (!isset($accessdata['ra'][$base])) {
1444 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
1445 } else {
1446 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
1449 // for dirty timestamps in cron
1450 $accessdata['time'] = time();
1452 $ACCESS[$userid] = $accessdata;
1453 compact_rdefs($ACCESS[$userid]['rdef']);
1455 return true;
1459 * Use shared copy of role definistions stored in $RDEFS;
1460 * @param array $rdefs array of role definitions in contexts
1462 function compact_rdefs(&$rdefs) {
1463 global $RDEFS;
1466 * This is a basic sharing only, we could also
1467 * use md5 sums of values. The main purpose is to
1468 * reduce mem in cron jobs - many users in $ACCESS array.
1471 foreach ($rdefs as $key => $value) {
1472 if (!array_key_exists($key, $RDEFS)) {
1473 $RDEFS[$key] = $rdefs[$key];
1475 $rdefs[$key] =& $RDEFS[$key];
1480 * A convenience function to completely load all the capabilities
1481 * for the current user. This is what gets called from complete_user_login()
1482 * for example. Call it only _after_ you've setup $USER and called
1483 * check_enrolment_plugins();
1486 function load_all_capabilities() {
1487 global $USER, $CFG, $DIRTYCONTEXTS;
1489 $base = '/'.SYSCONTEXTID;
1491 if (isguestuser()) {
1492 $guest = get_guest_role();
1494 // Load the rdefs
1495 $USER->access = get_role_access($guest->id);
1496 // Put the ghost enrolment in place...
1497 $USER->access['ra'][$base] = array($guest->id);
1500 } else if (isloggedin()) {
1502 $accessdata = get_user_access_sitewide($USER->id);
1505 // provide "default role" & set 'dr'
1507 if (!empty($CFG->defaultuserroleid)) {
1508 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1509 if (!isset($accessdata['ra'][$base])) {
1510 $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
1511 } else {
1512 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
1514 $accessdata['dr'] = $CFG->defaultuserroleid;
1517 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1520 // provide "default frontpage role"
1522 if (!empty($CFG->defaultfrontpageroleid)) {
1523 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1524 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1525 if (!isset($accessdata['ra'][$base])) {
1526 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
1527 } else {
1528 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
1531 $USER->access = $accessdata;
1533 } else if (!empty($CFG->notloggedinroleid)) {
1534 $USER->access = get_role_access($CFG->notloggedinroleid);
1535 $USER->access['ra'][$base] = array($CFG->notloggedinroleid);
1538 // Timestamp to read dirty context timestamps later
1539 $USER->access['time'] = time();
1540 $DIRTYCONTEXTS = array();
1542 // Clear to force a refresh
1543 unset($USER->mycourses);
1547 * A convenience function to completely reload all the capabilities
1548 * for the current user when roles have been updated in a relevant
1549 * context -- but PRESERVING switchroles and loginas.
1551 * That is - completely transparent to the user.
1553 * Note: rewrites $USER->access completely.
1556 function reload_all_capabilities() {
1557 global $USER,$CFG;
1559 // error_log("reloading");
1560 // copy switchroles
1561 $sw = array();
1562 if (isset($USER->access['rsw'])) {
1563 $sw = $USER->access['rsw'];
1564 // error_log(print_r($sw,1));
1567 unset($USER->access);
1568 unset($USER->mycourses);
1570 load_all_capabilities();
1572 foreach ($sw as $path => $roleid) {
1573 $context = get_record('context', 'path', $path);
1574 role_switch($roleid, $context);
1580 * Adds a temp role to an accessdata array.
1582 * Useful for the "temporary guest" access
1583 * we grant to logged-in users.
1585 * Note - assumes a course context!
1588 function load_temp_role($context, $roleid, $accessdata) {
1590 global $CFG;
1593 // Load rdefs for the role in -
1594 // - this context
1595 // - all the parents
1596 // - and below - IOWs overrides...
1599 // turn the path into a list of context ids
1600 $contexts = substr($context->path, 1); // kill leading slash
1601 $contexts = str_replace('/', ',', $contexts);
1603 $sql = "SELECT ctx.path,
1604 rc.capability, rc.permission
1605 FROM {$CFG->prefix}context ctx
1606 JOIN {$CFG->prefix}role_capabilities rc
1607 ON rc.contextid=ctx.id
1608 WHERE (ctx.id IN ($contexts)
1609 OR ctx.path LIKE '{$context->path}/%')
1610 AND rc.roleid = {$roleid}
1611 ORDER BY ctx.depth, ctx.path";
1612 $rs = get_recordset_sql($sql);
1613 while ($rd = rs_fetch_next_record($rs)) {
1614 $k = "{$rd->path}:{$roleid}";
1615 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1617 rs_close($rs);
1620 // Say we loaded everything for the course context
1621 // - which we just did - if the user gets a proper
1622 // RA in this session, this data will need to be reloaded,
1623 // but that is handled by the complete accessdata reload
1625 array_push($accessdata['loaded'], $context->path);
1628 // Add the ghost RA
1630 if (isset($accessdata['ra'][$context->path])) {
1631 array_push($accessdata['ra'][$context->path], $roleid);
1632 } else {
1633 $accessdata['ra'][$context->path] = array($roleid);
1636 return $accessdata;
1641 * Check all the login enrolment information for the given user object
1642 * by querying the enrolment plugins
1644 function check_enrolment_plugins(&$user) {
1645 global $CFG;
1647 static $inprogress; // To prevent this function being called more than once in an invocation
1649 if (!empty($inprogress[$user->id])) {
1650 return;
1653 $inprogress[$user->id] = true; // Set the flag
1655 require_once($CFG->dirroot .'/enrol/enrol.class.php');
1657 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
1658 $plugins = array($CFG->enrol);
1661 foreach ($plugins as $plugin) {
1662 $enrol = enrolment_factory::factory($plugin);
1663 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1664 $enrol->setup_enrolments($user);
1665 } else { /// Run legacy enrolment methods
1666 if (method_exists($enrol, 'get_student_courses')) {
1667 $enrol->get_student_courses($user);
1669 if (method_exists($enrol, 'get_teacher_courses')) {
1670 $enrol->get_teacher_courses($user);
1673 /// deal with $user->students and $user->teachers stuff
1674 unset($user->student);
1675 unset($user->teacher);
1677 unset($enrol);
1680 unset($inprogress[$user->id]); // Unset the flag
1684 * Installs the roles system.
1685 * This function runs on a fresh install as well as on an upgrade from the old
1686 * hard-coded student/teacher/admin etc. roles to the new roles system.
1688 function moodle_install_roles() {
1690 global $CFG, $db;
1692 /// Create a system wide context for assignemnt.
1693 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
1696 /// Create default/legacy roles and capabilities.
1697 /// (1 legacy capability per legacy role at system level).
1699 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1700 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1701 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1702 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1703 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1704 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1705 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1706 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1707 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1708 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1709 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1710 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
1711 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1712 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
1714 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1716 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
1717 error('Could not assign moodle/site:doanything to the admin role');
1719 if (!update_capabilities()) {
1720 error('Had trouble upgrading the core capabilities for the Roles System');
1723 /// Look inside user_admin, user_creator, user_teachers, user_students and
1724 /// assign above new roles. If a user has both teacher and student role,
1725 /// only teacher role is assigned. The assignment should be system level.
1727 $dbtables = $db->MetaTables('TABLES');
1729 /// Set up the progress bar
1731 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1733 $totalcount = $progresscount = 0;
1734 foreach ($usertables as $usertable) {
1735 if (in_array($CFG->prefix.$usertable, $dbtables)) {
1736 $totalcount += count_records($usertable);
1740 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1742 /// Upgrade the admins.
1743 /// Sort using id ASC, first one is primary admin.
1745 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
1746 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
1747 while ($admin = rs_fetch_next_record($rs)) {
1748 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
1749 $progresscount++;
1750 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1752 rs_close($rs);
1754 } else {
1755 // This is a fresh install.
1759 /// Upgrade course creators.
1760 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
1761 if ($rs = get_recordset('user_coursecreators')) {
1762 while ($coursecreator = rs_fetch_next_record($rs)) {
1763 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
1764 $progresscount++;
1765 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1767 rs_close($rs);
1772 /// Upgrade editting teachers and non-editting teachers.
1773 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
1774 if ($rs = get_recordset('user_teachers')) {
1775 while ($teacher = rs_fetch_next_record($rs)) {
1777 // removed code here to ignore site level assignments
1778 // since the contexts are separated now
1780 // populate the user_lastaccess table
1781 $access = new object();
1782 $access->timeaccess = $teacher->timeaccess;
1783 $access->userid = $teacher->userid;
1784 $access->courseid = $teacher->course;
1785 insert_record('user_lastaccess', $access);
1787 // assign the default student role
1788 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
1789 // hidden teacher
1790 if ($teacher->authority == 0) {
1791 $hiddenteacher = 1;
1792 } else {
1793 $hiddenteacher = 0;
1796 if ($teacher->editall) { // editting teacher
1797 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id, $teacher->timestart, $teacher->timeend, $hiddenteacher, $teacher->enrol, $teacher->timemodified);
1798 } else {
1799 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id, $teacher->timestart, $teacher->timeend, $hiddenteacher, $teacher->enrol, $teacher->timemodified);
1801 $progresscount++;
1802 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1804 rs_close($rs);
1809 /// Upgrade students.
1810 if (in_array($CFG->prefix.'user_students', $dbtables)) {
1811 if ($rs = get_recordset('user_students')) {
1812 while ($student = rs_fetch_next_record($rs)) {
1814 // populate the user_lastaccess table
1815 $access = new object;
1816 $access->timeaccess = $student->timeaccess;
1817 $access->userid = $student->userid;
1818 $access->courseid = $student->course;
1819 insert_record('user_lastaccess', $access);
1821 // assign the default student role
1822 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
1823 role_assign($studentrole, $student->userid, 0, $coursecontext->id, $student->timestart, $student->timeend, 0, $student->enrol, $student->time);
1824 $progresscount++;
1825 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1827 rs_close($rs);
1832 /// Upgrade guest (only 1 entry).
1833 if ($guestuser = get_record('user', 'username', 'guest')) {
1834 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
1836 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1839 /// Insert the correct records for legacy roles
1840 allow_assign($adminrole, $adminrole);
1841 allow_assign($adminrole, $coursecreatorrole);
1842 allow_assign($adminrole, $noneditteacherrole);
1843 allow_assign($adminrole, $editteacherrole);
1844 allow_assign($adminrole, $studentrole);
1845 allow_assign($adminrole, $guestrole);
1847 allow_assign($coursecreatorrole, $noneditteacherrole);
1848 allow_assign($coursecreatorrole, $editteacherrole);
1849 allow_assign($coursecreatorrole, $studentrole);
1850 allow_assign($coursecreatorrole, $guestrole);
1852 allow_assign($editteacherrole, $noneditteacherrole);
1853 allow_assign($editteacherrole, $studentrole);
1854 allow_assign($editteacherrole, $guestrole);
1856 /// Set up default permissions for overrides
1857 allow_override($adminrole, $adminrole);
1858 allow_override($adminrole, $coursecreatorrole);
1859 allow_override($adminrole, $noneditteacherrole);
1860 allow_override($adminrole, $editteacherrole);
1861 allow_override($adminrole, $studentrole);
1862 allow_override($adminrole, $guestrole);
1863 allow_override($adminrole, $userrole);
1866 /// Delete the old user tables when we are done
1868 $tables = array('user_students', 'user_teachers', 'user_coursecreators', 'user_admins');
1869 foreach ($tables as $tablename) {
1870 $table = new XMLDBTable($tablename);
1871 if (table_exists($table)) {
1872 drop_table($table);
1878 * Returns array of all legacy roles.
1880 function get_legacy_roles() {
1881 return array(
1882 'admin' => 'moodle/legacy:admin',
1883 'coursecreator' => 'moodle/legacy:coursecreator',
1884 'editingteacher' => 'moodle/legacy:editingteacher',
1885 'teacher' => 'moodle/legacy:teacher',
1886 'student' => 'moodle/legacy:student',
1887 'guest' => 'moodle/legacy:guest',
1888 'user' => 'moodle/legacy:user'
1892 function get_legacy_type($roleid) {
1893 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1894 $legacyroles = get_legacy_roles();
1896 $result = '';
1897 foreach($legacyroles as $ltype=>$lcap) {
1898 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
1899 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
1900 //choose first selected legacy capability - reset the rest
1901 if (empty($result)) {
1902 $result = $ltype;
1903 } else {
1904 unassign_capability($lcap, $roleid);
1909 return $result;
1913 * Assign the defaults found in this capabality definition to roles that have
1914 * the corresponding legacy capabilities assigned to them.
1915 * @param $legacyperms - an array in the format (example):
1916 * 'guest' => CAP_PREVENT,
1917 * 'student' => CAP_ALLOW,
1918 * 'teacher' => CAP_ALLOW,
1919 * 'editingteacher' => CAP_ALLOW,
1920 * 'coursecreator' => CAP_ALLOW,
1921 * 'admin' => CAP_ALLOW
1922 * @return boolean - success or failure.
1924 function assign_legacy_capabilities($capability, $legacyperms) {
1926 $legacyroles = get_legacy_roles();
1928 foreach ($legacyperms as $type => $perm) {
1930 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1932 if (!array_key_exists($type, $legacyroles)) {
1933 error('Incorrect legacy role definition for type: '.$type);
1936 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW)) {
1937 foreach ($roles as $role) {
1938 // Assign a site level capability.
1939 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1940 return false;
1945 return true;
1950 * Checks to see if a capability is a legacy capability.
1951 * @param $capabilityname
1952 * @return boolean
1954 function islegacy($capabilityname) {
1955 if (strpos($capabilityname, 'moodle/legacy') === 0) {
1956 return true;
1957 } else {
1958 return false;
1964 /**********************************
1965 * Context Manipulation functions *
1966 **********************************/
1969 * Create a new context record for use by all roles-related stuff
1970 * assumes that the caller has done the homework.
1972 * @param $level
1973 * @param $instanceid
1975 * @return object newly created context
1977 function create_context($contextlevel, $instanceid) {
1979 global $CFG;
1981 if ($contextlevel == CONTEXT_SYSTEM) {
1982 return create_system_context();
1985 $context = new object();
1986 $context->contextlevel = $contextlevel;
1987 $context->instanceid = $instanceid;
1989 // Define $context->path based on the parent
1990 // context. In other words... Who is your daddy?
1991 $basepath = '/' . SYSCONTEXTID;
1992 $basedepth = 1;
1994 $result = true;
1996 switch ($contextlevel) {
1997 case CONTEXT_COURSECAT:
1998 $sql = "SELECT ctx.path, ctx.depth
1999 FROM {$CFG->prefix}context ctx
2000 JOIN {$CFG->prefix}course_categories cc
2001 ON (cc.parent=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
2002 WHERE cc.id={$instanceid}";
2003 if ($p = get_record_sql($sql)) {
2004 $basepath = $p->path;
2005 $basedepth = $p->depth;
2006 } else if ($category = get_record('course_categories', 'id', $instanceid)) {
2007 if (empty($category->parent)) {
2008 // ok - this is a top category
2009 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $category->parent)) {
2010 $basepath = $parent->path;
2011 $basedepth = $parent->depth;
2012 } else {
2013 // wrong parent category - no big deal, this can be fixed later
2014 $basepath = null;
2015 $basedepth = 0;
2017 } else {
2018 // incorrect category id
2019 $result = false;
2021 break;
2023 case CONTEXT_COURSE:
2024 $sql = "SELECT ctx.path, ctx.depth
2025 FROM {$CFG->prefix}context ctx
2026 JOIN {$CFG->prefix}course c
2027 ON (c.category=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
2028 WHERE c.id={$instanceid} AND c.id !=" . SITEID;
2029 if ($p = get_record_sql($sql)) {
2030 $basepath = $p->path;
2031 $basedepth = $p->depth;
2032 } else if ($course = get_record('course', 'id', $instanceid)) {
2033 if ($course->id == SITEID) {
2034 //ok - no parent category
2035 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
2036 $basepath = $parent->path;
2037 $basedepth = $parent->depth;
2038 } else {
2039 // wrong parent category of course - no big deal, this can be fixed later
2040 $basepath = null;
2041 $basedepth = 0;
2043 } else if ($instanceid == SITEID) {
2044 // no errors for missing site course during installation
2045 return false;
2046 } else {
2047 // incorrect course id
2048 $result = false;
2050 break;
2052 case CONTEXT_MODULE:
2053 $sql = "SELECT ctx.path, ctx.depth
2054 FROM {$CFG->prefix}context ctx
2055 JOIN {$CFG->prefix}course_modules cm
2056 ON (cm.course=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
2057 WHERE cm.id={$instanceid}";
2058 if ($p = get_record_sql($sql)) {
2059 $basepath = $p->path;
2060 $basedepth = $p->depth;
2061 } else if ($cm = get_record('course_modules', 'id', $instanceid)) {
2062 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
2063 $basepath = $parent->path;
2064 $basedepth = $parent->depth;
2065 } else {
2066 // course does not exist - modules can not exist without a course
2067 $result = false;
2069 } else {
2070 // cm does not exist
2071 $result = false;
2073 break;
2075 case CONTEXT_BLOCK:
2076 // Only non-pinned & course-page based
2077 $sql = "SELECT ctx.path, ctx.depth
2078 FROM {$CFG->prefix}context ctx
2079 JOIN {$CFG->prefix}block_instance bi
2080 ON (bi.pageid=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
2081 WHERE bi.id={$instanceid} AND bi.pagetype='course-view'";
2082 if ($p = get_record_sql($sql)) {
2083 $basepath = $p->path;
2084 $basedepth = $p->depth;
2085 } else if ($bi = get_record('block_instance', 'id', $instanceid)) {
2086 if ($bi->pagetype != 'course-view') {
2087 // ok - not a course block
2088 } else if ($parent = get_context_instance(CONTEXT_COURSE, $bi->pageid)) {
2089 $basepath = $parent->path;
2090 $basedepth = $parent->depth;
2091 } else {
2092 // parent course does not exist - course blocks can not exist without a course
2093 $result = false;
2095 } else {
2096 // block does not exist
2097 $result = false;
2099 break;
2100 case CONTEXT_USER:
2101 // default to basepath
2102 break;
2105 // if grandparents unknown, maybe rebuild_context_path() will solve it later
2106 if ($basedepth != 0) {
2107 $context->depth = $basedepth+1;
2110 if ($result and $id = insert_record('context', $context)) {
2111 // can't set the full path till we know the id!
2112 if ($basedepth != 0 and !empty($basepath)) {
2113 set_field('context', 'path', $basepath.'/'. $id, 'id', $id);
2115 return get_context_instance_by_id($id);
2117 } else {
2118 debugging('Error: could not insert new context level "'.
2119 s($contextlevel).'", instance "'.
2120 s($instanceid).'".');
2121 return false;
2126 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
2128 function get_system_context($cache=true) {
2129 static $cached = null;
2130 if ($cache and defined('SYSCONTEXTID')) {
2131 if (is_null($cached)) {
2132 $cached = new object();
2133 $cached->id = SYSCONTEXTID;
2134 $cached->contextlevel = CONTEXT_SYSTEM;
2135 $cached->instanceid = 0;
2136 $cached->path = '/'.SYSCONTEXTID;
2137 $cached->depth = 1;
2139 return $cached;
2142 if (!$context = get_record('context', 'contextlevel', CONTEXT_SYSTEM)) {
2143 $context = new object();
2144 $context->contextlevel = CONTEXT_SYSTEM;
2145 $context->instanceid = 0;
2146 $context->depth = 1;
2147 $context->path = NULL; //not known before insert
2149 if (!$context->id = insert_record('context', $context)) {
2150 // better something than nothing - let's hope it will work somehow
2151 if (!defined('SYSCONTEXTID')) {
2152 define('SYSCONTEXTID', 1);
2154 debugging('Can not create system context');
2155 $context->id = SYSCONTEXTID;
2156 $context->path = '/'.SYSCONTEXTID;
2157 return $context;
2161 if (!isset($context->depth) or $context->depth != 1 or $context->instanceid != 0 or $context->path != '/'.$context->id) {
2162 $context->instanceid = 0;
2163 $context->path = '/'.$context->id;
2164 $context->depth = 1;
2165 update_record('context', $context);
2168 if (!defined('SYSCONTEXTID')) {
2169 define('SYSCONTEXTID', $context->id);
2172 $cached = $context;
2173 return $cached;
2177 * Remove a context record and any dependent entries,
2178 * removes context from static context cache too
2179 * @param $level
2180 * @param $instanceid
2182 * @return bool properly deleted
2184 function delete_context($contextlevel, $instanceid) {
2185 global $context_cache, $context_cache_id;
2187 // do not use get_context_instance(), because the related object might not exist,
2188 // or the context does not exist yet and it would be created now
2189 if ($context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instanceid)) {
2190 $result = delete_records('role_assignments', 'contextid', $context->id) &&
2191 delete_records('role_capabilities', 'contextid', $context->id) &&
2192 delete_records('context', 'id', $context->id);
2194 // do not mark dirty contexts if parents unknown
2195 if (!is_null($context->path) and $context->depth > 0) {
2196 mark_context_dirty($context->path);
2199 // purge static context cache if entry present
2200 unset($context_cache[$contextlevel][$instanceid]);
2201 unset($context_cache_id[$context->id]);
2203 return $result;
2204 } else {
2206 return true;
2211 * Precreates all contexts including all parents
2212 * @param int $contextlevel, empty means all
2213 * @param bool $buildpaths update paths and depths
2214 * @param bool $feedback show sql feedback
2215 * @return void
2217 function create_contexts($contextlevel=null, $buildpaths=true, $feedback=false) {
2218 global $CFG;
2220 //make sure system context exists
2221 $syscontext = get_system_context(false);
2223 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSECAT
2224 or $contextlevel == CONTEXT_COURSE
2225 or $contextlevel == CONTEXT_MODULE
2226 or $contextlevel == CONTEXT_BLOCK) {
2227 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2228 SELECT ".CONTEXT_COURSECAT.", cc.id
2229 FROM {$CFG->prefix}course_categories cc
2230 WHERE NOT EXISTS (SELECT 'x'
2231 FROM {$CFG->prefix}context cx
2232 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
2233 execute_sql($sql, $feedback);
2237 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSE
2238 or $contextlevel == CONTEXT_MODULE
2239 or $contextlevel == CONTEXT_BLOCK) {
2240 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2241 SELECT ".CONTEXT_COURSE.", c.id
2242 FROM {$CFG->prefix}course c
2243 WHERE NOT EXISTS (SELECT 'x'
2244 FROM {$CFG->prefix}context cx
2245 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
2246 execute_sql($sql, $feedback);
2250 if (empty($contextlevel) or $contextlevel == CONTEXT_MODULE) {
2251 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2252 SELECT ".CONTEXT_MODULE.", cm.id
2253 FROM {$CFG->prefix}course_modules cm
2254 WHERE NOT EXISTS (SELECT 'x'
2255 FROM {$CFG->prefix}context cx
2256 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
2257 execute_sql($sql, $feedback);
2260 if (empty($contextlevel) or $contextlevel == CONTEXT_BLOCK) {
2261 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2262 SELECT ".CONTEXT_BLOCK.", bi.id
2263 FROM {$CFG->prefix}block_instance bi
2264 WHERE NOT EXISTS (SELECT 'x'
2265 FROM {$CFG->prefix}context cx
2266 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
2267 execute_sql($sql, $feedback);
2270 if (empty($contextlevel) or $contextlevel == CONTEXT_USER) {
2271 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2272 SELECT ".CONTEXT_USER.", u.id
2273 FROM {$CFG->prefix}user u
2274 WHERE u.deleted=0
2275 AND NOT EXISTS (SELECT 'x'
2276 FROM {$CFG->prefix}context cx
2277 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
2278 execute_sql($sql, $feedback);
2282 if ($buildpaths) {
2283 build_context_path(false, $feedback);
2288 * Remove stale context records
2290 * @return bool
2292 function cleanup_contexts() {
2293 global $CFG;
2295 $sql = " SELECT c.contextlevel,
2296 c.instanceid AS instanceid
2297 FROM {$CFG->prefix}context c
2298 LEFT OUTER JOIN {$CFG->prefix}course_categories t
2299 ON c.instanceid = t.id
2300 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSECAT . "
2301 UNION
2302 SELECT c.contextlevel,
2303 c.instanceid
2304 FROM {$CFG->prefix}context c
2305 LEFT OUTER JOIN {$CFG->prefix}course t
2306 ON c.instanceid = t.id
2307 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSE . "
2308 UNION
2309 SELECT c.contextlevel,
2310 c.instanceid
2311 FROM {$CFG->prefix}context c
2312 LEFT OUTER JOIN {$CFG->prefix}course_modules t
2313 ON c.instanceid = t.id
2314 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_MODULE . "
2315 UNION
2316 SELECT c.contextlevel,
2317 c.instanceid
2318 FROM {$CFG->prefix}context c
2319 LEFT OUTER JOIN {$CFG->prefix}user t
2320 ON c.instanceid = t.id
2321 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_USER . "
2322 UNION
2323 SELECT c.contextlevel,
2324 c.instanceid
2325 FROM {$CFG->prefix}context c
2326 LEFT OUTER JOIN {$CFG->prefix}block_instance t
2327 ON c.instanceid = t.id
2328 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_BLOCK . "
2329 UNION
2330 SELECT c.contextlevel,
2331 c.instanceid
2332 FROM {$CFG->prefix}context c
2333 LEFT OUTER JOIN {$CFG->prefix}groups t
2334 ON c.instanceid = t.id
2335 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_GROUP . "
2337 if ($rs = get_recordset_sql($sql)) {
2338 begin_sql();
2339 $tx = true;
2340 while ($tx && $ctx = rs_fetch_next_record($rs)) {
2341 $tx = $tx && delete_context($ctx->contextlevel, $ctx->instanceid);
2343 rs_close($rs);
2344 if ($tx) {
2345 commit_sql();
2346 return true;
2348 rollback_sql();
2349 return false;
2350 rs_close($rs);
2352 return true;
2356 * Get the context instance as an object. This function will create the
2357 * context instance if it does not exist yet.
2358 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2359 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
2360 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
2361 * @return object The context object.
2363 function get_context_instance($contextlevel, $instance=0) {
2365 global $context_cache, $context_cache_id, $CFG;
2366 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_GROUP, CONTEXT_MODULE, CONTEXT_BLOCK);
2368 if ($contextlevel === 'clearcache') {
2369 // TODO: Remove for v2.0
2370 // No longer needed, but we'll catch it to avoid erroring out on custom code.
2371 // This used to be a fix for MDL-9016
2372 // "Restoring into existing course, deleting first
2373 // deletes context and doesn't recreate it"
2374 return false;
2377 /// System context has special cache
2378 if ($contextlevel == CONTEXT_SYSTEM) {
2379 return get_system_context();
2382 /// check allowed context levels
2383 if (!in_array($contextlevel, $allowed_contexts)) {
2384 // fatal error, code must be fixed - probably typo or switched parameters
2385 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
2388 if (!is_array($instance)) {
2389 /// Check the cache
2390 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2391 return $context_cache[$contextlevel][$instance];
2394 /// Get it from the database, or create it
2395 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
2396 $context = create_context($contextlevel, $instance);
2399 /// Only add to cache if context isn't empty.
2400 if (!empty($context)) {
2401 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
2402 $context_cache_id[$context->id] = $context; // Cache it for later
2405 return $context;
2409 /// ok, somebody wants to load several contexts to save some db queries ;-)
2410 $instances = $instance;
2411 $result = array();
2413 foreach ($instances as $key=>$instance) {
2414 /// Check the cache first
2415 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2416 $result[$instance] = $context_cache[$contextlevel][$instance];
2417 unset($instances[$key]);
2418 continue;
2422 if ($instances) {
2423 if (count($instances) > 1) {
2424 $instanceids = implode(',', $instances);
2425 $instanceids = "instanceid IN ($instanceids)";
2426 } else {
2427 $instance = reset($instances);
2428 $instanceids = "instanceid = $instance";
2431 if (!$contexts = get_records_sql("SELECT instanceid, id, contextlevel, path, depth
2432 FROM {$CFG->prefix}context
2433 WHERE contextlevel=$contextlevel AND $instanceids")) {
2434 $contexts = array();
2437 foreach ($instances as $instance) {
2438 if (isset($contexts[$instance])) {
2439 $context = $contexts[$instance];
2440 } else {
2441 $context = create_context($contextlevel, $instance);
2444 if (!empty($context)) {
2445 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
2446 $context_cache_id[$context->id] = $context; // Cache it for later
2449 $result[$instance] = $context;
2453 return $result;
2458 * Get a context instance as an object, from a given context id.
2459 * @param mixed $id a context id or array of ids.
2460 * @return mixed object or array of the context object.
2462 function get_context_instance_by_id($id) {
2464 global $context_cache, $context_cache_id;
2466 if ($id == SYSCONTEXTID) {
2467 return get_system_context();
2470 if (isset($context_cache_id[$id])) { // Already cached
2471 return $context_cache_id[$id];
2474 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
2475 $context_cache[$context->contextlevel][$context->instanceid] = $context;
2476 $context_cache_id[$context->id] = $context;
2477 return $context;
2480 return false;
2485 * Get the local override (if any) for a given capability in a role in a context
2486 * @param $roleid
2487 * @param $contextid
2488 * @param $capability
2490 function get_local_override($roleid, $contextid, $capability) {
2491 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
2496 /************************************
2497 * DB TABLE RELATED FUNCTIONS *
2498 ************************************/
2501 * function that creates a role
2502 * @param name - role name
2503 * @param shortname - role short name
2504 * @param description - role description
2505 * @param legacy - optional legacy capability
2506 * @return id or false
2508 function create_role($name, $shortname, $description, $legacy='') {
2510 // check for duplicate role name
2512 if ($role = get_record('role','name', $name)) {
2513 error('there is already a role with this name!');
2516 if ($role = get_record('role','shortname', $shortname)) {
2517 error('there is already a role with this shortname!');
2520 $role = new object();
2521 $role->name = $name;
2522 $role->shortname = $shortname;
2523 $role->description = $description;
2525 //find free sortorder number
2526 $role->sortorder = count_records('role');
2527 while (get_record('role','sortorder', $role->sortorder)) {
2528 $role->sortorder += 1;
2531 if (!$context = get_context_instance(CONTEXT_SYSTEM)) {
2532 return false;
2535 if ($id = insert_record('role', $role)) {
2536 if ($legacy) {
2537 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
2540 /// By default, users with role:manage at site level
2541 /// should be able to assign users to this new role, and override this new role's capabilities
2543 // find all admin roles
2544 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
2545 // foreach admin role
2546 foreach ($adminroles as $arole) {
2547 // write allow_assign and allow_overrid
2548 allow_assign($arole->id, $id);
2549 allow_override($arole->id, $id);
2553 return $id;
2554 } else {
2555 return false;
2561 * function that deletes a role and cleanups up after it
2562 * @param roleid - id of role to delete
2563 * @return success
2565 function delete_role($roleid) {
2566 global $CFG;
2567 $success = true;
2569 // mdl 10149, check if this is the last active admin role
2570 // if we make the admin role not deletable then this part can go
2572 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
2574 if ($role = get_record('role', 'id', $roleid)) {
2575 if (record_exists('role_capabilities', 'contextid', $systemcontext->id, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
2576 // deleting an admin role
2577 $status = false;
2578 if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext)) {
2579 foreach ($adminroles as $adminrole) {
2580 if ($adminrole->id != $roleid) {
2581 // some other admin role
2582 if (record_exists('role_assignments', 'roleid', $adminrole->id, 'contextid', $systemcontext->id)) {
2583 // found another admin role with at least 1 user assigned
2584 $status = true;
2585 break;
2590 if ($status !== true) {
2591 error ('You can not delete this role because there is no other admin roles with users assigned');
2596 // first unssign all users
2597 if (!role_unassign($roleid)) {
2598 debugging("Error while unassigning all users from role with ID $roleid!");
2599 $success = false;
2602 // cleanup all references to this role, ignore errors
2603 if ($success) {
2605 // MDL-10679 find all contexts where this role has an override
2606 $contexts = get_records_sql("SELECT contextid, contextid
2607 FROM {$CFG->prefix}role_capabilities
2608 WHERE roleid = $roleid");
2610 delete_records('role_capabilities', 'roleid', $roleid);
2612 delete_records('role_allow_assign', 'roleid', $roleid);
2613 delete_records('role_allow_assign', 'allowassign', $roleid);
2614 delete_records('role_allow_override', 'roleid', $roleid);
2615 delete_records('role_allow_override', 'allowoverride', $roleid);
2616 delete_records('role_names', 'roleid', $roleid);
2619 // finally delete the role itself
2620 // get this before the name is gone for logging
2621 $rolename = get_field('role', 'name', 'id', $roleid);
2623 if ($success and !delete_records('role', 'id', $roleid)) {
2624 debugging("Could not delete role record with ID $roleid!");
2625 $success = false;
2628 if ($success) {
2629 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '', $USER->id);
2632 return $success;
2636 * Function to write context specific overrides, or default capabilities.
2637 * @param module - string name
2638 * @param capability - string name
2639 * @param contextid - context id
2640 * @param roleid - role id
2641 * @param permission - int 1,-1 or -1000
2642 * should not be writing if permission is 0
2644 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2646 global $USER;
2648 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
2649 unassign_capability($capability, $roleid, $contextid);
2650 return true;
2653 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
2655 if ($existing and !$overwrite) { // We want to keep whatever is there already
2656 return true;
2659 $cap = new object;
2660 $cap->contextid = $contextid;
2661 $cap->roleid = $roleid;
2662 $cap->capability = $capability;
2663 $cap->permission = $permission;
2664 $cap->timemodified = time();
2665 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
2667 if ($existing) {
2668 $cap->id = $existing->id;
2669 return update_record('role_capabilities', $cap);
2670 } else {
2671 $c = get_record('context', 'id', $contextid);
2672 return insert_record('role_capabilities', $cap);
2677 * Unassign a capability from a role.
2678 * @param $roleid - the role id
2679 * @param $capability - the name of the capability
2680 * @return boolean - success or failure
2682 function unassign_capability($capability, $roleid, $contextid=NULL) {
2684 if (isset($contextid)) {
2685 // delete from context rel, if this is the last override in this context
2686 $status = delete_records('role_capabilities', 'capability', $capability,
2687 'roleid', $roleid, 'contextid', $contextid);
2688 } else {
2689 $status = delete_records('role_capabilities', 'capability', $capability,
2690 'roleid', $roleid);
2692 return $status;
2697 * Get the roles that have a given capability assigned to it. This function
2698 * does not resolve the actual permission of the capability. It just checks
2699 * for assignment only.
2700 * @param $capability - capability name (string)
2701 * @param $permission - optional, the permission defined for this capability
2702 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2703 * @return array or role objects
2705 function get_roles_with_capability($capability, $permission=NULL, $context='') {
2707 global $CFG;
2709 if ($context) {
2710 if ($contexts = get_parent_contexts($context)) {
2711 $listofcontexts = '('.implode(',', $contexts).')';
2712 } else {
2713 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2714 $listofcontexts = '('.$sitecontext->id.')'; // must be site
2716 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
2717 } else {
2718 $contextstr = '';
2721 $selectroles = "SELECT r.*
2722 FROM {$CFG->prefix}role r,
2723 {$CFG->prefix}role_capabilities rc
2724 WHERE rc.capability = '$capability'
2725 AND rc.roleid = r.id $contextstr";
2727 if (isset($permission)) {
2728 $selectroles .= " AND rc.permission = '$permission'";
2730 return get_records_sql($selectroles);
2735 * This function makes a role-assignment (a role for a user or group in a particular context)
2736 * @param $roleid - the role of the id
2737 * @param $userid - userid
2738 * @param $groupid - group id
2739 * @param $contextid - id of the context
2740 * @param $timestart - time this assignment becomes effective
2741 * @param $timeend - time this assignemnt ceases to be effective
2742 * @uses $USER
2743 * @return id - new id of the assigment
2745 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
2746 global $USER, $CFG;
2748 /// Do some data validation
2750 if (empty($roleid)) {
2751 debugging('Role ID not provided');
2752 return false;
2755 if (empty($userid) && empty($groupid)) {
2756 debugging('Either userid or groupid must be provided');
2757 return false;
2760 if ($userid && !record_exists('user', 'id', $userid)) {
2761 debugging('User ID '.intval($userid).' does not exist!');
2762 return false;
2765 if ($groupid && !groups_group_exists($groupid)) {
2766 debugging('Group ID '.intval($groupid).' does not exist!');
2767 return false;
2770 if (!$context = get_context_instance_by_id($contextid)) {
2771 debugging('Context ID '.intval($contextid).' does not exist!');
2772 return false;
2775 if (($timestart and $timeend) and ($timestart > $timeend)) {
2776 debugging('The end time can not be earlier than the start time');
2777 return false;
2780 if (!$timemodified) {
2781 $timemodified = time();
2784 /// Check for existing entry
2785 if ($userid) {
2786 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
2787 } else {
2788 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
2791 if (empty($ra)) { // Create a new entry
2792 $ra = new object();
2793 $ra->roleid = $roleid;
2794 $ra->contextid = $context->id;
2795 $ra->userid = $userid;
2796 $ra->hidden = $hidden;
2797 $ra->enrol = $enrol;
2798 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2799 /// by repeating queries with the same exact parameters in a 100 secs time window
2800 $ra->timestart = round($timestart, -2);
2801 $ra->timeend = $timeend;
2802 $ra->timemodified = $timemodified;
2803 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
2805 if (!$ra->id = insert_record('role_assignments', $ra)) {
2806 return false;
2809 } else { // We already have one, just update it
2810 $ra->id = $ra->id;
2811 $ra->hidden = $hidden;
2812 $ra->enrol = $enrol;
2813 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2814 /// by repeating queries with the same exact parameters in a 100 secs time window
2815 $ra->timestart = round($timestart, -2);
2816 $ra->timeend = $timeend;
2817 $ra->timemodified = $timemodified;
2818 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
2820 if (!update_record('role_assignments', $ra)) {
2821 return false;
2825 /// mark context as dirty - modules might use has_capability() in xxx_role_assing()
2826 /// again expensive, but needed
2827 mark_context_dirty($context->path);
2829 if (!empty($USER->id) && $USER->id == $userid) {
2830 /// If the user is the current user, then do full reload of capabilities too.
2831 load_all_capabilities();
2834 /// Ask all the modules if anything needs to be done for this user
2835 if ($mods = get_list_of_plugins('mod')) {
2836 foreach ($mods as $mod) {
2837 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2838 $functionname = $mod.'_role_assign';
2839 if (function_exists($functionname)) {
2840 $functionname($userid, $context, $roleid);
2845 /// now handle metacourse role assignments if in course context
2846 if ($context->contextlevel == CONTEXT_COURSE) {
2847 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2848 foreach ($parents as $parent) {
2849 sync_metacourse($parent->parent_course);
2854 events_trigger('role_assigned', $ra);
2856 return true;
2861 * Deletes one or more role assignments. You must specify at least one parameter.
2862 * @param $roleid
2863 * @param $userid
2864 * @param $groupid
2865 * @param $contextid
2866 * @param $enrol unassign only if enrolment type matches, NULL means anything
2867 * @return boolean - success or failure
2869 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
2870 global $USER, $CFG;
2871 require_once($CFG->dirroot.'/group/lib.php');
2873 $success = true;
2875 $args = array('roleid', 'userid', 'groupid', 'contextid');
2876 $select = array();
2877 foreach ($args as $arg) {
2878 if ($$arg) {
2879 $select[] = $arg.' = '.$$arg;
2882 if (!empty($enrol)) {
2883 $select[] = "enrol='$enrol'";
2886 if ($select) {
2887 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2888 $mods = get_list_of_plugins('mod');
2889 foreach($ras as $ra) {
2890 $fireevent = false;
2891 /// infinite loop protection when deleting recursively
2892 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
2893 continue;
2895 if (delete_records('role_assignments', 'id', $ra->id)) {
2896 $fireevent = true;
2897 } else {
2898 $success = false;
2901 if (!$context = get_context_instance_by_id($ra->contextid)) {
2902 // strange error, not much to do
2903 continue;
2906 /* mark contexts as dirty here, because we need the refreshed
2907 * caps bellow to delete group membership and user_lastaccess!
2908 * and yes, this is very expensive for bulk operations :-(
2910 mark_context_dirty($context->path);
2912 /// If the user is the current user, then do full reload of capabilities too.
2913 if (!empty($USER->id) && $USER->id == $ra->userid) {
2914 load_all_capabilities();
2917 /// Ask all the modules if anything needs to be done for this user
2918 foreach ($mods as $mod) {
2919 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2920 $functionname = $mod.'_role_unassign';
2921 if (function_exists($functionname)) {
2922 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
2926 /// now handle metacourse role unassigment and removing from goups if in course context
2927 if ($context->contextlevel == CONTEXT_COURSE) {
2929 // cleanup leftover course groups/subscriptions etc when user has
2930 // no capability to view course
2931 // this may be slow, but this is the proper way of doing it
2932 if (!has_capability('moodle/course:view', $context, $ra->userid)) {
2933 // remove from groups
2934 groups_delete_group_members($context->instanceid, $ra->userid);
2936 // delete lastaccess records
2937 delete_records('user_lastaccess', 'userid', $ra->userid, 'courseid', $context->instanceid);
2940 //unassign roles in metacourses if needed
2941 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2942 foreach ($parents as $parent) {
2943 sync_metacourse($parent->parent_course);
2948 if ($fireevent) {
2949 events_trigger('role_unassigned', $ra);
2955 return $success;
2959 * A convenience function to take care of the common case where you
2960 * just want to enrol someone using the default role into a course
2962 * @param object $course
2963 * @param object $user
2964 * @param string $enrol - the plugin used to do this enrolment
2966 function enrol_into_course($course, $user, $enrol) {
2968 $timestart = time();
2969 // remove time part from the timestamp and keep only the date part
2970 $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
2971 if ($course->enrolperiod) {
2972 $timeend = $timestart + $course->enrolperiod;
2973 } else {
2974 $timeend = 0;
2977 if ($role = get_default_course_role($course)) {
2979 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2981 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
2982 return false;
2985 // force accessdata refresh for users visiting this context...
2986 mark_context_dirty($context->path);
2988 email_welcome_message_to_user($course, $user);
2990 add_to_log($course->id, 'course', 'enrol',
2991 'view.php?id='.$course->id, $course->id);
2993 return true;
2996 return false;
3000 * Loads the capability definitions for the component (from file). If no
3001 * capabilities are defined for the component, we simply return an empty array.
3002 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3003 * @return array of capabilities
3005 function load_capability_def($component) {
3006 global $CFG;
3008 if ($component == 'moodle') {
3009 $defpath = $CFG->libdir.'/db/access.php';
3010 $varprefix = 'moodle';
3011 } else {
3012 $compparts = explode('/', $component);
3014 if ($compparts[0] == 'block') {
3015 // Blocks are an exception. Blocks directory is 'blocks', and not
3016 // 'block'. So we need to jump through hoops.
3017 $defpath = $CFG->dirroot.'/'.$compparts[0].
3018 's/'.$compparts[1].'/db/access.php';
3019 $varprefix = $compparts[0].'_'.$compparts[1];
3021 } else if ($compparts[0] == 'format') {
3022 // Similar to the above, course formats are 'format' while they
3023 // are stored in 'course/format'.
3024 $defpath = $CFG->dirroot.'/course/'.$component.'/db/access.php';
3025 $varprefix = $compparts[0].'_'.$compparts[1];
3027 } else if ($compparts[0] == 'gradeimport') {
3028 $defpath = $CFG->dirroot.'/grade/import/'.$compparts[1].'/db/access.php';
3029 $varprefix = $compparts[0].'_'.$compparts[1];
3031 } else if ($compparts[0] == 'gradeexport') {
3032 $defpath = $CFG->dirroot.'/grade/export/'.$compparts[1].'/db/access.php';
3033 $varprefix = $compparts[0].'_'.$compparts[1];
3035 } else if ($compparts[0] == 'gradereport') {
3036 $defpath = $CFG->dirroot.'/grade/report/'.$compparts[1].'/db/access.php';
3037 $varprefix = $compparts[0].'_'.$compparts[1];
3039 } else {
3040 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
3041 $varprefix = str_replace('/', '_', $component);
3044 $capabilities = array();
3046 if (file_exists($defpath)) {
3047 require($defpath);
3048 $capabilities = ${$varprefix.'_capabilities'};
3050 return $capabilities;
3055 * Gets the capabilities that have been cached in the database for this
3056 * component.
3057 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3058 * @return array of capabilities
3060 function get_cached_capabilities($component='moodle') {
3061 if ($component == 'moodle') {
3062 $storedcaps = get_records_select('capabilities',
3063 "name LIKE 'moodle/%:%'");
3064 } else if ($component == 'local') {
3065 $storedcaps = get_records_select('capabilities',
3066 "name LIKE 'moodle/local:%'");
3067 } else {
3068 $storedcaps = get_records_select('capabilities',
3069 "name LIKE '$component:%'");
3071 return $storedcaps;
3075 * Returns default capabilities for given legacy role type.
3077 * @param string legacy role name
3078 * @return array
3080 function get_default_capabilities($legacyrole) {
3081 if (!$allcaps = get_records('capabilities')) {
3082 error('Error: no capabilitites defined!');
3084 $alldefs = array();
3085 $defaults = array();
3086 $components = array();
3087 foreach ($allcaps as $cap) {
3088 if (!in_array($cap->component, $components)) {
3089 $components[] = $cap->component;
3090 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
3093 foreach($alldefs as $name=>$def) {
3094 if (isset($def['legacy'][$legacyrole])) {
3095 $defaults[$name] = $def['legacy'][$legacyrole];
3099 //some exceptions
3100 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW;
3101 if ($legacyrole == 'admin') {
3102 $defaults['moodle/site:doanything'] = CAP_ALLOW;
3104 return $defaults;
3108 * Reset role capabilitites to default according to selected legacy capability.
3109 * If several legacy caps selected, use the first from get_default_capabilities.
3110 * If no legacy selected, removes all capabilities.
3112 * @param int @roleid
3114 function reset_role_capabilities($roleid) {
3115 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
3116 $legacyroles = get_legacy_roles();
3118 $defaultcaps = array();
3119 foreach($legacyroles as $ltype=>$lcap) {
3120 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
3121 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
3122 //choose first selected legacy capability
3123 $defaultcaps = get_default_capabilities($ltype);
3124 break;
3128 delete_records('role_capabilities', 'roleid', $roleid);
3129 if (!empty($defaultcaps)) {
3130 foreach($defaultcaps as $cap=>$permission) {
3131 assign_capability($cap, $permission, $roleid, $sitecontext->id);
3137 * Updates the capabilities table with the component capability definitions.
3138 * If no parameters are given, the function updates the core moodle
3139 * capabilities.
3141 * Note that the absence of the db/access.php capabilities definition file
3142 * will cause any stored capabilities for the component to be removed from
3143 * the database.
3145 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3146 * @return boolean
3148 function update_capabilities($component='moodle') {
3150 $storedcaps = array();
3152 $filecaps = load_capability_def($component);
3153 $cachedcaps = get_cached_capabilities($component);
3154 if ($cachedcaps) {
3155 foreach ($cachedcaps as $cachedcap) {
3156 array_push($storedcaps, $cachedcap->name);
3157 // update risk bitmasks and context levels in existing capabilities if needed
3158 if (array_key_exists($cachedcap->name, $filecaps)) {
3159 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
3160 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
3162 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
3163 $updatecap = new object();
3164 $updatecap->id = $cachedcap->id;
3165 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
3166 if (!update_record('capabilities', $updatecap)) {
3167 return false;
3171 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
3172 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
3174 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
3175 $updatecap = new object();
3176 $updatecap->id = $cachedcap->id;
3177 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
3178 if (!update_record('capabilities', $updatecap)) {
3179 return false;
3186 // Are there new capabilities in the file definition?
3187 $newcaps = array();
3189 foreach ($filecaps as $filecap => $def) {
3190 if (!$storedcaps ||
3191 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
3192 if (!array_key_exists('riskbitmask', $def)) {
3193 $def['riskbitmask'] = 0; // no risk if not specified
3195 $newcaps[$filecap] = $def;
3198 // Add new capabilities to the stored definition.
3199 foreach ($newcaps as $capname => $capdef) {
3200 $capability = new object;
3201 $capability->name = $capname;
3202 $capability->captype = $capdef['captype'];
3203 $capability->contextlevel = $capdef['contextlevel'];
3204 $capability->component = $component;
3205 $capability->riskbitmask = $capdef['riskbitmask'];
3207 if (!insert_record('capabilities', $capability, false, 'id')) {
3208 return false;
3212 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
3213 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
3214 foreach ($rolecapabilities as $rolecapability){
3215 //assign_capability will update rather than insert if capability exists
3216 if (!assign_capability($capname, $rolecapability->permission,
3217 $rolecapability->roleid, $rolecapability->contextid, true)){
3218 notify('Could not clone capabilities for '.$capname);
3222 // Do we need to assign the new capabilities to roles that have the
3223 // legacy capabilities moodle/legacy:* as well?
3224 // we ignore legacy key if we have cloned permissions
3225 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
3226 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
3227 notify('Could not assign legacy capabilities for '.$capname);
3230 // Are there any capabilities that have been removed from the file
3231 // definition that we need to delete from the stored capabilities and
3232 // role assignments?
3233 capabilities_cleanup($component, $filecaps);
3235 return true;
3240 * Deletes cached capabilities that are no longer needed by the component.
3241 * Also unassigns these capabilities from any roles that have them.
3242 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3243 * @param $newcapdef - array of the new capability definitions that will be
3244 * compared with the cached capabilities
3245 * @return int - number of deprecated capabilities that have been removed
3247 function capabilities_cleanup($component, $newcapdef=NULL) {
3249 $removedcount = 0;
3251 if ($cachedcaps = get_cached_capabilities($component)) {
3252 foreach ($cachedcaps as $cachedcap) {
3253 if (empty($newcapdef) ||
3254 array_key_exists($cachedcap->name, $newcapdef) === false) {
3256 // Remove from capabilities cache.
3257 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
3258 error('Could not delete deprecated capability '.$cachedcap->name);
3259 } else {
3260 $removedcount++;
3262 // Delete from roles.
3263 if($roles = get_roles_with_capability($cachedcap->name)) {
3264 foreach($roles as $role) {
3265 if (!unassign_capability($cachedcap->name, $role->id)) {
3266 error('Could not unassign deprecated capability '.
3267 $cachedcap->name.' from role '.$role->name);
3271 } // End if.
3274 return $removedcount;
3279 /****************
3280 * UI FUNCTIONS *
3281 ****************/
3285 * prints human readable context identifier.
3287 function print_context_name($context, $withprefix = true, $short = false) {
3289 $name = '';
3290 switch ($context->contextlevel) {
3292 case CONTEXT_SYSTEM: // by now it's a definite an inherit
3293 $name = get_string('coresystem');
3294 break;
3296 case CONTEXT_USER:
3297 if ($user = get_record('user', 'id', $context->instanceid)) {
3298 if ($withprefix){
3299 $name = get_string('user').': ';
3301 $name .= fullname($user);
3303 break;
3305 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
3306 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
3307 if ($withprefix){
3308 $name = get_string('category').': ';
3310 $name .=format_string($category->name);
3312 break;
3314 case CONTEXT_COURSE: // 1 to 1 to course cat
3315 if ($course = get_record('course', 'id', $context->instanceid)) {
3316 if ($withprefix){
3317 if ($context->instanceid == SITEID) {
3318 $name = get_string('site').': ';
3319 } else {
3320 $name = get_string('course').': ';
3323 if ($short){
3324 $name .=format_string($course->shortname);
3325 } else {
3326 $name .=format_string($course->fullname);
3330 break;
3332 case CONTEXT_GROUP: // 1 to 1 to course
3333 if ($name = groups_get_group_name($context->instanceid)) {
3334 if ($withprefix){
3335 $name = get_string('group').': '. $name;
3338 break;
3340 case CONTEXT_MODULE: // 1 to 1 to course
3341 if ($cm = get_record('course_modules','id',$context->instanceid)) {
3342 if ($module = get_record('modules','id',$cm->module)) {
3343 if ($mod = get_record($module->name, 'id', $cm->instance)) {
3344 if ($withprefix){
3345 $name = get_string('activitymodule').': ';
3347 $name .= $mod->name;
3351 break;
3353 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
3354 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
3355 if ($block = get_record('block','id',$blockinstance->blockid)) {
3356 global $CFG;
3357 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
3358 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
3359 $blockname = "block_$block->name";
3360 if ($blockobject = new $blockname()) {
3361 if ($withprefix){
3362 $name = get_string('block').': ';
3364 $name .= $blockobject->title;
3368 break;
3370 default:
3371 error ('This is an unknown context (' . $context->contextlevel . ') in print_context_name!');
3372 return false;
3375 return $name;
3380 * Extracts the relevant capabilities given a contextid.
3381 * All case based, example an instance of forum context.
3382 * Will fetch all forum related capabilities, while course contexts
3383 * Will fetch all capabilities
3384 * @param object context
3385 * @return array();
3387 * capabilities
3388 * `name` varchar(150) NOT NULL,
3389 * `captype` varchar(50) NOT NULL,
3390 * `contextlevel` int(10) NOT NULL,
3391 * `component` varchar(100) NOT NULL,
3393 function fetch_context_capabilities($context) {
3395 global $CFG;
3397 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
3399 switch ($context->contextlevel) {
3401 case CONTEXT_SYSTEM: // all
3402 $SQL = "select * from {$CFG->prefix}capabilities";
3403 break;
3405 case CONTEXT_USER:
3406 $SQL = "SELECT *
3407 FROM {$CFG->prefix}capabilities
3408 WHERE contextlevel = ".CONTEXT_USER;
3409 break;
3411 case CONTEXT_COURSECAT: // all
3412 $SQL = "select * from {$CFG->prefix}capabilities";
3413 break;
3415 case CONTEXT_COURSE: // all
3416 $SQL = "select * from {$CFG->prefix}capabilities";
3417 break;
3419 case CONTEXT_GROUP: // group caps
3420 break;
3422 case CONTEXT_MODULE: // mod caps
3423 $cm = get_record('course_modules', 'id', $context->instanceid);
3424 $module = get_record('modules', 'id', $cm->module);
3426 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
3427 and component = 'mod/$module->name'";
3428 break;
3430 case CONTEXT_BLOCK: // block caps
3431 $cb = get_record('block_instance', 'id', $context->instanceid);
3432 $block = get_record('block', 'id', $cb->blockid);
3434 $SQL = "select * from {$CFG->prefix}capabilities where (contextlevel = ".CONTEXT_BLOCK." AND component = 'moodle')
3435 OR (component = 'block/$block->name')";
3436 break;
3438 default:
3439 return false;
3442 if (!$records = get_records_sql($SQL.' '.$sort)) {
3443 $records = array();
3446 /// the rest of code is a bit hacky, think twice before modifying it :-(
3448 // special sorting of core system capabiltites and enrollments
3449 if (in_array($context->contextlevel, array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE))) {
3450 $first = array();
3451 foreach ($records as $key=>$record) {
3452 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
3453 $first[$key] = $record;
3454 unset($records[$key]);
3455 } else if (count($first)){
3456 break;
3459 if (count($first)) {
3460 $records = $first + $records; // merge the two arrays keeping the keys
3462 } else {
3463 $contextindependentcaps = fetch_context_independent_capabilities();
3464 $records = array_merge($contextindependentcaps, $records);
3467 return $records;
3473 * Gets the context-independent capabilities that should be overrridable in
3474 * any context.
3475 * @return array of capability records from the capabilities table.
3477 function fetch_context_independent_capabilities() {
3479 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
3480 $contextindependentcaps = array(
3481 'moodle/site:accessallgroups'
3484 $records = array();
3486 foreach ($contextindependentcaps as $capname) {
3487 $record = get_record('capabilities', 'name', $capname);
3488 array_push($records, $record);
3490 return $records;
3495 * This function pulls out all the resolved capabilities (overrides and
3496 * defaults) of a role used in capability overrides in contexts at a given
3497 * context.
3498 * @param obj $context
3499 * @param int $roleid
3500 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
3501 * @return array
3503 function role_context_capabilities($roleid, $context, $cap='') {
3504 global $CFG;
3506 $contexts = get_parent_contexts($context);
3507 $contexts[] = $context->id;
3508 $contexts = '('.implode(',', $contexts).')';
3510 if ($cap) {
3511 $search = " AND rc.capability = '$cap' ";
3512 } else {
3513 $search = '';
3516 $SQL = "SELECT rc.*
3517 FROM {$CFG->prefix}role_capabilities rc,
3518 {$CFG->prefix}context c
3519 WHERE rc.contextid in $contexts
3520 AND rc.roleid = $roleid
3521 AND rc.contextid = c.id $search
3522 ORDER BY c.contextlevel DESC,
3523 rc.capability DESC";
3525 $capabilities = array();
3527 if ($records = get_records_sql($SQL)) {
3528 // We are traversing via reverse order.
3529 foreach ($records as $record) {
3530 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3531 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
3532 $capabilities[$record->capability] = $record->permission;
3536 return $capabilities;
3540 * Recursive function which, given a context, find all parent context ids,
3541 * and return the array in reverse order, i.e. parent first, then grand
3542 * parent, etc.
3544 * @param object $context
3545 * @return array()
3547 function get_parent_contexts($context) {
3549 if ($context->path == '') {
3550 return array();
3553 $parentcontexts = substr($context->path, 1); // kill leading slash
3554 $parentcontexts = explode('/', $parentcontexts);
3555 array_pop($parentcontexts); // and remove its own id
3557 return array_reverse($parentcontexts);
3561 * Return the id of the parent of this context, or false if there is no parent (only happens if this
3562 * is the site context.)
3564 * @param object $context
3565 * @return integer the id of the parent context.
3567 function get_parent_contextid($context) {
3568 $parentcontexts = get_parent_contexts($context);
3569 if (count($parentcontexts) == 0) {
3570 return false;
3572 return array_shift($parentcontexts);
3576 * Recursive function which, given a context, find all its children context ids.
3578 * When called for a course context, it will return the modules and blocks
3579 * displayed in the course page.
3581 * For course category contexts it will return categories and courses. It will
3582 * NOT recurse into courses - if you want to do that, call it on the returned
3583 * courses.
3585 * If called on a course context it _will_ populate the cache with the appropriate
3586 * contexts ;-)
3588 * @param object $context.
3589 * @return array of child records
3591 function get_child_contexts($context) {
3593 global $CFG, $context_cache;
3595 // We *MUST* populate the context_cache as the callers
3596 // will probably ask for the full record anyway soon after
3597 // soon after calling us ;-)
3599 switch ($context->contextlevel) {
3601 case CONTEXT_BLOCK:
3602 // No children.
3603 return array();
3604 break;
3606 case CONTEXT_MODULE:
3607 // No children.
3608 return array();
3609 break;
3611 case CONTEXT_GROUP:
3612 // No children.
3613 return array();
3614 break;
3616 case CONTEXT_COURSE:
3617 // Find
3618 // - module instances - easy
3619 // - groups
3620 // - blocks assigned to the course-view page explicitly - easy
3621 // - blocks pinned (note! we get all of them here, regardless of vis)
3622 $sql = " SELECT ctx.*
3623 FROM {$CFG->prefix}context ctx
3624 WHERE ctx.path LIKE '{$context->path}/%'
3625 AND ctx.contextlevel IN (".CONTEXT_MODULE.",".CONTEXT_BLOCK.")
3626 UNION
3627 SELECT ctx.*
3628 FROM {$CFG->prefix}context ctx
3629 JOIN {$CFG->prefix}groups g
3630 ON (ctx.instanceid=g.id AND ctx.contextlevel=".CONTEXT_GROUP.")
3631 WHERE g.courseid={$context->instanceid}
3632 UNION
3633 SELECT ctx.*
3634 FROM {$CFG->prefix}context ctx
3635 JOIN {$CFG->prefix}block_pinned b
3636 ON (ctx.instanceid=b.blockid AND ctx.contextlevel=".CONTEXT_BLOCK.")
3637 WHERE b.pagetype='course-view'
3639 $rs = get_recordset_sql($sql);
3640 $records = array();
3641 while ($rec = rs_fetch_next_record($rs)) {
3642 $records[$rec->id] = $rec;
3643 $context_cache[$rec->contextlevel][$rec->instanceid] = $rec;
3645 rs_close($rs);
3646 return $records;
3647 break;
3649 case CONTEXT_COURSECAT:
3650 // Find
3651 // - categories
3652 // - courses
3653 $sql = " SELECT ctx.*
3654 FROM {$CFG->prefix}context ctx
3655 WHERE ctx.path LIKE '{$context->path}/%'
3656 AND ctx.contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.")
3658 $rs = get_recordset_sql($sql);
3659 $records = array();
3660 while ($rec = rs_fetch_next_record($rs)) {
3661 $records[$rec->id] = $rec;
3662 $context_cache[$rec->contextlevel][$rec->instanceid] = $rec;
3664 rs_close($rs);
3665 return $records;
3666 break;
3668 case CONTEXT_USER:
3669 // No children.
3670 return array();
3671 break;
3673 case CONTEXT_SYSTEM:
3674 // Just get all the contexts except for CONTEXT_SYSTEM level
3675 // and hope we don't OOM in the process - don't cache
3676 $sql = 'SELECT c.*'.
3677 'FROM '.$CFG->prefix.'context c '.
3678 'WHERE contextlevel != '.CONTEXT_SYSTEM;
3680 return get_records_sql($sql);
3681 break;
3683 default:
3684 error('This is an unknown context (' . $context->contextlevel . ') in get_child_contexts!');
3685 return false;
3691 * Gets a string for sql calls, searching for stuff in this context or above
3692 * @param object $context
3693 * @return string
3695 function get_related_contexts_string($context) {
3696 if ($parents = get_parent_contexts($context)) {
3697 return (' IN ('.$context->id.','.implode(',', $parents).')');
3698 } else {
3699 return (' ='.$context->id);
3704 * Returns the human-readable, translated version of the capability.
3705 * Basically a big switch statement.
3706 * @param $capabilityname - e.g. mod/choice:readresponses
3708 function get_capability_string($capabilityname) {
3710 // Typical capabilityname is mod/choice:readresponses
3712 $names = split('/', $capabilityname);
3713 $stringname = $names[1]; // choice:readresponses
3714 $components = split(':', $stringname);
3715 $componentname = $components[0]; // choice
3717 switch ($names[0]) {
3718 case 'mod':
3719 $string = get_string($stringname, $componentname);
3720 break;
3722 case 'block':
3723 $string = get_string($stringname, 'block_'.$componentname);
3724 break;
3726 case 'moodle':
3727 if ($componentname == 'local') {
3728 $string = get_string($stringname, 'local');
3729 } else {
3730 $string = get_string($stringname, 'role');
3732 break;
3734 case 'enrol':
3735 $string = get_string($stringname, 'enrol_'.$componentname);
3736 break;
3738 case 'format':
3739 $string = get_string($stringname, 'format_'.$componentname);
3740 break;
3742 case 'gradeexport':
3743 $string = get_string($stringname, 'gradeexport_'.$componentname);
3744 break;
3746 case 'gradeimport':
3747 $string = get_string($stringname, 'gradeimport_'.$componentname);
3748 break;
3750 case 'gradereport':
3751 $string = get_string($stringname, 'gradereport_'.$componentname);
3752 break;
3754 default:
3755 $string = get_string($stringname);
3756 break;
3759 return $string;
3764 * This gets the mod/block/course/core etc strings.
3765 * @param $component
3766 * @param $contextlevel
3768 function get_component_string($component, $contextlevel) {
3770 switch ($contextlevel) {
3772 case CONTEXT_SYSTEM:
3773 if (preg_match('|^enrol/|', $component)) {
3774 $langname = str_replace('/', '_', $component);
3775 $string = get_string('enrolname', $langname);
3776 } else if (preg_match('|^block/|', $component)) {
3777 $langname = str_replace('/', '_', $component);
3778 $string = get_string('blockname', $langname);
3779 } else if (preg_match('|^local|', $component)) {
3780 $langname = str_replace('/', '_', $component);
3781 $string = get_string('local');
3782 } else {
3783 $string = get_string('coresystem');
3785 break;
3787 case CONTEXT_USER:
3788 $string = get_string('users');
3789 break;
3791 case CONTEXT_COURSECAT:
3792 $string = get_string('categories');
3793 break;
3795 case CONTEXT_COURSE:
3796 if (preg_match('|^gradeimport/|', $component)
3797 || preg_match('|^gradeexport/|', $component)
3798 || preg_match('|^gradereport/|', $component)) {
3799 $string = get_string('gradebook', 'admin');
3800 } else {
3801 $string = get_string('course');
3803 break;
3805 case CONTEXT_GROUP:
3806 $string = get_string('group');
3807 break;
3809 case CONTEXT_MODULE:
3810 $string = get_string('modulename', basename($component));
3811 break;
3813 case CONTEXT_BLOCK:
3814 if( $component == 'moodle' ){
3815 $string = get_string('block');
3816 }else{
3817 $string = get_string('blockname', 'block_'.basename($component));
3819 break;
3821 default:
3822 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
3823 return false;
3826 return $string;
3830 * Gets the list of roles assigned to this context and up (parents)
3831 * @param object $context
3832 * @param view - set to true when roles are pulled for display only
3833 * this is so that we can filter roles with no visible
3834 * assignment, for example, you might want to "hide" all
3835 * course creators when browsing the course participants
3836 * list.
3837 * @return array
3839 function get_roles_used_in_context($context, $view = false) {
3841 global $CFG;
3843 // filter for roles with all hidden assignments
3844 // no need to return when only pulling roles for reviewing
3845 // e.g. participants page.
3846 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
3847 $contextlist = get_related_contexts_string($context);
3849 $sql = "SELECT DISTINCT r.id,
3850 r.name,
3851 r.shortname,
3852 r.sortorder
3853 FROM {$CFG->prefix}role_assignments ra,
3854 {$CFG->prefix}role r
3855 WHERE r.id = ra.roleid
3856 AND ra.contextid $contextlist
3857 $hiddensql
3858 ORDER BY r.sortorder ASC";
3860 return get_records_sql($sql);
3864 * This function is used to print roles column in user profile page.
3865 * @param int userid
3866 * @param object context
3867 * @return string
3869 function get_user_roles_in_context($userid, $context, $view=true){
3870 global $CFG, $USER;
3872 $rolestring = '';
3873 $SQL = 'select * from '.$CFG->prefix.'role_assignments ra, '.$CFG->prefix.'role r where ra.userid='.$userid.' and ra.contextid='.$context->id.' and ra.roleid = r.id';
3874 $rolenames = array();
3875 if ($roles = get_records_sql($SQL)) {
3876 foreach ($roles as $userrole) {
3877 // MDL-12544, if we are in view mode and current user has no capability to view hidden assignment, skip it
3878 if ($userrole->hidden && $view && !has_capability('moodle/role:viewhiddenassigns', $context)) {
3879 continue;
3881 $rolenames[$userrole->roleid] = $userrole->name;
3884 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
3886 foreach ($rolenames as $roleid => $rolename) {
3887 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
3889 $rolestring = implode(',', $rolenames);
3891 return $rolestring;
3896 * Checks if a user can override capabilities of a particular role in this context
3897 * @param object $context
3898 * @param int targetroleid - the id of the role you want to override
3899 * @return boolean
3901 function user_can_override($context, $targetroleid) {
3902 // first check if user has override capability
3903 // if not return false;
3904 if (!has_capability('moodle/role:override', $context)) {
3905 return false;
3907 // pull out all active roles of this user from this context(or above)
3908 if ($userroles = get_user_roles($context)) {
3909 foreach ($userroles as $userrole) {
3910 // if any in the role_allow_override table, then it's ok
3911 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
3912 return true;
3917 return false;
3922 * Checks if a user can assign users to a particular role in this context
3923 * @param object $context
3924 * @param int targetroleid - the id of the role you want to assign users to
3925 * @return boolean
3927 function user_can_assign($context, $targetroleid) {
3929 // first check if user has override capability
3930 // if not return false;
3931 if (!has_capability('moodle/role:assign', $context)) {
3932 return false;
3934 // pull out all active roles of this user from this context(or above)
3935 if ($userroles = get_user_roles($context)) {
3936 foreach ($userroles as $userrole) {
3937 // if any in the role_allow_override table, then it's ok
3938 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
3939 return true;
3944 return false;
3947 /** Returns all site roles in correct sort order.
3950 function get_all_roles() {
3951 return get_records('role', '', '', 'sortorder ASC');
3955 * gets all the user roles assigned in this context, or higher contexts
3956 * this is mainly used when checking if a user can assign a role, or overriding a role
3957 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3958 * allow_override tables
3959 * @param object $context
3960 * @param int $userid
3961 * @param view - set to true when roles are pulled for display only
3962 * this is so that we can filter roles with no visible
3963 * assignment, for example, you might want to "hide" all
3964 * course creators when browsing the course participants
3965 * list.
3966 * @return array
3968 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
3970 global $USER, $CFG, $db;
3972 if (empty($userid)) {
3973 if (empty($USER->id)) {
3974 return array();
3976 $userid = $USER->id;
3978 // set up hidden sql
3979 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
3981 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
3982 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id.')';
3983 } else {
3984 $contexts = ' ra.contextid = \''.$context->id.'\'';
3987 if (!$return = get_records_sql('SELECT ra.*, r.name, r.shortname
3988 FROM '.$CFG->prefix.'role_assignments ra,
3989 '.$CFG->prefix.'role r,
3990 '.$CFG->prefix.'context c
3991 WHERE ra.userid = '.$userid.'
3992 AND ra.roleid = r.id
3993 AND ra.contextid = c.id
3994 AND '.$contexts . $hiddensql .'
3995 ORDER BY '.$order)) {
3996 $return = array();
3999 return $return;
4003 * Creates a record in the allow_override table
4004 * @param int sroleid - source roleid
4005 * @param int troleid - target roleid
4006 * @return int - id or false
4008 function allow_override($sroleid, $troleid) {
4009 $record = new object();
4010 $record->roleid = $sroleid;
4011 $record->allowoverride = $troleid;
4012 return insert_record('role_allow_override', $record);
4016 * Creates a record in the allow_assign table
4017 * @param int sroleid - source roleid
4018 * @param int troleid - target roleid
4019 * @return int - id or false
4021 function allow_assign($sroleid, $troleid) {
4022 $record = new object;
4023 $record->roleid = $sroleid;
4024 $record->allowassign = $troleid;
4025 return insert_record('role_allow_assign', $record);
4029 * Gets a list of roles that this user can assign in this context
4030 * @param object $context
4031 * @param string $field
4032 * @return array
4034 function get_assignable_roles ($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS) {
4036 global $CFG;
4038 // this users RAs
4039 $ras = get_user_roles($context);
4040 $roleids = array();
4041 foreach ($ras as $ra) {
4042 $roleids[] = $ra->roleid;
4044 unset($ra);
4046 if (count($roleids)===0) {
4047 return array();
4050 $roleids = implode(',',$roleids);
4052 // The subselect scopes the DISTINCT down to
4053 // the role ids - a DISTINCT over the whole of
4054 // the role table is much more expensive on some DBs
4055 $sql = "SELECT r.id, r.$field
4056 FROM {$CFG->prefix}role r
4057 JOIN ( SELECT DISTINCT allowassign as allowedrole
4058 FROM {$CFG->prefix}role_allow_assign raa
4059 WHERE raa.roleid IN ($roleids) ) ar
4060 ON r.id=ar.allowedrole
4061 ORDER BY sortorder ASC";
4063 $rs = get_recordset_sql($sql);
4064 $roles = array();
4065 while ($r = rs_fetch_next_record($rs)) {
4066 $roles[$r->id] = $r->{$field};
4068 rs_close($rs);
4070 return role_fix_names($roles, $context, $rolenamedisplay);
4074 * Gets a list of roles that this user can assign in this context, for the switchrole menu
4076 * This is a quick-fix for MDL-13459 until MDL-8312 is sorted out...
4077 * @param object $context
4078 * @param string $field
4079 * @return array
4081 function get_assignable_roles_for_switchrole ($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS) {
4083 global $CFG;
4085 // this users RAs
4086 $ras = get_user_roles($context);
4087 $roleids = array();
4088 foreach ($ras as $ra) {
4089 $roleids[] = $ra->roleid;
4091 unset($ra);
4093 if (count($roleids)===0) {
4094 return array();
4097 $roleids = implode(',',$roleids);
4099 // The subselect scopes the DISTINCT down to
4100 // the role ids - a DISTINCT over the whole of
4101 // the role table is much more expensive on some DBs
4102 $sql = "SELECT r.id, r.$field
4103 FROM {$CFG->prefix}role r
4104 JOIN ( SELECT DISTINCT allowassign as allowedrole
4105 FROM {$CFG->prefix}role_allow_assign raa
4106 WHERE raa.roleid IN ($roleids) ) ar
4107 ON r.id=ar.allowedrole
4108 JOIN {$CFG->prefix}role_capabilities rc
4109 ON (r.id = rc.roleid AND rc.capability = 'moodle/course:view'
4110 AND rc.capability != 'moodle/site:doanything')
4111 ORDER BY sortorder ASC";
4113 $rs = get_recordset_sql($sql);
4114 $roles = array();
4115 while ($r = rs_fetch_next_record($rs)) {
4116 $roles[$r->id] = $r->{$field};
4118 rs_close($rs);
4120 return role_fix_names($roles, $context, $rolenamedisplay);
4124 * Gets a list of roles that this user can override in this context
4125 * @param object $context
4126 * @return array
4128 function get_overridable_roles($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS) {
4130 $options = array();
4132 if ($roles = get_all_roles()) {
4133 foreach ($roles as $role) {
4134 if (user_can_override($context, $role->id)) {
4135 $options[$role->id] = $role->$field;
4140 return role_fix_names($options, $context, $rolenamedisplay);
4144 * Returns a role object that is the default role for new enrolments
4145 * in a given course
4147 * @param object $course
4148 * @return object $role
4150 function get_default_course_role($course) {
4151 global $CFG;
4153 /// First let's take the default role the course may have
4154 if (!empty($course->defaultrole)) {
4155 if ($role = get_record('role', 'id', $course->defaultrole)) {
4156 return $role;
4160 /// Otherwise the site setting should tell us
4161 if ($CFG->defaultcourseroleid) {
4162 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid)) {
4163 return $role;
4167 /// It's unlikely we'll get here, but just in case, try and find a student role
4168 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
4169 return array_shift($studentroles); /// Take the first one
4172 return NULL;
4177 * Who has this capability in this context?
4179 * This can be a very expensive call - use sparingly and keep
4180 * the results if you are going to need them again soon.
4182 * Note if $fields is empty this function attempts to get u.*
4183 * which can get rather large - and has a serious perf impact
4184 * on some DBs.
4186 * @param $context - object
4187 * @param $capability - string capability
4188 * @param $fields - fields to be pulled
4189 * @param $sort - the sort order
4190 * @param $limitfrom - number of records to skip (offset)
4191 * @param $limitnum - number of records to fetch
4192 * @param $groups - single group or array of groups - only return
4193 * users who are in one of these group(s).
4194 * @param $exceptions - list of users to exclude
4195 * @param view - set to true when roles are pulled for display only
4196 * this is so that we can filter roles with no visible
4197 * assignment, for example, you might want to "hide" all
4198 * course creators when browsing the course participants
4199 * list.
4200 * @param boolean $useviewallgroups if $groups is set the return users who
4201 * have capability both $capability and moodle/site:accessallgroups
4202 * in this context, as well as users who have $capability and who are
4203 * in $groups.
4205 function get_users_by_capability($context, $capability, $fields='', $sort='',
4206 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true,
4207 $view=false, $useviewallgroups=false) {
4208 global $CFG;
4210 $ctxids = substr($context->path, 1); // kill leading slash
4211 $ctxids = str_replace('/', ',', $ctxids);
4213 // Context is the frontpage
4214 $isfrontpage = false;
4215 $iscoursepage = false; // coursepage other than fp
4216 if ($context->contextlevel == CONTEXT_COURSE) {
4217 if ($context->instanceid == SITEID) {
4218 $isfrontpage = true;
4219 } else {
4220 $iscoursepage = true;
4224 // What roles/rolecaps are interesting?
4225 $caps = "'$capability'";
4226 if ($doanything===true) {
4227 $caps.=",'moodle/site:doanything'";
4228 $doanything_join='';
4229 $doanything_cond='';
4230 } else {
4231 // This is an outer join against
4232 // admin-ish roleids. Any row that succeeds
4233 // in JOINing here ends up removed from
4234 // the resultset. This means we remove
4235 // rolecaps from roles that also have
4236 // 'doanything' capabilities.
4237 $doanything_join="LEFT OUTER JOIN (
4238 SELECT DISTINCT rc.roleid
4239 FROM {$CFG->prefix}role_capabilities rc
4240 WHERE rc.capability='moodle/site:doanything'
4241 AND rc.permission=".CAP_ALLOW."
4242 AND rc.contextid IN ($ctxids)
4243 ) dar
4244 ON rc.roleid=dar.roleid";
4245 $doanything_cond="AND dar.roleid IS NULL";
4248 // fetch all capability records - we'll walk several
4249 // times over them, and should be a small set
4251 $negperm = false; // has any negative (<0) permission?
4252 $roleids = array();
4254 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability,
4255 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
4256 FROM {$CFG->prefix}role_capabilities rc
4257 JOIN {$CFG->prefix}context ctx on rc.contextid = ctx.id
4258 $doanything_join
4259 WHERE rc.capability IN ($caps) AND ctx.id IN ($ctxids)
4260 $doanything_cond
4261 ORDER BY rc.roleid ASC, ctx.depth ASC";
4262 if ($capdefs = get_records_sql($sql)) {
4263 foreach ($capdefs AS $rcid=>$rc) {
4264 $roleids[] = (int)$rc->roleid;
4265 if ($rc->permission < 0) {
4266 $negperm = true;
4271 $roleids = array_unique($roleids);
4273 if (count($roleids)===0) { // noone here!
4274 return false;
4277 // is the default role interesting? does it have
4278 // a relevant rolecap? (we use this a lot later)
4279 if (in_array((int)$CFG->defaultuserroleid, $roleids, true)) {
4280 $defaultroleinteresting = true;
4281 } else {
4282 $defaultroleinteresting = false;
4286 // Prepare query clauses
4288 $wherecond = array();
4289 /// Groups
4290 if ($groups) {
4291 if (is_array($groups)) {
4292 $grouptest = 'gm.groupid IN (' . implode(',', $groups) . ')';
4293 } else {
4294 $grouptest = 'gm.groupid = ' . $groups;
4296 $grouptest = 'ra.userid IN (SELECT userid FROM ' .
4297 $CFG->prefix . 'groups_members gm WHERE ' . $grouptest . ')';
4299 if ($useviewallgroups) {
4300 $viewallgroupsusers = get_users_by_capability($context,
4301 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
4302 $wherecond['groups'] = '('. $grouptest . ' OR ra.userid IN (' .
4303 implode(',', array_keys($viewallgroupsusers)) . '))';
4304 } else {
4305 $wherecond['groups'] = '(' . $grouptest .')';
4309 /// User exceptions
4310 if (!empty($exceptions)) {
4311 $wherecond['userexceptions'] = ' u.id NOT IN ('.$exceptions.')';
4314 /// Set up hidden role-assignments sql
4315 if ($view && !has_capability('moodle/role:viewhiddenassigns', $context)) {
4316 $condhiddenra = 'AND ra.hidden = 0 ';
4317 $sscondhiddenra = 'AND ssra.hidden = 0 ';
4318 } else {
4319 $condhiddenra = '';
4320 $sscondhiddenra = '';
4323 // Collect WHERE conditions
4324 $where = implode(' AND ', array_values($wherecond));
4325 if ($where != '') {
4326 $where = 'WHERE ' . $where;
4329 /// Set up default fields
4330 if (empty($fields)) {
4331 if ($iscoursepage) {
4332 $fields = 'u.*, ul.timeaccess as lastaccess';
4333 } else {
4334 $fields = 'u.*';
4338 /// Set up default sort
4339 if (empty($sort)) { // default to course lastaccess or just lastaccess
4340 if ($iscoursepage) {
4341 $sort = 'ul.timeaccess';
4342 } else {
4343 $sort = 'u.lastaccess';
4346 $sortby = $sort ? " ORDER BY $sort " : '';
4348 // User lastaccess JOIN
4349 if ((strpos($sort, 'ul.timeaccess') === FALSE) and (strpos($fields, 'ul.timeaccess') === FALSE)) { // user_lastaccess is not required MDL-13810
4350 $uljoin = '';
4351 } else {
4352 $uljoin = "LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul
4353 ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
4357 // Simple cases - No negative permissions means we can take shortcuts
4359 if (!$negperm) {
4361 // at the frontpage, and all site users have it - easy!
4362 if ($isfrontpage && !empty($CFG->defaultfrontpageroleid)
4363 && in_array((int)$CFG->defaultfrontpageroleid, $roleids, true)) {
4365 return get_records_sql("SELECT $fields
4366 FROM {$CFG->prefix}user u
4367 ORDER BY $sort",
4368 $limitfrom, $limitnum);
4371 // all site users have it, anyway
4372 // TODO: NOT ALWAYS! Check this case because this gets run for cases like this:
4373 // 1) Default role has the permission for a module thing like mod/choice:choose
4374 // 2) We are checking for an activity module context in a course
4375 // 3) Thus all users are returned even though course:view is also required
4376 if ($defaultroleinteresting) {
4377 $sql = "SELECT $fields
4378 FROM {$CFG->prefix}user u
4379 $uljoin
4380 $where
4381 ORDER BY $sort";
4382 return get_records_sql($sql, $limitfrom, $limitnum);
4385 /// Simple SQL assuming no negative rolecaps.
4386 /// We use a subselect to grab the role assignments
4387 /// ensuring only one row per user -- even if they
4388 /// have many "relevant" role assignments.
4389 $select = " SELECT $fields";
4390 $from = " FROM {$CFG->prefix}user u
4391 JOIN (SELECT DISTINCT ssra.userid
4392 FROM {$CFG->prefix}role_assignments ssra
4393 WHERE ssra.contextid IN ($ctxids)
4394 AND ssra.roleid IN (".implode(',',$roleids) .")
4395 $sscondhiddenra
4396 ) ra ON ra.userid = u.id
4397 $uljoin ";
4398 $where = " WHERE u.deleted = 0 ";
4399 if (count(array_keys($wherecond))) {
4400 $where .= ' AND ' . implode(' AND ', array_values($wherecond));
4402 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
4406 // If there are any negative rolecaps, we need to
4407 // work through a subselect that will bring several rows
4408 // per user (one per RA).
4409 // Since we cannot do the job in pure SQL (not without SQL stored
4410 // procedures anyway), we end up tied to processing the data in PHP
4411 // all the way down to pagination.
4413 // In some cases, this will mean bringing across a ton of data --
4414 // when paginating, we have to walk the permisisons of all the rows
4415 // in the _previous_ pages to get the pagination correct in the case
4416 // of users that end up not having the permission - this removed.
4419 // Prepare the role permissions datastructure for fast lookups
4420 $roleperms = array(); // each role cap and depth
4421 foreach ($capdefs AS $rcid=>$rc) {
4423 $rid = (int)$rc->roleid;
4424 $perm = (int)$rc->permission;
4425 $rcdepth = (int)$rc->ctxdepth;
4426 if (!isset($roleperms[$rc->capability][$rid])) {
4427 $roleperms[$rc->capability][$rid] = (object)array('perm' => $perm,
4428 'rcdepth' => $rcdepth);
4429 } else {
4430 if ($roleperms[$rc->capability][$rid]->perm == CAP_PROHIBIT) {
4431 continue;
4433 // override - as we are going
4434 // from general to local perms
4435 // (as per the ORDER BY...depth ASC above)
4436 // and local perms win...
4437 $roleperms[$rc->capability][$rid] = (object)array('perm' => $perm,
4438 'rcdepth' => $rcdepth);
4443 if ($context->contextlevel == CONTEXT_SYSTEM
4444 || $isfrontpage
4445 || $defaultroleinteresting) {
4447 // Handle system / sitecourse / defaultrole-with-perhaps-neg-overrides
4448 // with a SELECT FROM user LEFT OUTER JOIN against ra -
4449 // This is expensive on the SQL and PHP sides -
4450 // moves a ton of data across the wire.
4451 $ss = "SELECT u.id as userid, ra.roleid,
4452 ctx.depth
4453 FROM {$CFG->prefix}user u
4454 LEFT OUTER JOIN {$CFG->prefix}role_assignments ra
4455 ON (ra.userid = u.id
4456 AND ra.contextid IN ($ctxids)
4457 AND ra.roleid IN (".implode(',',$roleids) .")
4458 $condhiddenra)
4459 LEFT OUTER JOIN {$CFG->prefix}context ctx
4460 ON ra.contextid=ctx.id
4461 WHERE u.deleted=0";
4462 } else {
4463 // "Normal complex case" - the rolecaps we are after will
4464 // be defined in a role assignment somewhere.
4465 $ss = "SELECT ra.userid as userid, ra.roleid,
4466 ctx.depth
4467 FROM {$CFG->prefix}role_assignments ra
4468 JOIN {$CFG->prefix}context ctx
4469 ON ra.contextid=ctx.id
4470 WHERE ra.contextid IN ($ctxids)
4471 $condhiddenra
4472 AND ra.roleid IN (".implode(',',$roleids) .")";
4475 $select = "SELECT $fields ,ra.roleid, ra.depth ";
4476 $from = "FROM ($ss) ra
4477 JOIN {$CFG->prefix}user u
4478 ON ra.userid=u.id
4479 $uljoin ";
4480 $where = "WHERE u.deleted = 0 ";
4481 if (count(array_keys($wherecond))) {
4482 $where .= ' AND ' . implode(' AND ', array_values($wherecond));
4485 // Each user's entries MUST come clustered together
4486 // and RAs ordered in depth DESC - the role/cap resolution
4487 // code depends on this.
4488 $sort .= ' , ra.userid ASC, ra.depth DESC';
4489 $sortby .= ' , ra.userid ASC, ra.depth DESC ';
4491 $rs = get_recordset_sql($select.$from.$where.$sortby);
4494 // Process the user accounts+RAs, folding repeats together...
4496 // The processing for this recordset is tricky - to fold
4497 // the role/perms of users with multiple role-assignments
4498 // correctly while still processing one-row-at-a-time
4499 // we need to add a few additional 'private' fields to
4500 // the results array - so we can treat the rows as a
4501 // state machine to track the cap/perms and at what RA-depth
4502 // and RC-depth they were defined.
4504 // So what we do here is:
4505 // - loop over rows, checking pagination limits
4506 // - when we find a new user, if we are in the page add it to the
4507 // $results, and start building $ras array with its role-assignments
4508 // - when we are dealing with the next user, or are at the end of the userlist
4509 // (last rec or last in page), trigger the check-permission idiom
4510 // - the check permission idiom will
4511 // - add the default enrolment if needed
4512 // - call has_capability_from_rarc(), which based on RAs and RCs will return a bool
4513 // (should be fairly tight code ;-) )
4514 // - if the user has permission, all is good, just $c++ (counter)
4515 // - ...else, decrease the counter - so pagination is kept straight,
4516 // and (if we are in the page) remove from the results
4518 $results = array();
4520 // pagination controls
4521 $c = 0;
4522 $limitfrom = (int)$limitfrom;
4523 $limitnum = (int)$limitnum;
4526 // Track our last user id so we know when we are dealing
4527 // with a new user...
4529 $lastuserid = 0;
4531 // In this loop, we
4532 // $ras: role assignments, multidimensional array
4533 // treat as a stack - going from local to general
4534 // $ras = (( roleid=> x, $depth=>y) , ( roleid=> x, $depth=>y))
4536 while ($user = rs_fetch_next_record($rs)) {
4538 //error_log(" Record: " . print_r($user,1));
4541 // Pagination controls
4542 // Note that we might end up removing a user
4543 // that ends up _not_ having the rights,
4544 // therefore rolling back $c
4546 if ($lastuserid != $user->id) {
4548 // Did the last user end up with a positive permission?
4549 if ($lastuserid !=0) {
4550 if ($defaultroleinteresting) {
4551 // add the role at the end of $ras
4552 $ras[] = array( 'roleid' => $CFG->defaultuserroleid,
4553 'depth' => 1 );
4555 if (has_capability_from_rarc($ras, $roleperms, $capability, $doanything)) {
4556 $c++;
4557 } else {
4558 // remove the user from the result set,
4559 // only if we are 'in the page'
4560 if ($limitfrom === 0 || $c >= $limitfrom) {
4561 unset($results[$lastuserid]);
4566 // Did we hit pagination limit?
4567 if ($limitnum !==0 && $c >= ($limitfrom+$limitnum)) { // we are done!
4568 break;
4571 // New user setup, and $ras reset
4572 $lastuserid = $user->id;
4573 $ras = array();
4574 if (!empty($user->roleid)) {
4575 $ras[] = array( 'roleid' => (int)$user->roleid,
4576 'depth' => (int)$user->depth );
4579 // if we are 'in the page', also add the rec
4580 // to the results...
4581 if ($limitfrom === 0 || $c >= $limitfrom) {
4582 $results[$user->id] = $user; // trivial
4584 } else {
4585 // Additional RA for $lastuserid
4586 $ras[] = array( 'roleid'=>(int)$user->roleid,
4587 'depth'=>(int)$user->depth );
4590 } // end while(fetch)
4592 // Prune last entry if necessary
4593 if ($lastuserid !=0) {
4594 if ($defaultroleinteresting) {
4595 // add the role at the end of $ras
4596 $ras[] = array( 'roleid' => $CFG->defaultuserroleid,
4597 'depth' => 1 );
4599 if (!has_capability_from_rarc($ras, $roleperms, $capability, $doanything)) {
4600 // remove the user from the result set,
4601 // only if we are 'in the page'
4602 if ($limitfrom === 0 || $c >= $limitfrom) {
4603 if (isset($results[$lastuserid])) {
4604 unset($results[$lastuserid]);
4610 return $results;
4614 * Fast (fast!) utility function to resolve if a capability is granted,
4615 * based on Role Assignments and Role Capabilities.
4617 * Used (at least) by get_users_by_capability().
4619 * If PHP had fast built-in memoize functions, we could
4620 * add a $contextid parameter and memoize the return values.
4622 * @param array $ras - role assignments
4623 * @param array $roleperms - role permissions
4624 * @param string $capability - name of the capability
4625 * @param bool $doanything
4626 * @return boolean
4629 function has_capability_from_rarc($ras, $roleperms, $capability, $doanything) {
4630 // Mini-state machine, using $hascap
4631 // $hascap[ 'moodle/foo:bar' ]->perm = CAP_SOMETHING (numeric constant)
4632 // $hascap[ 'moodle/foo:bar' ]->radepth = depth of the role assignment that set it
4633 // $hascap[ 'moodle/foo:bar' ]->rcdepth = depth of the rolecap that set it
4634 // -- when resolving conflicts, we need to look into radepth first, if unresolved
4636 $caps = array($capability);
4637 if ($doanything) {
4638 $caps[] = 'moodle/site:candoanything';
4641 $hascap = array();
4644 // Compute which permission/roleassignment/rolecap
4645 // wins for each capability we are walking
4647 foreach ($ras as $ra) {
4648 foreach ($caps as $cap) {
4649 if (!isset($roleperms[$cap][$ra['roleid']])) {
4650 // nothing set for this cap - skip
4651 continue;
4653 // We explicitly clone here as we
4654 // add more properties to it
4655 // that must stay separate from the
4656 // original roleperm data structure
4657 $rp = clone($roleperms[$cap][$ra['roleid']]);
4658 $rp->radepth = $ra['depth'];
4660 // Trivial case, we are the first to set
4661 if (!isset($hascap[$cap])) {
4662 $hascap[$cap] = $rp;
4666 // Resolve who prevails, in order of precendence
4667 // - Prohibits always wins
4668 // - Locality of RA
4669 // - Locality of RC
4671 //// Prohibits...
4672 if ($rp->perm === CAP_PROHIBIT) {
4673 $hascap[$cap] = $rp;
4674 continue;
4676 if ($hascap[$cap]->perm === CAP_PROHIBIT) {
4677 continue;
4680 // Locality of RA - the look is ordered by depth DESC
4681 // so from local to general -
4682 // Higher RA loses to local RA... unless perm===0
4683 /// Thanks to the order of the records, $rp->radepth <= $hascap[$cap]->radepth
4684 if ($rp->radepth > $hascap[$cap]->radepth) {
4685 error_log('Should not happen @ ' . __FUNCTION__.':'.__LINE__);
4687 if ($rp->radepth < $hascap[$cap]->radepth) {
4688 if ($hascap[$cap]->perm!==0) {
4689 // Wider RA loses to local RAs...
4690 continue;
4691 } else {
4692 // "Higher RA resolves conflict" case,
4693 // local RAs had cancelled eachother
4694 $hascap[$cap] = $rp;
4695 continue;
4698 // Same ralevel - locality of RC wins
4699 if ($rp->rcdepth > $hascap[$cap]->rcdepth) {
4700 $hascap[$cap] = $rp;
4701 continue;
4703 if ($rp->rcdepth > $hascap[$cap]->rcdepth) {
4704 continue;
4706 // We match depth - add them
4707 $hascap[$cap]->perm += $rp->perm;
4710 if ($hascap[$capability]->perm > 0
4711 || ($doanything && isset($hascap['moodle/site:candoanything'])
4712 && $hascap['moodle/site:candoanything']->perm > 0)) {
4713 return true;
4715 return false;
4719 * Will re-sort a $users results array (from get_users_by_capability(), usually)
4720 * based on a sorting policy. This is to support the odd practice of
4721 * sorting teachers by 'authority', where authority was "lowest id of the role
4722 * assignment".
4724 * Will execute 1 database query. Only suitable for small numbers of users, as it
4725 * uses an u.id IN() clause.
4727 * Notes about the sorting criteria.
4729 * As a default, we cannot rely on role.sortorder because then
4730 * admins/coursecreators will always win. That is why the sane
4731 * rule "is locality matters most", with sortorder as 2nd
4732 * consideration.
4734 * If you want role.sortorder, use the 'sortorder' policy, and
4735 * name explicitly what roles you want to cover. It's probably
4736 * a good idea to see what roles have the capabilities you want
4737 * (array_diff() them against roiles that have 'can-do-anything'
4738 * to weed out admin-ish roles. Or fetch a list of roles from
4739 * variables like $CFG->coursemanagers .
4741 * @param array users Users' array, keyed on userid
4742 * @param object context
4743 * @param array roles - ids of the roles to include, optional
4744 * @param string policy - defaults to locality, more about
4745 * @return array - sorted copy of the array
4747 function sort_by_roleassignment_authority($users, $context, $roles=array(), $sortpolicy='locality') {
4748 global $CFG;
4750 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
4751 $contextwhere = ' ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
4752 if (empty($roles)) {
4753 $roleswhere = '';
4754 } else {
4755 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
4758 $sql = "SELECT ra.userid
4759 FROM {$CFG->prefix}role_assignments ra
4760 JOIN {$CFG->prefix}role r
4761 ON ra.roleid=r.id
4762 JOIN {$CFG->prefix}context ctx
4763 ON ra.contextid=ctx.id
4764 WHERE
4765 $userswhere
4766 AND $contextwhere
4767 $roleswhere
4770 // Default 'locality' policy -- read PHPDoc notes
4771 // about sort policies...
4772 $orderby = 'ORDER BY
4773 ctx.depth DESC, /* locality wins */
4774 r.sortorder ASC, /* rolesorting 2nd criteria */
4775 ra.id /* role assignment order tie-breaker */';
4776 if ($sortpolicy === 'sortorder') {
4777 $orderby = 'ORDER BY
4778 r.sortorder ASC, /* rolesorting 2nd criteria */
4779 ra.id /* role assignment order tie-breaker */';
4782 $sortedids = get_fieldset_sql($sql . $orderby);
4783 $sortedusers = array();
4784 $seen = array();
4786 foreach ($sortedids as $id) {
4787 // Avoid duplicates
4788 if (isset($seen[$id])) {
4789 continue;
4791 $seen[$id] = true;
4793 // assign
4794 $sortedusers[$id] = $users[$id];
4796 return $sortedusers;
4800 * gets all the users assigned this role in this context or higher
4801 * @param int roleid (can also be an array of ints!)
4802 * @param int contextid
4803 * @param bool parent if true, get list of users assigned in higher context too
4804 * @param string fields - fields from user (u.) , role assignment (ra) or role (r.)
4805 * @param string sort - sort from user (u.) , role assignment (ra) or role (r.)
4806 * @param bool gethidden - whether to fetch hidden enrolments too
4807 * @return array()
4809 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $gethidden=true, $group='', $limitfrom='', $limitnum='') {
4810 global $CFG;
4812 if (empty($fields)) {
4813 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
4814 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
4815 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4816 'u.emailstop, u.lang, u.timezone, r.name as rolename';
4819 // whether this assignment is hidden
4820 $hiddensql = $gethidden ? '': ' AND ra.hidden = 0 ';
4822 $parentcontexts = '';
4823 if ($parent) {
4824 $parentcontexts = substr($context->path, 1); // kill leading slash
4825 $parentcontexts = str_replace('/', ',', $parentcontexts);
4826 if ($parentcontexts !== '') {
4827 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4831 if (is_array($roleid)) {
4832 $roleselect = ' AND ra.roleid IN (' . implode(',',$roleid) .')';
4833 } elseif (!empty($roleid)) { // should not test for int, because it can come in as a string
4834 $roleselect = "AND ra.roleid = $roleid";
4835 } else {
4836 $roleselect = '';
4839 if ($group) {
4840 $groupjoin = "JOIN {$CFG->prefix}groups_members gm
4841 ON gm.userid = u.id";
4842 $groupselect = " AND gm.groupid = $group ";
4843 } else {
4844 $groupjoin = '';
4845 $groupselect = '';
4848 $SQL = "SELECT $fields, ra.roleid
4849 FROM {$CFG->prefix}role_assignments ra
4850 JOIN {$CFG->prefix}user u
4851 ON u.id = ra.userid
4852 JOIN {$CFG->prefix}role r
4853 ON ra.roleid = r.id
4854 $groupjoin
4855 WHERE (ra.contextid = $context->id $parentcontexts)
4856 $roleselect
4857 $groupselect
4858 $hiddensql
4859 ORDER BY $sort
4860 "; // join now so that we can just use fullname() later
4862 return get_records_sql($SQL, $limitfrom, $limitnum);
4866 * Counts all the users assigned this role in this context or higher
4867 * @param int roleid
4868 * @param int contextid
4869 * @param bool parent if true, get list of users assigned in higher context too
4870 * @return array()
4872 function count_role_users($roleid, $context, $parent=false) {
4873 global $CFG;
4875 if ($parent) {
4876 if ($contexts = get_parent_contexts($context)) {
4877 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4878 } else {
4879 $parentcontexts = '';
4881 } else {
4882 $parentcontexts = '';
4885 $SQL = "SELECT count(u.id)
4886 FROM {$CFG->prefix}role_assignments r
4887 JOIN {$CFG->prefix}user u
4888 ON u.id = r.userid
4889 WHERE (r.contextid = $context->id $parentcontexts)
4890 AND r.roleid = $roleid
4891 AND u.deleted = 0";
4893 return count_records_sql($SQL);
4897 * This function gets the list of courses that this user has a particular capability in.
4898 * It is still not very efficient.
4899 * @param string $capability Capability in question
4900 * @param int $userid User ID or null for current user
4901 * @param bool $doanything True if 'doanything' is permitted (default)
4902 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4903 * otherwise use a comma-separated list of the fields you require, not including id
4904 * @param string $orderby If set, use a comma-separated list of fields from course
4905 * table with sql modifiers (DESC) if needed
4906 * @return array Array of courses, may have zero entries. Or false if query failed.
4908 function get_user_capability_course($capability, $userid=NULL,$doanything=true,$fieldsexceptid='',$orderby='') {
4909 // Convert fields list and ordering
4910 $fieldlist='';
4911 if($fieldsexceptid) {
4912 $fields=explode(',',$fieldsexceptid);
4913 foreach($fields as $field) {
4914 $fieldlist.=',c.'.$field;
4917 if($orderby) {
4918 $fields=explode(',',$orderby);
4919 $orderby='';
4920 foreach($fields as $field) {
4921 if($orderby) {
4922 $orderby.=',';
4924 $orderby.='c.'.$field;
4926 $orderby='ORDER BY '.$orderby;
4929 // Obtain a list of everything relevant about all courses including context.
4930 // Note the result can be used directly as a context (we are going to), the course
4931 // fields are just appended.
4932 global $CFG;
4933 $rs=get_recordset_sql("
4934 SELECT
4935 x.*,c.id AS courseid$fieldlist
4936 FROM
4937 {$CFG->prefix}course c
4938 INNER JOIN {$CFG->prefix}context x ON c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE."
4939 $orderby
4941 if(!$rs) {
4942 return false;
4945 // Check capability for each course in turn
4946 $courses=array();
4947 while($coursecontext=rs_fetch_next_record($rs)) {
4948 if(has_capability($capability,$coursecontext,$userid,$doanything)) {
4949 // We've got the capability. Make the record look like a course record
4950 // and store it
4951 $coursecontext->id=$coursecontext->courseid;
4952 unset($coursecontext->courseid);
4953 unset($coursecontext->contextlevel);
4954 unset($coursecontext->instanceid);
4955 $courses[]=$coursecontext;
4958 return $courses;
4961 /** This function finds the roles assigned directly to this context only
4962 * i.e. no parents role
4963 * @param object $context
4964 * @return array
4966 function get_roles_on_exact_context($context) {
4968 global $CFG;
4970 return get_records_sql("SELECT r.*
4971 FROM {$CFG->prefix}role_assignments ra,
4972 {$CFG->prefix}role r
4973 WHERE ra.roleid = r.id
4974 AND ra.contextid = $context->id");
4979 * Switches the current user to another role for the current session and only
4980 * in the given context.
4982 * The caller *must* check
4983 * - that this op is allowed
4984 * - that the requested role can be assigned in this ctx
4985 * (hint, use get_assignable_roles())
4986 * - that the requested role is NOT $CFG->defaultuserroleid
4988 * To "unswitch" pass 0 as the roleid.
4990 * This function *will* modify $USER->access - beware
4992 * @param integer $roleid
4993 * @param object $context
4994 * @return bool
4996 function role_switch($roleid, $context) {
4997 global $USER, $CFG;
5000 // Plan of action
5002 // - Add the ghost RA to $USER->access
5003 // as $USER->access['rsw'][$path] = $roleid
5005 // - Make sure $USER->access['rdef'] has the roledefs
5006 // it needs to honour the switcheroo
5008 // Roledefs will get loaded "deep" here - down to the last child
5009 // context. Note that
5011 // - When visiting subcontexts, our selective accessdata loading
5012 // will still work fine - though those ra/rdefs will be ignored
5013 // appropriately while the switch is in place
5015 // - If a switcheroo happens at a category with tons of courses
5016 // (that have many overrides for switched-to role), the session
5017 // will get... quite large. Sometimes you just can't win.
5019 // To un-switch just unset($USER->access['rsw'][$path])
5022 // Add the switch RA
5023 if (!isset($USER->access['rsw'])) {
5024 $USER->access['rsw'] = array();
5027 if ($roleid == 0) {
5028 unset($USER->access['rsw'][$context->path]);
5029 if (empty($USER->access['rsw'])) {
5030 unset($USER->access['rsw']);
5032 return true;
5035 $USER->access['rsw'][$context->path]=$roleid;
5037 // Load roledefs
5038 $USER->access = get_role_access_bycontext($roleid, $context,
5039 $USER->access);
5041 /* DO WE NEED THIS AT ALL???
5042 // Add some permissions we are really going
5043 // to always need, even if the role doesn't have them!
5045 $USER->capabilities[$context->id]['moodle/course:view'] = CAP_ALLOW;
5048 return true;
5052 // get any role that has an override on exact context
5053 function get_roles_with_override_on_context($context) {
5055 global $CFG;
5057 return get_records_sql("SELECT r.*
5058 FROM {$CFG->prefix}role_capabilities rc,
5059 {$CFG->prefix}role r
5060 WHERE rc.roleid = r.id
5061 AND rc.contextid = $context->id");
5064 // get all capabilities for this role on this context (overrids)
5065 function get_capabilities_from_role_on_context($role, $context) {
5067 global $CFG;
5069 return get_records_sql("SELECT *
5070 FROM {$CFG->prefix}role_capabilities
5071 WHERE contextid = $context->id
5072 AND roleid = $role->id");
5075 // find out which roles has assignment on this context
5076 function get_roles_with_assignment_on_context($context) {
5078 global $CFG;
5080 return get_records_sql("SELECT r.*
5081 FROM {$CFG->prefix}role_assignments ra,
5082 {$CFG->prefix}role r
5083 WHERE ra.roleid = r.id
5084 AND ra.contextid = $context->id");
5090 * Find all user assignemnt of users for this role, on this context
5092 function get_users_from_role_on_context($role, $context) {
5094 global $CFG;
5096 return get_records_sql("SELECT *
5097 FROM {$CFG->prefix}role_assignments
5098 WHERE contextid = $context->id
5099 AND roleid = $role->id");
5103 * Simple function returning a boolean true if roles exist, otherwise false
5105 function user_has_role_assignment($userid, $roleid, $contextid=0) {
5107 if ($contextid) {
5108 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
5109 } else {
5110 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
5115 * Get role name or alias if exists and format the text.
5116 * @param object $role role object
5117 * @param object $coursecontext
5118 * @return $string name of role in course context
5120 function role_get_name($role, $coursecontext) {
5121 if ($r = get_record('role_names','roleid', $role->id,'contextid', $coursecontext->id)) {
5122 return strip_tags(format_string($r->name));
5123 } else {
5124 return strip_tags(format_string($role->name));
5129 * Prepare list of roles for display, apply aliases and format text
5130 * @param array $roleoptions array roleid=>rolename
5131 * @param object $context
5132 * @return array of role names
5134 function role_fix_names($roleoptions, $context, $rolenamedisplay=ROLENAME_ALIAS) {
5135 if ($rolenamedisplay != ROLENAME_ORIGINAL && !empty($context->id)) {
5136 if ($context->contextlevel == CONTEXT_MODULE || $context->contextlevel == CONTEXT_BLOCK) { // find the parent course context
5137 if ($parentcontextid = array_shift(get_parent_contexts($context))) {
5138 $context = get_context_instance_by_id($parentcontextid);
5141 if ($aliasnames = get_records('role_names', 'contextid', $context->id)) {
5142 if ($rolenamedisplay == ROLENAME_ALIAS) {
5143 foreach ($aliasnames as $alias) {
5144 if (isset($roleoptions[$alias->roleid])) {
5145 $roleoptions[$alias->roleid] = format_string($alias->name);
5148 } else if ($rolenamedisplay == ROLENAME_BOTH) {
5149 foreach ($aliasnames as $alias) {
5150 if (isset($roleoptions[$alias->roleid])) {
5151 $roleoptions[$alias->roleid] = format_string($alias->name).' ('.format_string($roleoptions[$alias->roleid]).')';
5157 foreach ($roleoptions as $rid => $name) {
5158 $roleoptions[$rid] = strip_tags($name);
5160 return $roleoptions;
5164 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
5165 * when we read in a new capability
5166 * most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
5167 * but when we are in grade, all reports/import/export capabilites should be together
5168 * @param string a - component string a
5169 * @param string b - component string b
5170 * @return bool - whether 2 component are in different "sections"
5172 function component_level_changed($cap, $comp, $contextlevel) {
5174 if ($cap->component == 'enrol/authorize' && $comp =='enrol/authorize') {
5175 return false;
5178 if (strstr($cap->component, '/') && strstr($comp, '/')) {
5179 $compsa = explode('/', $cap->component);
5180 $compsb = explode('/', $comp);
5184 // we are in gradebook, still
5185 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
5186 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
5187 return false;
5191 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
5195 * Populate context.path and context.depth where missing.
5196 * @param bool $force force a complete rebuild of the path and depth fields.
5197 * @param bool $feedback display feedback (during upgrade usually)
5198 * @return void
5200 function build_context_path($force=false, $feedback=false) {
5201 global $CFG;
5202 require_once($CFG->libdir.'/ddllib.php');
5204 // System context
5205 $sitectx = get_system_context(!$force);
5206 $base = '/'.$sitectx->id;
5208 // Sitecourse
5209 $sitecoursectx = get_record('context',
5210 'contextlevel', CONTEXT_COURSE,
5211 'instanceid', SITEID);
5212 if ($force || $sitecoursectx->path !== "$base/{$sitecoursectx->id}") {
5213 set_field('context', 'path', "$base/{$sitecoursectx->id}",
5214 'id', $sitecoursectx->id);
5215 set_field('context', 'depth', 2,
5216 'id', $sitecoursectx->id);
5217 $sitecoursectx = get_record('context',
5218 'contextlevel', CONTEXT_COURSE,
5219 'instanceid', SITEID);
5222 $ctxemptyclause = " AND (ctx.path IS NULL
5223 OR ctx.depth=0) ";
5224 $emptyclause = " AND ({$CFG->prefix}context.path IS NULL
5225 OR {$CFG->prefix}context.depth=0) ";
5226 if ($force) {
5227 $ctxemptyclause = $emptyclause = '';
5230 /* MDL-11347:
5231 * - mysql does not allow to use FROM in UPDATE statements
5232 * - using two tables after UPDATE works in mysql, but might give unexpected
5233 * results in pg 8 (depends on configuration)
5234 * - using table alias in UPDATE does not work in pg < 8.2
5236 if ($CFG->dbfamily == 'mysql') {
5237 $updatesql = "UPDATE {$CFG->prefix}context ct, {$CFG->prefix}context_temp temp
5238 SET ct.path = temp.path,
5239 ct.depth = temp.depth
5240 WHERE ct.id = temp.id";
5241 } else if ($CFG->dbfamily == 'oracle') {
5242 $updatesql = "UPDATE {$CFG->prefix}context ct
5243 SET (ct.path, ct.depth) =
5244 (SELECT temp.path, temp.depth
5245 FROM {$CFG->prefix}context_temp temp
5246 WHERE temp.id=ct.id)
5247 WHERE EXISTS (SELECT 'x'
5248 FROM {$CFG->prefix}context_temp temp
5249 WHERE temp.id = ct.id)";
5250 } else {
5251 $updatesql = "UPDATE {$CFG->prefix}context
5252 SET path = temp.path,
5253 depth = temp.depth
5254 FROM {$CFG->prefix}context_temp temp
5255 WHERE temp.id={$CFG->prefix}context.id";
5258 $udelsql = "TRUNCATE TABLE {$CFG->prefix}context_temp";
5260 // Top level categories
5261 $sql = "UPDATE {$CFG->prefix}context
5262 SET depth=2, path=" . sql_concat("'$base/'", 'id') . "
5263 WHERE contextlevel=".CONTEXT_COURSECAT."
5264 AND EXISTS (SELECT 'x'
5265 FROM {$CFG->prefix}course_categories cc
5266 WHERE cc.id = {$CFG->prefix}context.instanceid
5267 AND cc.depth=1)
5268 $emptyclause";
5270 execute_sql($sql, $feedback);
5272 execute_sql($udelsql, $feedback);
5274 // Deeper categories - one query per depthlevel
5275 $maxdepth = get_field_sql("SELECT MAX(depth)
5276 FROM {$CFG->prefix}course_categories");
5277 for ($n=2;$n<=$maxdepth;$n++) {
5278 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5279 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", $n+1
5280 FROM {$CFG->prefix}context ctx
5281 JOIN {$CFG->prefix}course_categories c ON ctx.instanceid=c.id
5282 JOIN {$CFG->prefix}context pctx ON c.parent=pctx.instanceid
5283 WHERE ctx.contextlevel=".CONTEXT_COURSECAT."
5284 AND pctx.contextlevel=".CONTEXT_COURSECAT."
5285 AND c.depth=$n
5286 AND NOT EXISTS (SELECT 'x'
5287 FROM {$CFG->prefix}context_temp temp
5288 WHERE temp.id = ctx.id)
5289 $ctxemptyclause";
5290 execute_sql($sql, $feedback);
5292 // this is needed after every loop
5293 // MDL-11532
5294 execute_sql($updatesql, $feedback);
5295 execute_sql($udelsql, $feedback);
5298 // Courses -- except sitecourse
5299 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5300 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5301 FROM {$CFG->prefix}context ctx
5302 JOIN {$CFG->prefix}course c ON ctx.instanceid=c.id
5303 JOIN {$CFG->prefix}context pctx ON c.category=pctx.instanceid
5304 WHERE ctx.contextlevel=".CONTEXT_COURSE."
5305 AND c.id!=".SITEID."
5306 AND pctx.contextlevel=".CONTEXT_COURSECAT."
5307 AND NOT EXISTS (SELECT 'x'
5308 FROM {$CFG->prefix}context_temp temp
5309 WHERE temp.id = ctx.id)
5310 $ctxemptyclause";
5311 execute_sql($sql, $feedback);
5313 execute_sql($updatesql, $feedback);
5314 execute_sql($udelsql, $feedback);
5316 // Module instances
5317 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5318 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5319 FROM {$CFG->prefix}context ctx
5320 JOIN {$CFG->prefix}course_modules cm ON ctx.instanceid=cm.id
5321 JOIN {$CFG->prefix}context pctx ON cm.course=pctx.instanceid
5322 WHERE ctx.contextlevel=".CONTEXT_MODULE."
5323 AND pctx.contextlevel=".CONTEXT_COURSE."
5324 AND NOT EXISTS (SELECT 'x'
5325 FROM {$CFG->prefix}context_temp temp
5326 WHERE temp.id = ctx.id)
5327 $ctxemptyclause";
5328 execute_sql($sql, $feedback);
5330 execute_sql($updatesql, $feedback);
5331 execute_sql($udelsql, $feedback);
5333 // Blocks - non-pinned course-view only
5334 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5335 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5336 FROM {$CFG->prefix}context ctx
5337 JOIN {$CFG->prefix}block_instance bi ON ctx.instanceid = bi.id
5338 JOIN {$CFG->prefix}context pctx ON bi.pageid=pctx.instanceid
5339 WHERE ctx.contextlevel=".CONTEXT_BLOCK."
5340 AND pctx.contextlevel=".CONTEXT_COURSE."
5341 AND bi.pagetype='course-view'
5342 AND NOT EXISTS (SELECT 'x'
5343 FROM {$CFG->prefix}context_temp temp
5344 WHERE temp.id = ctx.id)
5345 $ctxemptyclause";
5346 execute_sql($sql, $feedback);
5348 execute_sql($updatesql, $feedback);
5349 execute_sql($udelsql, $feedback);
5351 // Blocks - others
5352 $sql = "UPDATE {$CFG->prefix}context
5353 SET depth=2, path=".sql_concat("'$base/'", 'id')."
5354 WHERE contextlevel=".CONTEXT_BLOCK."
5355 AND EXISTS (SELECT 'x'
5356 FROM {$CFG->prefix}block_instance bi
5357 WHERE bi.id = {$CFG->prefix}context.instanceid
5358 AND bi.pagetype!='course-view')
5359 $emptyclause ";
5360 execute_sql($sql, $feedback);
5362 // User
5363 $sql = "UPDATE {$CFG->prefix}context
5364 SET depth=2, path=".sql_concat("'$base/'", 'id')."
5365 WHERE contextlevel=".CONTEXT_USER."
5366 AND EXISTS (SELECT 'x'
5367 FROM {$CFG->prefix}user u
5368 WHERE u.id = {$CFG->prefix}context.instanceid)
5369 $emptyclause ";
5370 execute_sql($sql, $feedback);
5372 // Personal TODO
5374 //TODO: fix group contexts
5376 // reset static course cache - it might have incorrect cached data
5377 global $context_cache, $context_cache_id;
5378 $context_cache = array();
5379 $context_cache_id = array();
5384 * Update the path field of the context and
5385 * all the dependent subcontexts that follow
5386 * the move.
5388 * The most important thing here is to be as
5389 * DB efficient as possible. This op can have a
5390 * massive impact in the DB.
5392 * @param obj current context obj
5393 * @param obj newparent new parent obj
5396 function context_moved($context, $newparent) {
5397 global $CFG;
5399 $frompath = $context->path;
5400 $newpath = $newparent->path . '/' . $context->id;
5402 $setdepth = '';
5403 if (($newparent->depth +1) != $context->depth) {
5404 $setdepth = ", depth= depth + ({$newparent->depth} - {$context->depth}) + 1";
5406 $sql = "UPDATE {$CFG->prefix}context
5407 SET path='$newpath'
5408 $setdepth
5409 WHERE path='$frompath'";
5410 execute_sql($sql,false);
5412 $len = strlen($frompath);
5413 $sql = "UPDATE {$CFG->prefix}context
5414 SET path = ".sql_concat("'$newpath'", 'SUBSTR(path, '.$len.' +1)')."
5415 $setdepth
5416 WHERE path LIKE '{$frompath}/%'";
5417 execute_sql($sql,false);
5419 mark_context_dirty($frompath);
5420 mark_context_dirty($newpath);
5425 * Turn the ctx* fields in an objectlike record
5426 * into a context subobject. This allows
5427 * us to SELECT from major tables JOINing with
5428 * context at no cost, saving a ton of context
5429 * lookups...
5431 function make_context_subobj($rec) {
5432 $ctx = new StdClass;
5433 $ctx->id = $rec->ctxid; unset($rec->ctxid);
5434 $ctx->path = $rec->ctxpath; unset($rec->ctxpath);
5435 $ctx->depth = $rec->ctxdepth; unset($rec->ctxdepth);
5436 $ctx->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
5437 $ctx->instanceid = $rec->id;
5439 $rec->context = $ctx;
5440 return $rec;
5444 * Fetch recent dirty contexts to know cheaply whether our $USER->access
5445 * is stale and needs to be reloaded.
5447 * Uses cache_flags
5448 * @param int $time
5449 * @return array of dirty contexts
5451 function get_dirty_contexts($time) {
5452 return get_cache_flags('accesslib/dirtycontexts', $time-2);
5456 * Mark a context as dirty (with timestamp)
5457 * so as to force reloading of the context.
5458 * @param string $path context path
5460 function mark_context_dirty($path) {
5461 global $CFG, $DIRTYCONTEXTS;
5462 // only if it is a non-empty string
5463 if (is_string($path) && $path !== '') {
5464 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
5465 if (isset($DIRTYCONTEXTS)) {
5466 $DIRTYCONTEXTS[$path] = 1;
5472 * Will walk the contextpath to answer whether
5473 * the contextpath is dirty
5475 * @param array $contexts array of strings
5476 * @param obj/array dirty contexts from get_dirty_contexts()
5477 * @return bool
5479 function is_contextpath_dirty($pathcontexts, $dirty) {
5480 $path = '';
5481 foreach ($pathcontexts as $ctx) {
5482 $path = $path.'/'.$ctx;
5483 if (isset($dirty[$path])) {
5484 return true;
5487 return false;
5492 * switch role order (used in admin/roles/manage.php)
5494 * @param int $first id of role to move down
5495 * @param int $second id of role to move up
5497 * @return bool success or failure
5499 function switch_roles($first, $second) {
5500 $status = true;
5501 //first find temorary sortorder number
5502 $tempsort = count_records('role') + 3;
5503 while (get_record('role','sortorder', $tempsort)) {
5504 $tempsort += 3;
5507 $r1 = new object();
5508 $r1->id = $first->id;
5509 $r1->sortorder = $tempsort;
5510 $r2 = new object();
5511 $r2->id = $second->id;
5512 $r2->sortorder = $first->sortorder;
5514 if (!update_record('role', $r1)) {
5515 debugging("Can not update role with ID $r1->id!");
5516 $status = false;
5519 if (!update_record('role', $r2)) {
5520 debugging("Can not update role with ID $r2->id!");
5521 $status = false;
5524 $r1->sortorder = $second->sortorder;
5525 if (!update_record('role', $r1)) {
5526 debugging("Can not update role with ID $r1->id!");
5527 $status = false;
5530 return $status;
5534 * duplicates all the base definitions of a role
5536 * @param object $sourcerole role to copy from
5537 * @param int $targetrole id of role to copy to
5539 * @return void
5541 function role_cap_duplicate($sourcerole, $targetrole) {
5542 global $CFG;
5543 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
5544 $caps = get_records_sql("SELECT * FROM {$CFG->prefix}role_capabilities
5545 WHERE roleid = $sourcerole->id
5546 AND contextid = $systemcontext->id");
5547 // adding capabilities
5548 foreach ($caps as $cap) {
5549 unset($cap->id);
5550 $cap->roleid = $targetrole;
5551 insert_record('role_capabilities', $cap);