3 ///////////////////////////////////////////////////////////////////////////
5 // NOTICE OF COPYRIGHT //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
10 // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
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. //
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: //
22 // http://www.gnu.org/copyleft/gpl.html //
24 ///////////////////////////////////////////////////////////////////////////
27 * Public API vs internals
28 * -----------------------
30 * General users probably only care about
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...
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()
50 * - enrol_into_course()
51 * - role_assign()/role_unassign()
55 * - load_all_capabilities()
56 * - reload_all_capabilities()
58 * - has_capability_in_accessdata()
60 * - get_user_access_sitewide()
62 * - get_role_access_bycontext()
67 * - "ctx" means context
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
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)
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.
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);
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!
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
;
203 * Gets the accessdata for role "sitewide"
204 * (system down to course)
208 function get_role_access($roleid, $accessdata=NULL) {
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;
250 foreach ($cron_cache[$roleid] as $rd) {
251 $k = "{$rd->path}:{$roleid}";
252 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
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
;
270 * Gets the accessdata for role "sitewide"
271 * (system down to course)
275 function get_default_frontpage_role_access($roleid, $accessdata=NULL) {
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
;
309 * Get the default guest role
310 * @return object role
312 function get_guest_role() {
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
);
321 debugging('Can not find any guest role!');
325 if ($guestrole = get_record('role','id', $CFG->guestroleid
)) {
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
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');
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
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
);
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
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
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']);
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
428 if (defined('FULLME') && FULLME
=== 'cron') {
429 load_user_accessdata($userid);
430 $USER->access
= $ACCESS[$userid];
431 $DIRTYCONTEXTS = array();
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
495 function has_any_capability($capabilities, $context, $userid=NULL, $doanything=true) {
496 foreach ($capabilities as $capability) {
497 if (has_capability($capability, $context, $userid, $doanything)) {
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
515 * @returns bool $isadmin
517 function is_siteadmin($userid) {
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);
536 function get_course_from_path ($path) {
537 // assume that nothing is more than 1 course deep
538 if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
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!");
552 $base = '/' . SYSCONTEXTID
;
553 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
555 if ($path === $base) {
558 if (in_array($path, $accessdata['loaded'], true)) {
566 * Walk the accessdata array and return true/false.
567 * Deals with prohibits, roleswitching, aggregating
570 * The main feature of here is being FAST and with no
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.
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.
614 * - Document how it works
615 * - Rewrite in ASM :-)
618 function has_capability_in_accessdata($capability, $context, $accessdata, $doanything) {
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)) {
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
638 $ignoreguest = $accessdata['dr'];
641 // Coerce it to an int
642 $CAP_PROHIBIT = (int)CAP_PROHIBIT
;
644 $cc = count($contexts);
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
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
679 } elseif ($perm === $CAP_PROHIBIT) {
686 // As we are dealing with a switchrole,
687 // we return _here_, do _not_ walk up
688 // the hierarchy any further
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);
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];
718 for ($rn=0;$rn<$rc;$rn++
) {
719 $roleid = (int)$ras[$rn];
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
731 && isset($accessdata['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'])
732 && $accessdata['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'] > 0) {
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) {
742 } elseif ($perm === $CAP_PROHIBIT) {
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;
756 } elseif ($ctxcapdepth === $rolecapdepth) {
758 } elseif ($ctxcapdepth < $rolecapdepth) {
760 $ctxcapdepth = $rolecapdepth;
761 } else { // ctxcaptdepth is deeper
765 // The most local RAs with a defined
766 // permission ($ctxcan) win, except
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) {
775 } elseif ($can === 0) { // see note above
777 $capdepth = $ctxcapdepth;
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);
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)) {
805 array_unshift($contexts, $path);
808 $cc = count($contexts);
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='') {
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.
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
)) {
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().
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) {
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);
943 $fields = $basefields;
945 $coursefields = 'c.' .implode(',c.', $fields);
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)
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
966 JOIN {$CFG->prefix}context ctx
967 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
969 $rs = get_recordset_sql($sql);
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
978 FROM {$CFG->prefix}context ctx
979 WHERE ctx.contextlevel=".CONTEXT_COURSECAT
."
981 $rs = get_recordset_sql($sql);
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
;
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) .')';
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
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
1026 $rs = get_recordset_sql($sql);
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)) {
1036 if ($limit > 0 && $cc++
> $limit) {
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) {
1065 // this flag has not been set!
1066 // (not clean install, or upgraded successfully to 1.7 and up)
1067 if (empty($CFG->rolesactive
)) {
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
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();
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
],
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
;
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()
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
1163 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1165 $rs = get_recordset_sql($sql);
1169 while ($rd = rs_fetch_next_record($rs)) {
1170 $k = "{$rd->path}:{$rd->roleid}";
1171 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
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);
1202 while ($rd = rs_fetch_next_record($rs)) {
1203 $k = "{$rd->path}:{$rd->roleid}";
1204 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
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) {
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.
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 $targetid = array_pop(explode('/',get_course_from_path($context->path
)));
1257 $context = get_context_instance_by_id($targetid);
1262 // Role assignments in the context and below
1264 $sql = "SELECT ctx.path, ra.roleid
1265 FROM {$CFG->prefix}role_assignments ra
1266 JOIN {$CFG->prefix}context ctx
1267 ON ra.contextid=ctx.id
1268 WHERE ra.userid = $userid
1269 AND (ctx.path = '{$context->path}' OR ctx.path LIKE '{$context->path}/%')
1270 ORDER BY ctx.depth, ctx.path";
1271 $rs = get_recordset_sql($sql);
1276 $localroles = array();
1277 while ($ra = rs_fetch_next_record($rs)) {
1278 if (!isset($accessdata['ra'][$ra->path
])) {
1279 $accessdata['ra'][$ra->path
] = array();
1281 array_push($accessdata['ra'][$ra->path
], $ra->roleid
);
1282 array_push($localroles, $ra->roleid
);
1287 // Walk up and down the tree to grab all the roledefs
1288 // of interest to our user...
1291 // - we use IN() but the number of roles is very limited.
1293 $courseroles = aggregate_roles_from_accessdata($context, $accessdata);
1295 // Do we have any interesting "local" roles?
1296 $localroles = array_diff($localroles,$courseroles); // only "new" local roles
1297 $wherelocalroles='';
1298 if (count($localroles)) {
1299 // Role defs for local roles in 'higher' contexts...
1300 $contexts = substr($context->path
, 1); // kill leading slash
1301 $contexts = str_replace('/', ',', $contexts);
1302 $localroleids = implode(',',$localroles);
1303 $wherelocalroles="OR (rc.roleid IN ({$localroleids})
1304 AND ctx.id IN ($contexts))" ;
1307 // We will want overrides for all of them
1309 if ($roleids = implode(',',array_merge($courseroles,$localroles))) {
1310 $whereroles = "rc.roleid IN ($roleids) AND";
1312 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1313 FROM {$CFG->prefix}role_capabilities rc
1314 JOIN {$CFG->prefix}context ctx
1315 ON rc.contextid=ctx.id
1317 (ctx.id={$context->id} OR ctx.path LIKE '{$context->path}/%'))
1319 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1321 $newrdefs = array();
1322 if ($rs = get_recordset_sql($sql)) {
1323 while ($rd = rs_fetch_next_record($rs)) {
1324 $k = "{$rd->path}:{$rd->roleid}";
1325 if (!array_key_exists($k, $newrdefs)) {
1326 $newrdefs[$k] = array();
1328 $newrdefs[$k][$rd->capability
] = $rd->permission
;
1332 debugging('Bad SQL encountered!');
1335 compact_rdefs($newrdefs);
1336 foreach ($newrdefs as $key=>$value) {
1337 $accessdata['rdef'][$key] =& $newrdefs[$key];
1340 // error_log("loaded {$context->path}");
1341 $accessdata['loaded'][] = $context->path
;
1345 * It add to the access ctrl array the data
1346 * needed by a role for a given context.
1348 * The data is added in the rdef key.
1350 * This role-centric function is useful for role_switching
1351 * and to get an overview of what a role gets under a
1352 * given context and below...
1354 * @param $roleid integer - the id of the user
1355 * @param $context context obj - needs path!
1356 * @param $accessdata accessdata array
1359 function get_role_access_bycontext($roleid, $context, $accessdata=NULL) {
1363 /* Get the relevant rolecaps into rdef
1364 * - relevant role caps
1365 * - at ctx and above
1369 if (is_null($accessdata)) {
1370 $accessdata = array(); // named list
1371 $accessdata['ra'] = array();
1372 $accessdata['rdef'] = array();
1373 $accessdata['loaded'] = array();
1376 $contexts = substr($context->path
, 1); // kill leading slash
1377 $contexts = str_replace('/', ',', $contexts);
1380 // Walk up and down the tree to grab all the roledefs
1381 // of interest to our role...
1383 // NOTE: we use an IN clauses here - which
1384 // might explode on huge sites with very convoluted nesting of
1385 // categories... - extremely unlikely that the number of nested
1386 // categories is so large that we hit the limits of IN()
1388 $sql = "SELECT ctx.path, rc.capability, rc.permission
1389 FROM {$CFG->prefix}role_capabilities rc
1390 JOIN {$CFG->prefix}context ctx
1391 ON rc.contextid=ctx.id
1392 WHERE rc.roleid=$roleid AND
1393 ( ctx.id IN ($contexts) OR
1394 ctx.path LIKE '{$context->path}/%' )
1395 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1397 $rs = get_recordset_sql($sql);
1398 while ($rd = rs_fetch_next_record($rs)) {
1399 $k = "{$rd->path}:{$roleid}";
1400 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
1408 * Load accessdata for a user
1409 * into the $ACCESS global
1411 * Used by has_capability() - but feel free
1412 * to call it if you are about to run a BIG
1413 * cron run across a bazillion users.
1416 function load_user_accessdata($userid) {
1417 global $ACCESS,$CFG;
1419 $base = '/'.SYSCONTEXTID
;
1421 $accessdata = get_user_access_sitewide($userid);
1422 $frontpagecontext = get_context_instance(CONTEXT_COURSE
, SITEID
);
1424 // provide "default role" & set 'dr'
1426 if (!empty($CFG->defaultuserroleid
)) {
1427 $accessdata = get_role_access($CFG->defaultuserroleid
, $accessdata);
1428 if (!isset($accessdata['ra'][$base])) {
1429 $accessdata['ra'][$base] = array($CFG->defaultuserroleid
);
1431 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid
);
1433 $accessdata['dr'] = $CFG->defaultuserroleid
;
1437 // provide "default frontpage role"
1439 if (!empty($CFG->defaultfrontpageroleid
)) {
1440 $base = '/'. SYSCONTEXTID
.'/'. $frontpagecontext->id
;
1441 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid
, $accessdata);
1442 if (!isset($accessdata['ra'][$base])) {
1443 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid
);
1445 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid
);
1448 // for dirty timestamps in cron
1449 $accessdata['time'] = time();
1451 $ACCESS[$userid] = $accessdata;
1452 compact_rdefs($ACCESS[$userid]['rdef']);
1458 * Use shared copy of role definistions stored in $RDEFS;
1459 * @param array $rdefs array of role definitions in contexts
1461 function compact_rdefs(&$rdefs) {
1465 * This is a basic sharing only, we could also
1466 * use md5 sums of values. The main purpose is to
1467 * reduce mem in cron jobs - many users in $ACCESS array.
1470 foreach ($rdefs as $key => $value) {
1471 if (!array_key_exists($key, $RDEFS)) {
1472 $RDEFS[$key] = $rdefs[$key];
1474 $rdefs[$key] =& $RDEFS[$key];
1479 * A convenience function to completely load all the capabilities
1480 * for the current user. This is what gets called from complete_user_login()
1481 * for example. Call it only _after_ you've setup $USER and called
1482 * check_enrolment_plugins();
1485 function load_all_capabilities() {
1486 global $USER, $CFG, $DIRTYCONTEXTS;
1488 $base = '/'.SYSCONTEXTID
;
1490 if (isguestuser()) {
1491 $guest = get_guest_role();
1494 $USER->access
= get_role_access($guest->id
);
1495 // Put the ghost enrolment in place...
1496 $USER->access
['ra'][$base] = array($guest->id
);
1499 } else if (isloggedin()) {
1501 $accessdata = get_user_access_sitewide($USER->id
);
1504 // provide "default role" & set 'dr'
1506 if (!empty($CFG->defaultuserroleid
)) {
1507 $accessdata = get_role_access($CFG->defaultuserroleid
, $accessdata);
1508 if (!isset($accessdata['ra'][$base])) {
1509 $accessdata['ra'][$base] = array($CFG->defaultuserroleid
);
1511 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid
);
1513 $accessdata['dr'] = $CFG->defaultuserroleid
;
1516 $frontpagecontext = get_context_instance(CONTEXT_COURSE
, SITEID
);
1519 // provide "default frontpage role"
1521 if (!empty($CFG->defaultfrontpageroleid
)) {
1522 $base = '/'. SYSCONTEXTID
.'/'. $frontpagecontext->id
;
1523 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid
, $accessdata);
1524 if (!isset($accessdata['ra'][$base])) {
1525 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid
);
1527 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid
);
1530 $USER->access
= $accessdata;
1532 } else if (!empty($CFG->notloggedinroleid
)) {
1533 $USER->access
= get_role_access($CFG->notloggedinroleid
);
1534 $USER->access
['ra'][$base] = array($CFG->notloggedinroleid
);
1537 // Timestamp to read dirty context timestamps later
1538 $USER->access
['time'] = time();
1539 $DIRTYCONTEXTS = array();
1541 // Clear to force a refresh
1542 unset($USER->mycourses
);
1546 * A convenience function to completely reload all the capabilities
1547 * for the current user when roles have been updated in a relevant
1548 * context -- but PRESERVING switchroles and loginas.
1550 * That is - completely transparent to the user.
1552 * Note: rewrites $USER->access completely.
1555 function reload_all_capabilities() {
1558 // error_log("reloading");
1561 if (isset($USER->access
['rsw'])) {
1562 $sw = $USER->access
['rsw'];
1563 // error_log(print_r($sw,1));
1566 unset($USER->access
);
1567 unset($USER->mycourses
);
1569 load_all_capabilities();
1571 foreach ($sw as $path => $roleid) {
1572 $context = get_record('context', 'path', $path);
1573 role_switch($roleid, $context);
1579 * Adds a temp role to an accessdata array.
1581 * Useful for the "temporary guest" access
1582 * we grant to logged-in users.
1584 * Note - assumes a course context!
1587 function load_temp_role($context, $roleid, $accessdata) {
1592 // Load rdefs for the role in -
1594 // - all the parents
1595 // - and below - IOWs overrides...
1598 // turn the path into a list of context ids
1599 $contexts = substr($context->path
, 1); // kill leading slash
1600 $contexts = str_replace('/', ',', $contexts);
1602 $sql = "SELECT ctx.path,
1603 rc.capability, rc.permission
1604 FROM {$CFG->prefix}context ctx
1605 JOIN {$CFG->prefix}role_capabilities rc
1606 ON rc.contextid=ctx.id
1607 WHERE (ctx.id IN ($contexts)
1608 OR ctx.path LIKE '{$context->path}/%')
1609 AND rc.roleid = {$roleid}
1610 ORDER BY ctx.depth, ctx.path";
1611 $rs = get_recordset_sql($sql);
1612 while ($rd = rs_fetch_next_record($rs)) {
1613 $k = "{$rd->path}:{$roleid}";
1614 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
1619 // Say we loaded everything for the course context
1620 // - which we just did - if the user gets a proper
1621 // RA in this session, this data will need to be reloaded,
1622 // but that is handled by the complete accessdata reload
1624 array_push($accessdata['loaded'], $context->path
);
1629 if (isset($accessdata['ra'][$context->path
])) {
1630 array_push($accessdata['ra'][$context->path
], $roleid);
1632 $accessdata['ra'][$context->path
] = array($roleid);
1640 * Check all the login enrolment information for the given user object
1641 * by querying the enrolment plugins
1643 function check_enrolment_plugins(&$user) {
1646 static $inprogress; // To prevent this function being called more than once in an invocation
1648 if (!empty($inprogress[$user->id
])) {
1652 $inprogress[$user->id
] = true; // Set the flag
1654 require_once($CFG->dirroot
.'/enrol/enrol.class.php');
1656 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled
))) {
1657 $plugins = array($CFG->enrol
);
1660 foreach ($plugins as $plugin) {
1661 $enrol = enrolment_factory
::factory($plugin);
1662 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1663 $enrol->setup_enrolments($user);
1664 } else { /// Run legacy enrolment methods
1665 if (method_exists($enrol, 'get_student_courses')) {
1666 $enrol->get_student_courses($user);
1668 if (method_exists($enrol, 'get_teacher_courses')) {
1669 $enrol->get_teacher_courses($user);
1672 /// deal with $user->students and $user->teachers stuff
1673 unset($user->student
);
1674 unset($user->teacher
);
1679 unset($inprogress[$user->id
]); // Unset the flag
1683 * Installs the roles system.
1684 * This function runs on a fresh install as well as on an upgrade from the old
1685 * hard-coded student/teacher/admin etc. roles to the new roles system.
1687 function moodle_install_roles() {
1691 /// Create a system wide context for assignemnt.
1692 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM
);
1695 /// Create default/legacy roles and capabilities.
1696 /// (1 legacy capability per legacy role at system level).
1698 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1699 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1700 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1701 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1702 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1703 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1704 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1705 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1706 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1707 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1708 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1709 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
1710 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1711 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
1713 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1715 if (!assign_capability('moodle/site:doanything', CAP_ALLOW
, $adminrole, $systemcontext->id
)) {
1716 error('Could not assign moodle/site:doanything to the admin role');
1718 if (!update_capabilities()) {
1719 error('Had trouble upgrading the core capabilities for the Roles System');
1722 /// Look inside user_admin, user_creator, user_teachers, user_students and
1723 /// assign above new roles. If a user has both teacher and student role,
1724 /// only teacher role is assigned. The assignment should be system level.
1726 $dbtables = $db->MetaTables('TABLES');
1728 /// Set up the progress bar
1730 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1732 $totalcount = $progresscount = 0;
1733 foreach ($usertables as $usertable) {
1734 if (in_array($CFG->prefix
.$usertable, $dbtables)) {
1735 $totalcount +
= count_records($usertable);
1739 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1741 /// Upgrade the admins.
1742 /// Sort using id ASC, first one is primary admin.
1744 if (in_array($CFG->prefix
.'user_admins', $dbtables)) {
1745 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix
.'user_admins ORDER BY ID ASC')) {
1746 while ($admin = rs_fetch_next_record($rs)) {
1747 role_assign($adminrole, $admin->userid
, 0, $systemcontext->id
);
1749 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1754 // This is a fresh install.
1758 /// Upgrade course creators.
1759 if (in_array($CFG->prefix
.'user_coursecreators', $dbtables)) {
1760 if ($rs = get_recordset('user_coursecreators')) {
1761 while ($coursecreator = rs_fetch_next_record($rs)) {
1762 role_assign($coursecreatorrole, $coursecreator->userid
, 0, $systemcontext->id
);
1764 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1771 /// Upgrade editting teachers and non-editting teachers.
1772 if (in_array($CFG->prefix
.'user_teachers', $dbtables)) {
1773 if ($rs = get_recordset('user_teachers')) {
1774 while ($teacher = rs_fetch_next_record($rs)) {
1776 // removed code here to ignore site level assignments
1777 // since the contexts are separated now
1779 // populate the user_lastaccess table
1780 $access = new object();
1781 $access->timeaccess
= $teacher->timeaccess
;
1782 $access->userid
= $teacher->userid
;
1783 $access->courseid
= $teacher->course
;
1784 insert_record('user_lastaccess', $access);
1786 // assign the default student role
1787 $coursecontext = get_context_instance(CONTEXT_COURSE
, $teacher->course
); // needs cache
1789 if ($teacher->authority
== 0) {
1795 if ($teacher->editall
) { // editting teacher
1796 role_assign($editteacherrole, $teacher->userid
, 0, $coursecontext->id
, $teacher->timestart
, $teacher->timeend
, $hiddenteacher, $teacher->enrol
, $teacher->timemodified
);
1798 role_assign($noneditteacherrole, $teacher->userid
, 0, $coursecontext->id
, $teacher->timestart
, $teacher->timeend
, $hiddenteacher, $teacher->enrol
, $teacher->timemodified
);
1801 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1808 /// Upgrade students.
1809 if (in_array($CFG->prefix
.'user_students', $dbtables)) {
1810 if ($rs = get_recordset('user_students')) {
1811 while ($student = rs_fetch_next_record($rs)) {
1813 // populate the user_lastaccess table
1814 $access = new object;
1815 $access->timeaccess
= $student->timeaccess
;
1816 $access->userid
= $student->userid
;
1817 $access->courseid
= $student->course
;
1818 insert_record('user_lastaccess', $access);
1820 // assign the default student role
1821 $coursecontext = get_context_instance(CONTEXT_COURSE
, $student->course
);
1822 role_assign($studentrole, $student->userid
, 0, $coursecontext->id
, $student->timestart
, $student->timeend
, 0, $student->enrol
, $student->time
);
1824 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1831 /// Upgrade guest (only 1 entry).
1832 if ($guestuser = get_record('user', 'username', 'guest')) {
1833 role_assign($guestrole, $guestuser->id
, 0, $systemcontext->id
);
1835 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1838 /// Insert the correct records for legacy roles
1839 allow_assign($adminrole, $adminrole);
1840 allow_assign($adminrole, $coursecreatorrole);
1841 allow_assign($adminrole, $noneditteacherrole);
1842 allow_assign($adminrole, $editteacherrole);
1843 allow_assign($adminrole, $studentrole);
1844 allow_assign($adminrole, $guestrole);
1846 allow_assign($coursecreatorrole, $noneditteacherrole);
1847 allow_assign($coursecreatorrole, $editteacherrole);
1848 allow_assign($coursecreatorrole, $studentrole);
1849 allow_assign($coursecreatorrole, $guestrole);
1851 allow_assign($editteacherrole, $noneditteacherrole);
1852 allow_assign($editteacherrole, $studentrole);
1853 allow_assign($editteacherrole, $guestrole);
1855 /// Set up default permissions for overrides
1856 allow_override($adminrole, $adminrole);
1857 allow_override($adminrole, $coursecreatorrole);
1858 allow_override($adminrole, $noneditteacherrole);
1859 allow_override($adminrole, $editteacherrole);
1860 allow_override($adminrole, $studentrole);
1861 allow_override($adminrole, $guestrole);
1862 allow_override($adminrole, $userrole);
1865 /// Delete the old user tables when we are done
1867 $tables = array('user_students', 'user_teachers', 'user_coursecreators', 'user_admins');
1868 foreach ($tables as $tablename) {
1869 $table = new XMLDBTable($tablename);
1870 if (table_exists($table)) {
1877 * Returns array of all legacy roles.
1879 function get_legacy_roles() {
1881 'admin' => 'moodle/legacy:admin',
1882 'coursecreator' => 'moodle/legacy:coursecreator',
1883 'editingteacher' => 'moodle/legacy:editingteacher',
1884 'teacher' => 'moodle/legacy:teacher',
1885 'student' => 'moodle/legacy:student',
1886 'guest' => 'moodle/legacy:guest',
1887 'user' => 'moodle/legacy:user'
1891 function get_legacy_type($roleid) {
1892 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
1893 $legacyroles = get_legacy_roles();
1896 foreach($legacyroles as $ltype=>$lcap) {
1897 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
1898 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
1899 //choose first selected legacy capability - reset the rest
1900 if (empty($result)) {
1903 unassign_capability($lcap, $roleid);
1912 * Assign the defaults found in this capabality definition to roles that have
1913 * the corresponding legacy capabilities assigned to them.
1914 * @param $legacyperms - an array in the format (example):
1915 * 'guest' => CAP_PREVENT,
1916 * 'student' => CAP_ALLOW,
1917 * 'teacher' => CAP_ALLOW,
1918 * 'editingteacher' => CAP_ALLOW,
1919 * 'coursecreator' => CAP_ALLOW,
1920 * 'admin' => CAP_ALLOW
1921 * @return boolean - success or failure.
1923 function assign_legacy_capabilities($capability, $legacyperms) {
1925 $legacyroles = get_legacy_roles();
1927 foreach ($legacyperms as $type => $perm) {
1929 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1931 if (!array_key_exists($type, $legacyroles)) {
1932 error('Incorrect legacy role definition for type: '.$type);
1935 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW
)) {
1936 foreach ($roles as $role) {
1937 // Assign a site level capability.
1938 if (!assign_capability($capability, $perm, $role->id
, $systemcontext->id
)) {
1949 * Checks to see if a capability is a legacy capability.
1950 * @param $capabilityname
1953 function islegacy($capabilityname) {
1954 if (strpos($capabilityname, 'moodle/legacy') === 0) {
1963 /**********************************
1964 * Context Manipulation functions *
1965 **********************************/
1968 * Create a new context record for use by all roles-related stuff
1969 * assumes that the caller has done the homework.
1972 * @param $instanceid
1974 * @return object newly created context
1976 function create_context($contextlevel, $instanceid) {
1980 if ($contextlevel == CONTEXT_SYSTEM
) {
1981 return create_system_context();
1984 $context = new object();
1985 $context->contextlevel
= $contextlevel;
1986 $context->instanceid
= $instanceid;
1988 // Define $context->path based on the parent
1989 // context. In other words... Who is your daddy?
1990 $basepath = '/' . SYSCONTEXTID
;
1995 switch ($contextlevel) {
1996 case CONTEXT_COURSECAT
:
1997 $sql = "SELECT ctx.path, ctx.depth
1998 FROM {$CFG->prefix}context ctx
1999 JOIN {$CFG->prefix}course_categories cc
2000 ON (cc.parent=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT
.")
2001 WHERE cc.id={$instanceid}";
2002 if ($p = get_record_sql($sql)) {
2003 $basepath = $p->path
;
2004 $basedepth = $p->depth
;
2005 } else if ($category = get_record('course_categories', 'id', $instanceid)) {
2006 if (empty($category->parent
)) {
2007 // ok - this is a top category
2008 } else if ($parent = get_context_instance(CONTEXT_COURSECAT
, $category->parent
)) {
2009 $basepath = $parent->path
;
2010 $basedepth = $parent->depth
;
2012 // wrong parent category - no big deal, this can be fixed later
2017 // incorrect category id
2022 case CONTEXT_COURSE
:
2023 $sql = "SELECT ctx.path, ctx.depth
2024 FROM {$CFG->prefix}context ctx
2025 JOIN {$CFG->prefix}course c
2026 ON (c.category=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT
.")
2027 WHERE c.id={$instanceid} AND c.id !=" . SITEID
;
2028 if ($p = get_record_sql($sql)) {
2029 $basepath = $p->path
;
2030 $basedepth = $p->depth
;
2031 } else if ($course = get_record('course', 'id', $instanceid)) {
2032 if ($course->id
== SITEID
) {
2033 //ok - no parent category
2034 } else if ($parent = get_context_instance(CONTEXT_COURSECAT
, $course->category
)) {
2035 $basepath = $parent->path
;
2036 $basedepth = $parent->depth
;
2038 // wrong parent category of course - no big deal, this can be fixed later
2042 } else if ($instanceid == SITEID
) {
2043 // no errors for missing site course during installation
2046 // incorrect course id
2051 case CONTEXT_MODULE
:
2052 $sql = "SELECT ctx.path, ctx.depth
2053 FROM {$CFG->prefix}context ctx
2054 JOIN {$CFG->prefix}course_modules cm
2055 ON (cm.course=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
2056 WHERE cm.id={$instanceid}";
2057 if ($p = get_record_sql($sql)) {
2058 $basepath = $p->path
;
2059 $basedepth = $p->depth
;
2060 } else if ($cm = get_record('course_modules', 'id', $instanceid)) {
2061 if ($parent = get_context_instance(CONTEXT_COURSE
, $cm->course
)) {
2062 $basepath = $parent->path
;
2063 $basedepth = $parent->depth
;
2065 // course does not exist - modules can not exist without a course
2069 // cm does not exist
2075 // Only non-pinned & course-page based
2076 $sql = "SELECT ctx.path, ctx.depth
2077 FROM {$CFG->prefix}context ctx
2078 JOIN {$CFG->prefix}block_instance bi
2079 ON (bi.pageid=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
2080 WHERE bi.id={$instanceid} AND bi.pagetype='course-view'";
2081 if ($p = get_record_sql($sql)) {
2082 $basepath = $p->path
;
2083 $basedepth = $p->depth
;
2084 } else if ($bi = get_record('block_instance', 'id', $instanceid)) {
2085 if ($bi->pagetype
!= 'course-view') {
2086 // ok - not a course block
2087 } else if ($parent = get_context_instance(CONTEXT_COURSE
, $bi->pageid
)) {
2088 $basepath = $parent->path
;
2089 $basedepth = $parent->depth
;
2091 // parent course does not exist - course blocks can not exist without a course
2095 // block does not exist
2100 // default to basepath
2104 // if grandparents unknown, maybe rebuild_context_path() will solve it later
2105 if ($basedepth != 0) {
2106 $context->depth
= $basedepth+
1;
2109 if ($result and $id = insert_record('context', $context)) {
2110 // can't set the full path till we know the id!
2111 if ($basedepth != 0 and !empty($basepath)) {
2112 set_field('context', 'path', $basepath.'/'. $id, 'id', $id);
2114 return get_context_instance_by_id($id);
2117 debugging('Error: could not insert new context level "'.
2118 s($contextlevel).'", instance "'.
2119 s($instanceid).'".');
2125 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
2127 function get_system_context($cache=true) {
2128 static $cached = null;
2129 if ($cache and defined('SYSCONTEXTID')) {
2130 if (is_null($cached)) {
2131 $cached = new object();
2132 $cached->id
= SYSCONTEXTID
;
2133 $cached->contextlevel
= CONTEXT_SYSTEM
;
2134 $cached->instanceid
= 0;
2135 $cached->path
= '/'.SYSCONTEXTID
;
2141 if (!$context = get_record('context', 'contextlevel', CONTEXT_SYSTEM
)) {
2142 $context = new object();
2143 $context->contextlevel
= CONTEXT_SYSTEM
;
2144 $context->instanceid
= 0;
2145 $context->depth
= 1;
2146 $context->path
= NULL; //not known before insert
2148 if (!$context->id
= insert_record('context', $context)) {
2149 // better something than nothing - let's hope it will work somehow
2150 if (!defined('SYSCONTEXTID')) {
2151 define('SYSCONTEXTID', 1);
2153 debugging('Can not create system context');
2154 $context->id
= SYSCONTEXTID
;
2155 $context->path
= '/'.SYSCONTEXTID
;
2160 if (!isset($context->depth
) or $context->depth
!= 1 or $context->instanceid
!= 0 or $context->path
!= '/'.$context->id
) {
2161 $context->instanceid
= 0;
2162 $context->path
= '/'.$context->id
;
2163 $context->depth
= 1;
2164 update_record('context', $context);
2167 if (!defined('SYSCONTEXTID')) {
2168 define('SYSCONTEXTID', $context->id
);
2176 * Remove a context record and any dependent entries,
2177 * removes context from static context cache too
2179 * @param $instanceid
2181 * @return bool properly deleted
2183 function delete_context($contextlevel, $instanceid) {
2184 global $context_cache, $context_cache_id;
2186 // do not use get_context_instance(), because the related object might not exist,
2187 // or the context does not exist yet and it would be created now
2188 if ($context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instanceid)) {
2189 $result = delete_records('role_assignments', 'contextid', $context->id
) &&
2190 delete_records('role_capabilities', 'contextid', $context->id
) &&
2191 delete_records('context', 'id', $context->id
);
2193 // do not mark dirty contexts if parents unknown
2194 if (!is_null($context->path
) and $context->depth
> 0) {
2195 mark_context_dirty($context->path
);
2198 // purge static context cache if entry present
2199 unset($context_cache[$contextlevel][$instanceid]);
2200 unset($context_cache_id[$context->id
]);
2210 * Precreates all contexts including all parents
2211 * @param int $contextlevel, empty means all
2212 * @param bool $buildpaths update paths and depths
2213 * @param bool $feedback show sql feedback
2216 function create_contexts($contextlevel=null, $buildpaths=true, $feedback=false) {
2219 //make sure system context exists
2220 $syscontext = get_system_context(false);
2222 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSECAT
2223 or $contextlevel == CONTEXT_COURSE
2224 or $contextlevel == CONTEXT_MODULE
2225 or $contextlevel == CONTEXT_BLOCK
) {
2226 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2227 SELECT ".CONTEXT_COURSECAT
.", cc.id
2228 FROM {$CFG->prefix}course_categories cc
2229 WHERE NOT EXISTS (SELECT 'x'
2230 FROM {$CFG->prefix}context cx
2231 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT
.")";
2232 execute_sql($sql, $feedback);
2236 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSE
2237 or $contextlevel == CONTEXT_MODULE
2238 or $contextlevel == CONTEXT_BLOCK
) {
2239 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2240 SELECT ".CONTEXT_COURSE
.", c.id
2241 FROM {$CFG->prefix}course c
2242 WHERE NOT EXISTS (SELECT 'x'
2243 FROM {$CFG->prefix}context cx
2244 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE
.")";
2245 execute_sql($sql, $feedback);
2249 if (empty($contextlevel) or $contextlevel == CONTEXT_MODULE
) {
2250 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2251 SELECT ".CONTEXT_MODULE
.", cm.id
2252 FROM {$CFG->prefix}course_modules cm
2253 WHERE NOT EXISTS (SELECT 'x'
2254 FROM {$CFG->prefix}context cx
2255 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE
.")";
2256 execute_sql($sql, $feedback);
2259 if (empty($contextlevel) or $contextlevel == CONTEXT_BLOCK
) {
2260 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2261 SELECT ".CONTEXT_BLOCK
.", bi.id
2262 FROM {$CFG->prefix}block_instance bi
2263 WHERE NOT EXISTS (SELECT 'x'
2264 FROM {$CFG->prefix}context cx
2265 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK
.")";
2266 execute_sql($sql, $feedback);
2269 if (empty($contextlevel) or $contextlevel == CONTEXT_USER
) {
2270 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2271 SELECT ".CONTEXT_USER
.", u.id
2272 FROM {$CFG->prefix}user u
2274 AND NOT EXISTS (SELECT 'x'
2275 FROM {$CFG->prefix}context cx
2276 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER
.")";
2277 execute_sql($sql, $feedback);
2282 build_context_path(false, $feedback);
2287 * Remove stale context records
2291 function cleanup_contexts() {
2294 $sql = " SELECT c.contextlevel,
2295 c.instanceid AS instanceid
2296 FROM {$CFG->prefix}context c
2297 LEFT OUTER JOIN {$CFG->prefix}course_categories t
2298 ON c.instanceid = t.id
2299 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSECAT
. "
2301 SELECT c.contextlevel,
2303 FROM {$CFG->prefix}context c
2304 LEFT OUTER JOIN {$CFG->prefix}course t
2305 ON c.instanceid = t.id
2306 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSE
. "
2308 SELECT c.contextlevel,
2310 FROM {$CFG->prefix}context c
2311 LEFT OUTER JOIN {$CFG->prefix}course_modules t
2312 ON c.instanceid = t.id
2313 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_MODULE
. "
2315 SELECT c.contextlevel,
2317 FROM {$CFG->prefix}context c
2318 LEFT OUTER JOIN {$CFG->prefix}user t
2319 ON c.instanceid = t.id
2320 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_USER
. "
2322 SELECT c.contextlevel,
2324 FROM {$CFG->prefix}context c
2325 LEFT OUTER JOIN {$CFG->prefix}block_instance t
2326 ON c.instanceid = t.id
2327 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_BLOCK
. "
2329 SELECT c.contextlevel,
2331 FROM {$CFG->prefix}context c
2332 LEFT OUTER JOIN {$CFG->prefix}groups t
2333 ON c.instanceid = t.id
2334 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_GROUP
. "
2336 if ($rs = get_recordset_sql($sql)) {
2339 while ($tx && $ctx = rs_fetch_next_record($rs)) {
2340 $tx = $tx && delete_context($ctx->contextlevel
, $ctx->instanceid
);
2355 * Get the context instance as an object. This function will create the
2356 * context instance if it does not exist yet.
2357 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2358 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
2359 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
2360 * @return object The context object.
2362 function get_context_instance($contextlevel, $instance=0) {
2364 global $context_cache, $context_cache_id, $CFG;
2365 static $allowed_contexts = array(CONTEXT_SYSTEM
, CONTEXT_USER
, CONTEXT_COURSECAT
, CONTEXT_COURSE
, CONTEXT_GROUP
, CONTEXT_MODULE
, CONTEXT_BLOCK
);
2367 if ($contextlevel === 'clearcache') {
2368 // TODO: Remove for v2.0
2369 // No longer needed, but we'll catch it to avoid erroring out on custom code.
2370 // This used to be a fix for MDL-9016
2371 // "Restoring into existing course, deleting first
2372 // deletes context and doesn't recreate it"
2376 /// System context has special cache
2377 if ($contextlevel == CONTEXT_SYSTEM
) {
2378 return get_system_context();
2381 /// check allowed context levels
2382 if (!in_array($contextlevel, $allowed_contexts)) {
2383 // fatal error, code must be fixed - probably typo or switched parameters
2384 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
2387 if (!is_array($instance)) {
2389 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2390 return $context_cache[$contextlevel][$instance];
2393 /// Get it from the database, or create it
2394 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
2395 $context = create_context($contextlevel, $instance);
2398 /// Only add to cache if context isn't empty.
2399 if (!empty($context)) {
2400 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
2401 $context_cache_id[$context->id
] = $context; // Cache it for later
2408 /// ok, somebody wants to load several contexts to save some db queries ;-)
2409 $instances = $instance;
2412 foreach ($instances as $key=>$instance) {
2413 /// Check the cache first
2414 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2415 $result[$instance] = $context_cache[$contextlevel][$instance];
2416 unset($instances[$key]);
2422 if (count($instances) > 1) {
2423 $instanceids = implode(',', $instances);
2424 $instanceids = "instanceid IN ($instanceids)";
2426 $instance = reset($instances);
2427 $instanceids = "instanceid = $instance";
2430 if (!$contexts = get_records_sql("SELECT instanceid, id, contextlevel, path, depth
2431 FROM {$CFG->prefix}context
2432 WHERE contextlevel=$contextlevel AND $instanceids")) {
2433 $contexts = array();
2436 foreach ($instances as $instance) {
2437 if (isset($contexts[$instance])) {
2438 $context = $contexts[$instance];
2440 $context = create_context($contextlevel, $instance);
2443 if (!empty($context)) {
2444 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
2445 $context_cache_id[$context->id
] = $context; // Cache it for later
2448 $result[$instance] = $context;
2457 * Get a context instance as an object, from a given context id.
2458 * @param mixed $id a context id or array of ids.
2459 * @return mixed object or array of the context object.
2461 function get_context_instance_by_id($id) {
2463 global $context_cache, $context_cache_id;
2465 if ($id == SYSCONTEXTID
) {
2466 return get_system_context();
2469 if (isset($context_cache_id[$id])) { // Already cached
2470 return $context_cache_id[$id];
2473 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
2474 $context_cache[$context->contextlevel
][$context->instanceid
] = $context;
2475 $context_cache_id[$context->id
] = $context;
2484 * Get the local override (if any) for a given capability in a role in a context
2487 * @param $capability
2489 function get_local_override($roleid, $contextid, $capability) {
2490 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
2495 /************************************
2496 * DB TABLE RELATED FUNCTIONS *
2497 ************************************/
2500 * function that creates a role
2501 * @param name - role name
2502 * @param shortname - role short name
2503 * @param description - role description
2504 * @param legacy - optional legacy capability
2505 * @return id or false
2507 function create_role($name, $shortname, $description, $legacy='') {
2509 // check for duplicate role name
2511 if ($role = get_record('role','name', $name)) {
2512 error('there is already a role with this name!');
2515 if ($role = get_record('role','shortname', $shortname)) {
2516 error('there is already a role with this shortname!');
2519 $role = new object();
2520 $role->name
= $name;
2521 $role->shortname
= $shortname;
2522 $role->description
= $description;
2524 //find free sortorder number
2525 $role->sortorder
= count_records('role');
2526 while (get_record('role','sortorder', $role->sortorder
)) {
2527 $role->sortorder +
= 1;
2530 if (!$context = get_context_instance(CONTEXT_SYSTEM
)) {
2534 if ($id = insert_record('role', $role)) {
2536 assign_capability($legacy, CAP_ALLOW
, $id, $context->id
);
2539 /// By default, users with role:manage at site level
2540 /// should be able to assign users to this new role, and override this new role's capabilities
2542 // find all admin roles
2543 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW
, $context)) {
2544 // foreach admin role
2545 foreach ($adminroles as $arole) {
2546 // write allow_assign and allow_overrid
2547 allow_assign($arole->id
, $id);
2548 allow_override($arole->id
, $id);
2560 * function that deletes a role and cleanups up after it
2561 * @param roleid - id of role to delete
2564 function delete_role($roleid) {
2568 // mdl 10149, check if this is the last active admin role
2569 // if we make the admin role not deletable then this part can go
2571 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
2573 if ($role = get_record('role', 'id', $roleid)) {
2574 if (record_exists('role_capabilities', 'contextid', $systemcontext->id
, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
2575 // deleting an admin role
2577 if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $systemcontext)) {
2578 foreach ($adminroles as $adminrole) {
2579 if ($adminrole->id
!= $roleid) {
2580 // some other admin role
2581 if (record_exists('role_assignments', 'roleid', $adminrole->id
, 'contextid', $systemcontext->id
)) {
2582 // found another admin role with at least 1 user assigned
2589 if ($status !== true) {
2590 error ('You can not delete this role because there is no other admin roles with users assigned');
2595 // first unssign all users
2596 if (!role_unassign($roleid)) {
2597 debugging("Error while unassigning all users from role with ID $roleid!");
2601 // cleanup all references to this role, ignore errors
2604 // MDL-10679 find all contexts where this role has an override
2605 $contexts = get_records_sql("SELECT contextid, contextid
2606 FROM {$CFG->prefix}role_capabilities
2607 WHERE roleid = $roleid");
2609 delete_records('role_capabilities', 'roleid', $roleid);
2611 delete_records('role_allow_assign', 'roleid', $roleid);
2612 delete_records('role_allow_assign', 'allowassign', $roleid);
2613 delete_records('role_allow_override', 'roleid', $roleid);
2614 delete_records('role_allow_override', 'allowoverride', $roleid);
2615 delete_records('role_names', 'roleid', $roleid);
2618 // finally delete the role itself
2619 // get this before the name is gone for logging
2620 $rolename = get_field('role', 'name', 'id', $roleid);
2622 if ($success and !delete_records('role', 'id', $roleid)) {
2623 debugging("Could not delete role record with ID $roleid!");
2628 add_to_log(SITEID
, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '', $USER->id
);
2635 * Function to write context specific overrides, or default capabilities.
2636 * @param module - string name
2637 * @param capability - string name
2638 * @param contextid - context id
2639 * @param roleid - role id
2640 * @param permission - int 1,-1 or -1000
2641 * should not be writing if permission is 0
2643 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2647 if (empty($permission) ||
$permission == CAP_INHERIT
) { // if permission is not set
2648 unassign_capability($capability, $roleid, $contextid);
2652 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
2654 if ($existing and !$overwrite) { // We want to keep whatever is there already
2659 $cap->contextid
= $contextid;
2660 $cap->roleid
= $roleid;
2661 $cap->capability
= $capability;
2662 $cap->permission
= $permission;
2663 $cap->timemodified
= time();
2664 $cap->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2667 $cap->id
= $existing->id
;
2668 return update_record('role_capabilities', $cap);
2670 $c = get_record('context', 'id', $contextid);
2671 return insert_record('role_capabilities', $cap);
2676 * Unassign a capability from a role.
2677 * @param $roleid - the role id
2678 * @param $capability - the name of the capability
2679 * @return boolean - success or failure
2681 function unassign_capability($capability, $roleid, $contextid=NULL) {
2683 if (isset($contextid)) {
2684 // delete from context rel, if this is the last override in this context
2685 $status = delete_records('role_capabilities', 'capability', $capability,
2686 'roleid', $roleid, 'contextid', $contextid);
2688 $status = delete_records('role_capabilities', 'capability', $capability,
2696 * Get the roles that have a given capability assigned to it. This function
2697 * does not resolve the actual permission of the capability. It just checks
2698 * for assignment only.
2699 * @param $capability - capability name (string)
2700 * @param $permission - optional, the permission defined for this capability
2701 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2702 * @return array or role objects
2704 function get_roles_with_capability($capability, $permission=NULL, $context='') {
2709 if ($contexts = get_parent_contexts($context)) {
2710 $listofcontexts = '('.implode(',', $contexts).')';
2712 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2713 $listofcontexts = '('.$sitecontext->id
.')'; // must be site
2715 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
2720 $selectroles = "SELECT r.*
2721 FROM {$CFG->prefix}role r,
2722 {$CFG->prefix}role_capabilities rc
2723 WHERE rc.capability = '$capability'
2724 AND rc.roleid = r.id $contextstr";
2726 if (isset($permission)) {
2727 $selectroles .= " AND rc.permission = '$permission'";
2729 return get_records_sql($selectroles);
2734 * This function makes a role-assignment (a role for a user or group in a particular context)
2735 * @param $roleid - the role of the id
2736 * @param $userid - userid
2737 * @param $groupid - group id
2738 * @param $contextid - id of the context
2739 * @param $timestart - time this assignment becomes effective
2740 * @param $timeend - time this assignemnt ceases to be effective
2742 * @return id - new id of the assigment
2744 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
2747 /// Do some data validation
2749 if (empty($roleid)) {
2750 debugging('Role ID not provided');
2754 if (empty($userid) && empty($groupid)) {
2755 debugging('Either userid or groupid must be provided');
2759 if ($userid && !record_exists('user', 'id', $userid)) {
2760 debugging('User ID '.intval($userid).' does not exist!');
2764 if ($groupid && !groups_group_exists($groupid)) {
2765 debugging('Group ID '.intval($groupid).' does not exist!');
2769 if (!$context = get_context_instance_by_id($contextid)) {
2770 debugging('Context ID '.intval($contextid).' does not exist!');
2774 if (($timestart and $timeend) and ($timestart > $timeend)) {
2775 debugging('The end time can not be earlier than the start time');
2779 if (!$timemodified) {
2780 $timemodified = time();
2783 /// Check for existing entry
2785 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'userid', $userid);
2787 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'groupid', $groupid);
2791 $newra = new object;
2793 if (empty($ra)) { // Create a new entry
2794 $newra->roleid
= $roleid;
2795 $newra->contextid
= $context->id
;
2796 $newra->userid
= $userid;
2797 $newra->hidden
= $hidden;
2798 $newra->enrol
= $enrol;
2799 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2800 /// by repeating queries with the same exact parameters in a 100 secs time window
2801 $newra->timestart
= round($timestart, -2);
2802 $newra->timeend
= $timeend;
2803 $newra->timemodified
= $timemodified;
2804 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2806 $success = insert_record('role_assignments', $newra);
2808 } else { // We already have one, just update it
2810 $newra->id
= $ra->id
;
2811 $newra->hidden
= $hidden;
2812 $newra->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 $newra->timestart
= round($timestart, -2);
2816 $newra->timeend
= $timeend;
2817 $newra->timemodified
= $timemodified;
2818 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2820 $success = update_record('role_assignments', $newra);
2823 if ($success) { /// Role was assigned, so do some other things
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);
2846 /// now handle metacourse role assignments if in course context
2847 if ($success and $context->contextlevel
== CONTEXT_COURSE
) {
2848 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2849 foreach ($parents as $parent) {
2850 sync_metacourse($parent->parent_course
);
2860 * Deletes one or more role assignments. You must specify at least one parameter.
2865 * @param $enrol unassign only if enrolment type matches, NULL means anything
2866 * @return boolean - success or failure
2868 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
2874 $args = array('roleid', 'userid', 'groupid', 'contextid');
2876 foreach ($args as $arg) {
2878 $select[] = $arg.' = '.$
$arg;
2881 if (!empty($enrol)) {
2882 $select[] = "enrol='$enrol'";
2886 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2887 $mods = get_list_of_plugins('mod');
2888 foreach($ras as $ra) {
2889 /// infinite loop protection when deleting recursively
2890 if (!$ra = get_record('role_assignments', 'id', $ra->id
)) {
2893 $success = delete_records('role_assignments', 'id', $ra->id
) and $success;
2895 if (!$context = get_context_instance_by_id($ra->contextid
)) {
2896 // strange error, not much to do
2900 /* mark contexts as dirty here, because we need the refreshed
2901 * caps bellow to delete group membership and user_lastaccess!
2902 * and yes, this is very expensive for bulk operations :-(
2904 mark_context_dirty($context->path
);
2906 /// If the user is the current user, then do full reload of capabilities too.
2907 if (!empty($USER->id
) && $USER->id
== $ra->userid
) {
2908 load_all_capabilities();
2911 /// Ask all the modules if anything needs to be done for this user
2912 foreach ($mods as $mod) {
2913 include_once($CFG->dirroot
.'/mod/'.$mod.'/lib.php');
2914 $functionname = $mod.'_role_unassign';
2915 if (function_exists($functionname)) {
2916 $functionname($ra->userid
, $context); // watch out, $context might be NULL if something goes wrong
2920 /// now handle metacourse role unassigment and removing from goups if in course context
2921 if ($context->contextlevel
== CONTEXT_COURSE
) {
2923 // cleanup leftover course groups/subscriptions etc when user has
2924 // no capability to view course
2925 // this may be slow, but this is the proper way of doing it
2926 if (!has_capability('moodle/course:view', $context, $ra->userid
)) {
2927 // remove from groups
2928 if ($groups = groups_get_all_groups($context->instanceid
)) {
2929 foreach ($groups as $group) {
2930 delete_records('groups_members', 'groupid', $group->id
, 'userid', $ra->userid
);
2934 // delete lastaccess records
2935 delete_records('user_lastaccess', 'userid', $ra->userid
, 'courseid', $context->instanceid
);
2938 //unassign roles in metacourses if needed
2939 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2940 foreach ($parents as $parent) {
2941 sync_metacourse($parent->parent_course
);
2953 * A convenience function to take care of the common case where you
2954 * just want to enrol someone using the default role into a course
2956 * @param object $course
2957 * @param object $user
2958 * @param string $enrol - the plugin used to do this enrolment
2960 function enrol_into_course($course, $user, $enrol) {
2962 $timestart = time();
2963 // remove time part from the timestamp and keep only the date part
2964 $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
2965 if ($course->enrolperiod
) {
2966 $timeend = $timestart +
$course->enrolperiod
;
2971 if ($role = get_default_course_role($course)) {
2973 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2975 if (!role_assign($role->id
, $user->id
, 0, $context->id
, $timestart, $timeend, 0, $enrol)) {
2979 // force accessdata refresh for users visiting this context...
2980 mark_context_dirty($context->path
);
2982 email_welcome_message_to_user($course, $user);
2984 add_to_log($course->id
, 'course', 'enrol',
2985 'view.php?id='.$course->id
, $course->id
);
2994 * Loads the capability definitions for the component (from file). If no
2995 * capabilities are defined for the component, we simply return an empty array.
2996 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2997 * @return array of capabilities
2999 function load_capability_def($component) {
3002 if ($component == 'moodle') {
3003 $defpath = $CFG->libdir
.'/db/access.php';
3004 $varprefix = 'moodle';
3006 $compparts = explode('/', $component);
3008 if ($compparts[0] == 'block') {
3009 // Blocks are an exception. Blocks directory is 'blocks', and not
3010 // 'block'. So we need to jump through hoops.
3011 $defpath = $CFG->dirroot
.'/'.$compparts[0].
3012 's/'.$compparts[1].'/db/access.php';
3013 $varprefix = $compparts[0].'_'.$compparts[1];
3015 } else if ($compparts[0] == 'format') {
3016 // Similar to the above, course formats are 'format' while they
3017 // are stored in 'course/format'.
3018 $defpath = $CFG->dirroot
.'/course/'.$component.'/db/access.php';
3019 $varprefix = $compparts[0].'_'.$compparts[1];
3021 } else if ($compparts[0] == 'gradeimport') {
3022 $defpath = $CFG->dirroot
.'/grade/import/'.$compparts[1].'/db/access.php';
3023 $varprefix = $compparts[0].'_'.$compparts[1];
3025 } else if ($compparts[0] == 'gradeexport') {
3026 $defpath = $CFG->dirroot
.'/grade/export/'.$compparts[1].'/db/access.php';
3027 $varprefix = $compparts[0].'_'.$compparts[1];
3029 } else if ($compparts[0] == 'gradereport') {
3030 $defpath = $CFG->dirroot
.'/grade/report/'.$compparts[1].'/db/access.php';
3031 $varprefix = $compparts[0].'_'.$compparts[1];
3034 $defpath = $CFG->dirroot
.'/'.$component.'/db/access.php';
3035 $varprefix = str_replace('/', '_', $component);
3038 $capabilities = array();
3040 if (file_exists($defpath)) {
3042 $capabilities = $
{$varprefix.'_capabilities'};
3044 return $capabilities;
3049 * Gets the capabilities that have been cached in the database for this
3051 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3052 * @return array of capabilities
3054 function get_cached_capabilities($component='moodle') {
3055 if ($component == 'moodle') {
3056 $storedcaps = get_records_select('capabilities',
3057 "name LIKE 'moodle/%:%'");
3058 } else if ($component == 'local') {
3059 $storedcaps = get_records_select('capabilities',
3060 "name LIKE 'moodle/local:%'");
3062 $storedcaps = get_records_select('capabilities',
3063 "name LIKE '$component:%'");
3069 * Returns default capabilities for given legacy role type.
3071 * @param string legacy role name
3074 function get_default_capabilities($legacyrole) {
3075 if (!$allcaps = get_records('capabilities')) {
3076 error('Error: no capabilitites defined!');
3079 $defaults = array();
3080 $components = array();
3081 foreach ($allcaps as $cap) {
3082 if (!in_array($cap->component
, $components)) {
3083 $components[] = $cap->component
;
3084 $alldefs = array_merge($alldefs, load_capability_def($cap->component
));
3087 foreach($alldefs as $name=>$def) {
3088 if (isset($def['legacy'][$legacyrole])) {
3089 $defaults[$name] = $def['legacy'][$legacyrole];
3094 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW
;
3095 if ($legacyrole == 'admin') {
3096 $defaults['moodle/site:doanything'] = CAP_ALLOW
;
3102 * Reset role capabilitites to default according to selected legacy capability.
3103 * If several legacy caps selected, use the first from get_default_capabilities.
3104 * If no legacy selected, removes all capabilities.
3106 * @param int @roleid
3108 function reset_role_capabilities($roleid) {
3109 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
3110 $legacyroles = get_legacy_roles();
3112 $defaultcaps = array();
3113 foreach($legacyroles as $ltype=>$lcap) {
3114 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
3115 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
3116 //choose first selected legacy capability
3117 $defaultcaps = get_default_capabilities($ltype);
3122 delete_records('role_capabilities', 'roleid', $roleid);
3123 if (!empty($defaultcaps)) {
3124 foreach($defaultcaps as $cap=>$permission) {
3125 assign_capability($cap, $permission, $roleid, $sitecontext->id
);
3131 * Updates the capabilities table with the component capability definitions.
3132 * If no parameters are given, the function updates the core moodle
3135 * Note that the absence of the db/access.php capabilities definition file
3136 * will cause any stored capabilities for the component to be removed from
3139 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3142 function update_capabilities($component='moodle') {
3144 $storedcaps = array();
3146 $filecaps = load_capability_def($component);
3147 $cachedcaps = get_cached_capabilities($component);
3149 foreach ($cachedcaps as $cachedcap) {
3150 array_push($storedcaps, $cachedcap->name
);
3151 // update risk bitmasks and context levels in existing capabilities if needed
3152 if (array_key_exists($cachedcap->name
, $filecaps)) {
3153 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name
])) {
3154 $filecaps[$cachedcap->name
]['riskbitmask'] = 0; // no risk if not specified
3156 if ($cachedcap->riskbitmask
!= $filecaps[$cachedcap->name
]['riskbitmask']) {
3157 $updatecap = new object();
3158 $updatecap->id
= $cachedcap->id
;
3159 $updatecap->riskbitmask
= $filecaps[$cachedcap->name
]['riskbitmask'];
3160 if (!update_record('capabilities', $updatecap)) {
3165 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name
])) {
3166 $filecaps[$cachedcap->name
]['contextlevel'] = 0; // no context level defined
3168 if ($cachedcap->contextlevel
!= $filecaps[$cachedcap->name
]['contextlevel']) {
3169 $updatecap = new object();
3170 $updatecap->id
= $cachedcap->id
;
3171 $updatecap->contextlevel
= $filecaps[$cachedcap->name
]['contextlevel'];
3172 if (!update_record('capabilities', $updatecap)) {
3180 // Are there new capabilities in the file definition?
3183 foreach ($filecaps as $filecap => $def) {
3185 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
3186 if (!array_key_exists('riskbitmask', $def)) {
3187 $def['riskbitmask'] = 0; // no risk if not specified
3189 $newcaps[$filecap] = $def;
3192 // Add new capabilities to the stored definition.
3193 foreach ($newcaps as $capname => $capdef) {
3194 $capability = new object;
3195 $capability->name
= $capname;
3196 $capability->captype
= $capdef['captype'];
3197 $capability->contextlevel
= $capdef['contextlevel'];
3198 $capability->component
= $component;
3199 $capability->riskbitmask
= $capdef['riskbitmask'];
3201 if (!insert_record('capabilities', $capability, false, 'id')) {
3206 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
3207 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
3208 foreach ($rolecapabilities as $rolecapability){
3209 //assign_capability will update rather than insert if capability exists
3210 if (!assign_capability($capname, $rolecapability->permission
,
3211 $rolecapability->roleid
, $rolecapability->contextid
, true)){
3212 notify('Could not clone capabilities for '.$capname);
3216 // Do we need to assign the new capabilities to roles that have the
3217 // legacy capabilities moodle/legacy:* as well?
3218 // we ignore legacy key if we have cloned permissions
3219 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
3220 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
3221 notify('Could not assign legacy capabilities for '.$capname);
3224 // Are there any capabilities that have been removed from the file
3225 // definition that we need to delete from the stored capabilities and
3226 // role assignments?
3227 capabilities_cleanup($component, $filecaps);
3234 * Deletes cached capabilities that are no longer needed by the component.
3235 * Also unassigns these capabilities from any roles that have them.
3236 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3237 * @param $newcapdef - array of the new capability definitions that will be
3238 * compared with the cached capabilities
3239 * @return int - number of deprecated capabilities that have been removed
3241 function capabilities_cleanup($component, $newcapdef=NULL) {
3245 if ($cachedcaps = get_cached_capabilities($component)) {
3246 foreach ($cachedcaps as $cachedcap) {
3247 if (empty($newcapdef) ||
3248 array_key_exists($cachedcap->name
, $newcapdef) === false) {
3250 // Remove from capabilities cache.
3251 if (!delete_records('capabilities', 'name', $cachedcap->name
)) {
3252 error('Could not delete deprecated capability '.$cachedcap->name
);
3256 // Delete from roles.
3257 if($roles = get_roles_with_capability($cachedcap->name
)) {
3258 foreach($roles as $role) {
3259 if (!unassign_capability($cachedcap->name
, $role->id
)) {
3260 error('Could not unassign deprecated capability '.
3261 $cachedcap->name
.' from role '.$role->name
);
3268 return $removedcount;
3279 * prints human readable context identifier.
3281 function print_context_name($context, $withprefix = true, $short = false) {
3284 switch ($context->contextlevel
) {
3286 case CONTEXT_SYSTEM
: // by now it's a definite an inherit
3287 $name = get_string('coresystem');
3291 if ($user = get_record('user', 'id', $context->instanceid
)) {
3293 $name = get_string('user').': ';
3295 $name .= fullname($user);
3299 case CONTEXT_COURSECAT
: // Coursecat -> coursecat or site
3300 if ($category = get_record('course_categories', 'id', $context->instanceid
)) {
3302 $name = get_string('category').': ';
3304 $name .=format_string($category->name
);
3308 case CONTEXT_COURSE
: // 1 to 1 to course cat
3309 if ($course = get_record('course', 'id', $context->instanceid
)) {
3311 if ($context->instanceid
== SITEID
) {
3312 $name = get_string('site').': ';
3314 $name = get_string('course').': ';
3318 $name .=format_string($course->shortname
);
3320 $name .=format_string($course->fullname
);
3326 case CONTEXT_GROUP
: // 1 to 1 to course
3327 if ($name = groups_get_group_name($context->instanceid
)) {
3329 $name = get_string('group').': '. $name;
3334 case CONTEXT_MODULE
: // 1 to 1 to course
3335 if ($cm = get_record('course_modules','id',$context->instanceid
)) {
3336 if ($module = get_record('modules','id',$cm->module
)) {
3337 if ($mod = get_record($module->name
, 'id', $cm->instance
)) {
3339 $name = get_string('activitymodule').': ';
3341 $name .= $mod->name
;
3347 case CONTEXT_BLOCK
: // not necessarily 1 to 1 to course
3348 if ($blockinstance = get_record('block_instance','id',$context->instanceid
)) {
3349 if ($block = get_record('block','id',$blockinstance->blockid
)) {
3351 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
3352 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
3353 $blockname = "block_$block->name";
3354 if ($blockobject = new $blockname()) {
3356 $name = get_string('block').': ';
3358 $name .= $blockobject->title
;
3365 error ('This is an unknown context (' . $context->contextlevel
. ') in print_context_name!');
3374 * Extracts the relevant capabilities given a contextid.
3375 * All case based, example an instance of forum context.
3376 * Will fetch all forum related capabilities, while course contexts
3377 * Will fetch all capabilities
3378 * @param object context
3382 * `name` varchar(150) NOT NULL,
3383 * `captype` varchar(50) NOT NULL,
3384 * `contextlevel` int(10) NOT NULL,
3385 * `component` varchar(100) NOT NULL,
3387 function fetch_context_capabilities($context) {
3391 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
3393 switch ($context->contextlevel
) {
3395 case CONTEXT_SYSTEM
: // all
3396 $SQL = "select * from {$CFG->prefix}capabilities";
3401 FROM {$CFG->prefix}capabilities
3402 WHERE contextlevel = ".CONTEXT_USER
;
3405 case CONTEXT_COURSECAT
: // all
3406 $SQL = "select * from {$CFG->prefix}capabilities";
3409 case CONTEXT_COURSE
: // all
3410 $SQL = "select * from {$CFG->prefix}capabilities";
3413 case CONTEXT_GROUP
: // group caps
3416 case CONTEXT_MODULE
: // mod caps
3417 $cm = get_record('course_modules', 'id', $context->instanceid
);
3418 $module = get_record('modules', 'id', $cm->module
);
3420 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE
."
3421 and component = 'mod/$module->name'";
3424 case CONTEXT_BLOCK
: // block caps
3425 $cb = get_record('block_instance', 'id', $context->instanceid
);
3426 $block = get_record('block', 'id', $cb->blockid
);
3428 $SQL = "select * from {$CFG->prefix}capabilities where (contextlevel = ".CONTEXT_BLOCK
." AND component = 'moodle')
3429 OR (component = 'block/$block->name')";
3436 if (!$records = get_records_sql($SQL.' '.$sort)) {
3440 /// the rest of code is a bit hacky, think twice before modifying it :-(
3442 // special sorting of core system capabiltites and enrollments
3443 if (in_array($context->contextlevel
, array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
, CONTEXT_COURSE
))) {
3445 foreach ($records as $key=>$record) {
3446 if (preg_match('|^moodle/|', $record->name
) and $record->contextlevel
== CONTEXT_SYSTEM
) {
3447 $first[$key] = $record;
3448 unset($records[$key]);
3449 } else if (count($first)){
3453 if (count($first)) {
3454 $records = $first +
$records; // merge the two arrays keeping the keys
3457 $contextindependentcaps = fetch_context_independent_capabilities();
3458 $records = array_merge($contextindependentcaps, $records);
3467 * Gets the context-independent capabilities that should be overrridable in
3469 * @return array of capability records from the capabilities table.
3471 function fetch_context_independent_capabilities() {
3473 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
3474 $contextindependentcaps = array(
3475 'moodle/site:accessallgroups'
3480 foreach ($contextindependentcaps as $capname) {
3481 $record = get_record('capabilities', 'name', $capname);
3482 array_push($records, $record);
3489 * This function pulls out all the resolved capabilities (overrides and
3490 * defaults) of a role used in capability overrides in contexts at a given
3492 * @param obj $context
3493 * @param int $roleid
3494 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
3497 function role_context_capabilities($roleid, $context, $cap='') {
3500 $contexts = get_parent_contexts($context);
3501 $contexts[] = $context->id
;
3502 $contexts = '('.implode(',', $contexts).')';
3505 $search = " AND rc.capability = '$cap' ";
3511 FROM {$CFG->prefix}role_capabilities rc,
3512 {$CFG->prefix}context c
3513 WHERE rc.contextid in $contexts
3514 AND rc.roleid = $roleid
3515 AND rc.contextid = c.id $search
3516 ORDER BY c.contextlevel DESC,
3517 rc.capability DESC";
3519 $capabilities = array();
3521 if ($records = get_records_sql($SQL)) {
3522 // We are traversing via reverse order.
3523 foreach ($records as $record) {
3524 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3525 if (!isset($capabilities[$record->capability
]) ||
$record->permission
<-500) {
3526 $capabilities[$record->capability
] = $record->permission
;
3530 return $capabilities;
3534 * Recursive function which, given a context, find all parent context ids,
3535 * and return the array in reverse order, i.e. parent first, then grand
3538 * @param object $context
3541 function get_parent_contexts($context) {
3543 if ($context->path
== '') {
3547 $parentcontexts = substr($context->path
, 1); // kill leading slash
3548 $parentcontexts = explode('/', $parentcontexts);
3549 array_pop($parentcontexts); // and remove its own id
3551 return array_reverse($parentcontexts);
3555 * Return the id of the parent of this context, or false if there is no parent (only happens if this
3556 * is the site context.)
3558 * @param object $context
3559 * @return integer the id of the parent context.
3561 function get_parent_contextid($context) {
3562 $parentcontexts = get_parent_contexts($context);
3563 if (count($parentcontexts) == 0) {
3566 return array_shift($parentcontexts);
3570 * Recursive function which, given a context, find all its children context ids.
3572 * When called for a course context, it will return the modules and blocks
3573 * displayed in the course page.
3575 * For course category contexts it will return categories and courses. It will
3576 * NOT recurse into courses - if you want to do that, call it on the returned
3579 * If called on a course context it _will_ populate the cache with the appropriate
3582 * @param object $context.
3583 * @return array of child records
3585 function get_child_contexts($context) {
3587 global $CFG, $context_cache;
3589 // We *MUST* populate the context_cache as the callers
3590 // will probably ask for the full record anyway soon after
3591 // soon after calling us ;-)
3593 switch ($context->contextlevel
) {
3600 case CONTEXT_MODULE
:
3610 case CONTEXT_COURSE
:
3612 // - module instances - easy
3614 // - blocks assigned to the course-view page explicitly - easy
3615 // - blocks pinned (note! we get all of them here, regardless of vis)
3616 $sql = " SELECT ctx.*
3617 FROM {$CFG->prefix}context ctx
3618 WHERE ctx.path LIKE '{$context->path}/%'
3619 AND ctx.contextlevel IN (".CONTEXT_MODULE
.",".CONTEXT_BLOCK
.")
3622 FROM {$CFG->prefix}context ctx
3623 JOIN {$CFG->prefix}groups g
3624 ON (ctx.instanceid=g.id AND ctx.contextlevel=".CONTEXT_GROUP
.")
3625 WHERE g.courseid={$context->instanceid}
3628 FROM {$CFG->prefix}context ctx
3629 JOIN {$CFG->prefix}block_pinned b
3630 ON (ctx.instanceid=b.blockid AND ctx.contextlevel=".CONTEXT_BLOCK
.")
3631 WHERE b.pagetype='course-view'
3633 $rs = get_recordset_sql($sql);
3635 while ($rec = rs_fetch_next_record($rs)) {
3636 $records[$rec->id
] = $rec;
3637 $context_cache[$rec->contextlevel
][$rec->instanceid
] = $rec;
3643 case CONTEXT_COURSECAT
:
3647 $sql = " SELECT ctx.*
3648 FROM {$CFG->prefix}context ctx
3649 WHERE ctx.path LIKE '{$context->path}/%'
3650 AND ctx.contextlevel IN (".CONTEXT_COURSECAT
.",".CONTEXT_COURSE
.")
3652 $rs = get_recordset_sql($sql);
3654 while ($rec = rs_fetch_next_record($rs)) {
3655 $records[$rec->id
] = $rec;
3656 $context_cache[$rec->contextlevel
][$rec->instanceid
] = $rec;
3667 case CONTEXT_SYSTEM
:
3668 // Just get all the contexts except for CONTEXT_SYSTEM level
3669 // and hope we don't OOM in the process - don't cache
3670 $sql = 'SELECT c.*'.
3671 'FROM '.$CFG->prefix
.'context c '.
3672 'WHERE contextlevel != '.CONTEXT_SYSTEM
;
3674 return get_records_sql($sql);
3678 error('This is an unknown context (' . $context->contextlevel
. ') in get_child_contexts!');
3685 * Gets a string for sql calls, searching for stuff in this context or above
3686 * @param object $context
3689 function get_related_contexts_string($context) {
3690 if ($parents = get_parent_contexts($context)) {
3691 return (' IN ('.$context->id
.','.implode(',', $parents).')');
3693 return (' ='.$context->id
);
3698 * Returns the human-readable, translated version of the capability.
3699 * Basically a big switch statement.
3700 * @param $capabilityname - e.g. mod/choice:readresponses
3702 function get_capability_string($capabilityname) {
3704 // Typical capabilityname is mod/choice:readresponses
3706 $names = split('/', $capabilityname);
3707 $stringname = $names[1]; // choice:readresponses
3708 $components = split(':', $stringname);
3709 $componentname = $components[0]; // choice
3711 switch ($names[0]) {
3713 $string = get_string($stringname, $componentname);
3717 $string = get_string($stringname, 'block_'.$componentname);
3721 if ($componentname == 'local') {
3722 $string = get_string($stringname, 'local');
3724 $string = get_string($stringname, 'role');
3729 $string = get_string($stringname, 'enrol_'.$componentname);
3733 $string = get_string($stringname, 'format_'.$componentname);
3737 $string = get_string($stringname, 'gradeexport_'.$componentname);
3741 $string = get_string($stringname, 'gradeimport_'.$componentname);
3745 $string = get_string($stringname, 'gradereport_'.$componentname);
3749 $string = get_string($stringname);
3758 * This gets the mod/block/course/core etc strings.
3760 * @param $contextlevel
3762 function get_component_string($component, $contextlevel) {
3764 switch ($contextlevel) {
3766 case CONTEXT_SYSTEM
:
3767 if (preg_match('|^enrol/|', $component)) {
3768 $langname = str_replace('/', '_', $component);
3769 $string = get_string('enrolname', $langname);
3770 } else if (preg_match('|^block/|', $component)) {
3771 $langname = str_replace('/', '_', $component);
3772 $string = get_string('blockname', $langname);
3773 } else if (preg_match('|^local|', $component)) {
3774 $langname = str_replace('/', '_', $component);
3775 $string = get_string('local');
3777 $string = get_string('coresystem');
3782 $string = get_string('users');
3785 case CONTEXT_COURSECAT
:
3786 $string = get_string('categories');
3789 case CONTEXT_COURSE
:
3790 if (preg_match('|^gradeimport/|', $component)
3791 ||
preg_match('|^gradeexport/|', $component)
3792 ||
preg_match('|^gradereport/|', $component)) {
3793 $string = get_string('gradebook', 'admin');
3795 $string = get_string('course');
3800 $string = get_string('group');
3803 case CONTEXT_MODULE
:
3804 $string = get_string('modulename', basename($component));
3808 if( $component == 'moodle' ){
3809 $string = get_string('block');
3811 $string = get_string('blockname', 'block_'.basename($component));
3816 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
3824 * Gets the list of roles assigned to this context and up (parents)
3825 * @param object $context
3826 * @param view - set to true when roles are pulled for display only
3827 * this is so that we can filter roles with no visible
3828 * assignment, for example, you might want to "hide" all
3829 * course creators when browsing the course participants
3833 function get_roles_used_in_context($context, $view = false) {
3837 // filter for roles with all hidden assignments
3838 // no need to return when only pulling roles for reviewing
3839 // e.g. participants page.
3840 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3841 $contextlist = get_related_contexts_string($context);
3843 $sql = "SELECT DISTINCT r.id,
3847 FROM {$CFG->prefix}role_assignments ra,
3848 {$CFG->prefix}role r
3849 WHERE r.id = ra.roleid
3850 AND ra.contextid $contextlist
3852 ORDER BY r.sortorder ASC";
3854 return get_records_sql($sql);
3858 * This function is used to print roles column in user profile page.
3860 * @param object context
3863 function get_user_roles_in_context($userid, $context, $view=true){
3867 $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';
3868 $rolenames = array();
3869 if ($roles = get_records_sql($SQL)) {
3870 foreach ($roles as $userrole) {
3871 // MDL-12544, if we are in view mode and current user has no capability to view hidden assignment, skip it
3872 if ($userrole->hidden
&& $view && !has_capability('moodle/role:viewhiddenassigns', $context)) {
3875 $rolenames[$userrole->roleid
] = $userrole->name
;
3878 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
3880 foreach ($rolenames as $roleid => $rolename) {
3881 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot
.'/user/index.php?contextid='.$context->id
.'&roleid='.$roleid.'">'.$rolename.'</a>';
3883 $rolestring = implode(',', $rolenames);
3890 * Checks if a user can override capabilities of a particular role in this context
3891 * @param object $context
3892 * @param int targetroleid - the id of the role you want to override
3895 function user_can_override($context, $targetroleid) {
3896 // first check if user has override capability
3897 // if not return false;
3898 if (!has_capability('moodle/role:override', $context)) {
3901 // pull out all active roles of this user from this context(or above)
3902 if ($userroles = get_user_roles($context)) {
3903 foreach ($userroles as $userrole) {
3904 // if any in the role_allow_override table, then it's ok
3905 if (get_record('role_allow_override', 'roleid', $userrole->roleid
, 'allowoverride', $targetroleid)) {
3916 * Checks if a user can assign users to a particular role in this context
3917 * @param object $context
3918 * @param int targetroleid - the id of the role you want to assign users to
3921 function user_can_assign($context, $targetroleid) {
3923 // first check if user has override capability
3924 // if not return false;
3925 if (!has_capability('moodle/role:assign', $context)) {
3928 // pull out all active roles of this user from this context(or above)
3929 if ($userroles = get_user_roles($context)) {
3930 foreach ($userroles as $userrole) {
3931 // if any in the role_allow_override table, then it's ok
3932 if (get_record('role_allow_assign', 'roleid', $userrole->roleid
, 'allowassign', $targetroleid)) {
3941 /** Returns all site roles in correct sort order.
3944 function get_all_roles() {
3945 return get_records('role', '', '', 'sortorder ASC');
3949 * gets all the user roles assigned in this context, or higher contexts
3950 * this is mainly used when checking if a user can assign a role, or overriding a role
3951 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3952 * allow_override tables
3953 * @param object $context
3954 * @param int $userid
3955 * @param view - set to true when roles are pulled for display only
3956 * this is so that we can filter roles with no visible
3957 * assignment, for example, you might want to "hide" all
3958 * course creators when browsing the course participants
3962 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
3964 global $USER, $CFG, $db;
3966 if (empty($userid)) {
3967 if (empty($USER->id
)) {
3970 $userid = $USER->id
;
3972 // set up hidden sql
3973 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3975 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
3976 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id
.')';
3978 $contexts = ' ra.contextid = \''.$context->id
.'\'';
3981 if (!$return = get_records_sql('SELECT ra.*, r.name, r.shortname
3982 FROM '.$CFG->prefix
.'role_assignments ra,
3983 '.$CFG->prefix
.'role r,
3984 '.$CFG->prefix
.'context c
3985 WHERE ra.userid = '.$userid.'
3986 AND ra.roleid = r.id
3987 AND ra.contextid = c.id
3988 AND '.$contexts . $hiddensql .'
3989 ORDER BY '.$order)) {
3997 * Creates a record in the allow_override table
3998 * @param int sroleid - source roleid
3999 * @param int troleid - target roleid
4000 * @return int - id or false
4002 function allow_override($sroleid, $troleid) {
4003 $record = new object();
4004 $record->roleid
= $sroleid;
4005 $record->allowoverride
= $troleid;
4006 return insert_record('role_allow_override', $record);
4010 * Creates a record in the allow_assign table
4011 * @param int sroleid - source roleid
4012 * @param int troleid - target roleid
4013 * @return int - id or false
4015 function allow_assign($sroleid, $troleid) {
4016 $record = new object;
4017 $record->roleid
= $sroleid;
4018 $record->allowassign
= $troleid;
4019 return insert_record('role_allow_assign', $record);
4023 * Gets a list of roles that this user can assign in this context
4024 * @param object $context
4025 * @param string $field
4028 function get_assignable_roles ($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS
) {
4033 $ras = get_user_roles($context);
4035 foreach ($ras as $ra) {
4036 $roleids[] = $ra->roleid
;
4040 if (count($roleids)===0) {
4044 $roleids = implode(',',$roleids);
4046 // The subselect scopes the DISTINCT down to
4047 // the role ids - a DISTINCT over the whole of
4048 // the role table is much more expensive on some DBs
4049 $sql = "SELECT r.id, r.$field
4050 FROM {$CFG->prefix}role r
4051 JOIN ( SELECT DISTINCT allowassign as allowedrole
4052 FROM {$CFG->prefix}role_allow_assign raa
4053 WHERE raa.roleid IN ($roleids) ) ar
4054 ON r.id=ar.allowedrole
4055 ORDER BY sortorder ASC";
4057 $rs = get_recordset_sql($sql);
4059 while ($r = rs_fetch_next_record($rs)) {
4060 $roles[$r->id
] = $r->{$field};
4064 return role_fix_names($roles, $context, $rolenamedisplay);
4068 * Gets a list of roles that this user can assign in this context, for the switchrole menu
4070 * This is a quick-fix for MDL-13459 until MDL-8312 is sorted out...
4071 * @param object $context
4072 * @param string $field
4075 function get_assignable_roles_for_switchrole ($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS
) {
4080 $ras = get_user_roles($context);
4082 foreach ($ras as $ra) {
4083 $roleids[] = $ra->roleid
;
4087 if (count($roleids)===0) {
4091 $roleids = implode(',',$roleids);
4093 // The subselect scopes the DISTINCT down to
4094 // the role ids - a DISTINCT over the whole of
4095 // the role table is much more expensive on some DBs
4096 $sql = "SELECT r.id, r.$field
4097 FROM {$CFG->prefix}role r
4098 JOIN ( SELECT DISTINCT allowassign as allowedrole
4099 FROM {$CFG->prefix}role_allow_assign raa
4100 WHERE raa.roleid IN ($roleids) ) ar
4101 ON r.id=ar.allowedrole
4102 JOIN {$CFG->prefix}role_capabilities rc
4103 ON (r.id = rc.roleid AND rc.capability = 'moodle/course:view'
4104 AND rc.capability != 'moodle/site:doanything')
4105 ORDER BY sortorder ASC";
4107 $rs = get_recordset_sql($sql);
4109 while ($r = rs_fetch_next_record($rs)) {
4110 $roles[$r->id
] = $r->{$field};
4114 return role_fix_names($roles, $context, $rolenamedisplay);
4118 * Gets a list of roles that this user can override in this context
4119 * @param object $context
4122 function get_overridable_roles($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS
) {
4126 if ($roles = get_all_roles()) {
4127 foreach ($roles as $role) {
4128 if (user_can_override($context, $role->id
)) {
4129 $options[$role->id
] = $role->$field;
4134 return role_fix_names($options, $context, $rolenamedisplay);
4138 * Returns a role object that is the default role for new enrolments
4141 * @param object $course
4142 * @return object $role
4144 function get_default_course_role($course) {
4147 /// First let's take the default role the course may have
4148 if (!empty($course->defaultrole
)) {
4149 if ($role = get_record('role', 'id', $course->defaultrole
)) {
4154 /// Otherwise the site setting should tell us
4155 if ($CFG->defaultcourseroleid
) {
4156 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid
)) {
4161 /// It's unlikely we'll get here, but just in case, try and find a student role
4162 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW
)) {
4163 return array_shift($studentroles); /// Take the first one
4171 * Who has this capability in this context?
4173 * This can be a very expensive call - use sparingly and keep
4174 * the results if you are going to need them again soon.
4176 * Note if $fields is empty this function attempts to get u.*
4177 * which can get rather large - and has a serious perf impact
4180 * @param $context - object
4181 * @param $capability - string capability
4182 * @param $fields - fields to be pulled
4183 * @param $sort - the sort order
4184 * @param $limitfrom - number of records to skip (offset)
4185 * @param $limitnum - number of records to fetch
4186 * @param $groups - single group or array of groups - only return
4187 * users who are in one of these group(s).
4188 * @param $exceptions - list of users to exclude
4189 * @param view - set to true when roles are pulled for display only
4190 * this is so that we can filter roles with no visible
4191 * assignment, for example, you might want to "hide" all
4192 * course creators when browsing the course participants
4194 * @param boolean $useviewallgroups if $groups is set the return users who
4195 * have capability both $capability and moodle/site:accessallgroups
4196 * in this context, as well as users who have $capability and who are
4199 function get_users_by_capability($context, $capability, $fields='', $sort='',
4200 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true,
4201 $view=false, $useviewallgroups=false) {
4204 $ctxids = substr($context->path
, 1); // kill leading slash
4205 $ctxids = str_replace('/', ',', $ctxids);
4207 // Context is the frontpage
4208 $isfrontpage = false;
4209 $iscoursepage = false; // coursepage other than fp
4210 if ($context->contextlevel
== CONTEXT_COURSE
) {
4211 if ($context->instanceid
== SITEID
) {
4212 $isfrontpage = true;
4214 $iscoursepage = true;
4218 // What roles/rolecaps are interesting?
4219 $caps = "'$capability'";
4220 if ($doanything===true) {
4221 $caps.=",'moodle/site:doanything'";
4222 $doanything_join='';
4223 $doanything_cond='';
4225 // This is an outer join against
4226 // admin-ish roleids. Any row that succeeds
4227 // in JOINing here ends up removed from
4228 // the resultset. This means we remove
4229 // rolecaps from roles that also have
4230 // 'doanything' capabilities.
4231 $doanything_join="LEFT OUTER JOIN (
4232 SELECT DISTINCT rc.roleid
4233 FROM {$CFG->prefix}role_capabilities rc
4234 WHERE rc.capability='moodle/site:doanything'
4235 AND rc.permission=".CAP_ALLOW
."
4236 AND rc.contextid IN ($ctxids)
4238 ON rc.roleid=dar.roleid";
4239 $doanything_cond="AND dar.roleid IS NULL";
4242 // fetch all capability records - we'll walk several
4243 // times over them, and should be a small set
4245 $negperm = false; // has any negative (<0) permission?
4248 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability,
4249 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
4250 FROM {$CFG->prefix}role_capabilities rc
4251 JOIN {$CFG->prefix}context ctx on rc.contextid = ctx.id
4253 WHERE rc.capability IN ($caps) AND ctx.id IN ($ctxids)
4255 ORDER BY rc.roleid ASC, ctx.depth ASC";
4256 if ($capdefs = get_records_sql($sql)) {
4257 foreach ($capdefs AS $rcid=>$rc) {
4258 $roleids[] = (int)$rc->roleid
;
4259 if ($rc->permission
< 0) {
4265 $roleids = array_unique($roleids);
4267 if (count($roleids)===0) { // noone here!
4271 // is the default role interesting? does it have
4272 // a relevant rolecap? (we use this a lot later)
4273 if (in_array((int)$CFG->defaultuserroleid
, $roleids, true)) {
4274 $defaultroleinteresting = true;
4276 $defaultroleinteresting = false;
4280 // Prepare query clauses
4282 $wherecond = array();
4285 if (is_array($groups)) {
4286 $grouptest = 'gm.groupid IN (' . implode(',', $groups) . ')';
4288 $grouptest = 'gm.groupid = ' . $groups;
4290 $grouptest = 'ra.userid IN (SELECT userid FROM ' .
4291 $CFG->prefix
. 'groups_members gm WHERE ' . $grouptest . ')';
4293 if ($useviewallgroups) {
4294 $viewallgroupsusers = get_users_by_capability($context,
4295 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
4296 $wherecond['groups'] = '('. $grouptest . ' OR ra.userid IN (' .
4297 implode(',', array_keys($viewallgroupsusers)) . '))';
4299 $wherecond['groups'] = '(' . $grouptest .')';
4304 if (!empty($exceptions)) {
4305 $wherecond['userexceptions'] = ' u.id NOT IN ('.$exceptions.')';
4308 /// Set up hidden role-assignments sql
4309 if ($view && !has_capability('moodle/role:viewhiddenassigns', $context)) {
4310 $condhiddenra = 'AND ra.hidden = 0 ';
4311 $sscondhiddenra = 'AND ssra.hidden = 0 ';
4314 $sscondhiddenra = '';
4317 // Collect WHERE conditions
4318 $where = implode(' AND ', array_values($wherecond));
4320 $where = 'WHERE ' . $where;
4323 /// Set up default fields
4324 if (empty($fields)) {
4325 if ($iscoursepage) {
4326 $fields = 'u.*, ul.timeaccess as lastaccess';
4332 /// Set up default sort
4333 if (empty($sort)) { // default to course lastaccess or just lastaccess
4334 if ($iscoursepage) {
4335 $sort = 'ul.timeaccess';
4337 $sort = 'u.lastaccess';
4340 $sortby = $sort ?
" ORDER BY $sort " : '';
4342 // User lastaccess JOIN
4343 if ((strpos($sort, 'ul.timeaccess') === FALSE) and (strpos($fields, 'ul.timeaccess') === FALSE)) { // user_lastaccess is not required MDL-13810
4346 $uljoin = "LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul
4347 ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
4351 // Simple cases - No negative permissions means we can take shortcuts
4355 // at the frontpage, and all site users have it - easy!
4356 if ($isfrontpage && !empty($CFG->defaultfrontpageroleid
)
4357 && in_array((int)$CFG->defaultfrontpageroleid
, $roleids, true)) {
4359 return get_records_sql("SELECT $fields
4360 FROM {$CFG->prefix}user u
4362 $limitfrom, $limitnum);
4365 // all site users have it, anyway
4366 // TODO: NOT ALWAYS! Check this case because this gets run for cases like this:
4367 // 1) Default role has the permission for a module thing like mod/choice:choose
4368 // 2) We are checking for an activity module context in a course
4369 // 3) Thus all users are returned even though course:view is also required
4370 if ($defaultroleinteresting) {
4371 $sql = "SELECT $fields
4372 FROM {$CFG->prefix}user u
4376 return get_records_sql($sql, $limitfrom, $limitnum);
4379 /// Simple SQL assuming no negative rolecaps.
4380 /// We use a subselect to grab the role assignments
4381 /// ensuring only one row per user -- even if they
4382 /// have many "relevant" role assignments.
4383 $select = " SELECT $fields";
4384 $from = " FROM {$CFG->prefix}user u
4385 JOIN (SELECT DISTINCT ssra.userid
4386 FROM {$CFG->prefix}role_assignments ssra
4387 WHERE ssra.contextid IN ($ctxids)
4388 AND ssra.roleid IN (".implode(',',$roleids) .")
4390 ) ra ON ra.userid = u.id
4392 $where = " WHERE u.deleted = 0 ";
4393 if (count(array_keys($wherecond))) {
4394 $where .= ' AND ' . implode(' AND ', array_values($wherecond));
4396 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
4400 // If there are any negative rolecaps, we need to
4401 // work through a subselect that will bring several rows
4402 // per user (one per RA).
4403 // Since we cannot do the job in pure SQL (not without SQL stored
4404 // procedures anyway), we end up tied to processing the data in PHP
4405 // all the way down to pagination.
4407 // In some cases, this will mean bringing across a ton of data --
4408 // when paginating, we have to walk the permisisons of all the rows
4409 // in the _previous_ pages to get the pagination correct in the case
4410 // of users that end up not having the permission - this removed.
4413 // Prepare the role permissions datastructure for fast lookups
4414 $roleperms = array(); // each role cap and depth
4415 foreach ($capdefs AS $rcid=>$rc) {
4417 $rid = (int)$rc->roleid
;
4418 $perm = (int)$rc->permission
;
4419 $rcdepth = (int)$rc->ctxdepth
;
4420 if (!isset($roleperms[$rc->capability
][$rid])) {
4421 $roleperms[$rc->capability
][$rid] = (object)array('perm' => $perm,
4422 'rcdepth' => $rcdepth);
4424 if ($roleperms[$rc->capability
][$rid]->perm
== CAP_PROHIBIT
) {
4427 // override - as we are going
4428 // from general to local perms
4429 // (as per the ORDER BY...depth ASC above)
4430 // and local perms win...
4431 $roleperms[$rc->capability
][$rid] = (object)array('perm' => $perm,
4432 'rcdepth' => $rcdepth);
4437 if ($context->contextlevel
== CONTEXT_SYSTEM
4439 ||
$defaultroleinteresting) {
4441 // Handle system / sitecourse / defaultrole-with-perhaps-neg-overrides
4442 // with a SELECT FROM user LEFT OUTER JOIN against ra -
4443 // This is expensive on the SQL and PHP sides -
4444 // moves a ton of data across the wire.
4445 $ss = "SELECT u.id as userid, ra.roleid,
4447 FROM {$CFG->prefix}user u
4448 LEFT OUTER JOIN {$CFG->prefix}role_assignments ra
4449 ON (ra.userid = u.id
4450 AND ra.contextid IN ($ctxids)
4451 AND ra.roleid IN (".implode(',',$roleids) .")
4453 LEFT OUTER JOIN {$CFG->prefix}context ctx
4454 ON ra.contextid=ctx.id
4457 // "Normal complex case" - the rolecaps we are after will
4458 // be defined in a role assignment somewhere.
4459 $ss = "SELECT ra.userid as userid, ra.roleid,
4461 FROM {$CFG->prefix}role_assignments ra
4462 JOIN {$CFG->prefix}context ctx
4463 ON ra.contextid=ctx.id
4464 WHERE ra.contextid IN ($ctxids)
4466 AND ra.roleid IN (".implode(',',$roleids) .")";
4469 $select = "SELECT $fields ,ra.roleid, ra.depth ";
4470 $from = "FROM ($ss) ra
4471 JOIN {$CFG->prefix}user u
4474 $where = "WHERE u.deleted = 0 ";
4475 if (count(array_keys($wherecond))) {
4476 $where .= ' AND ' . implode(' AND ', array_values($wherecond));
4479 // Each user's entries MUST come clustered together
4480 // and RAs ordered in depth DESC - the role/cap resolution
4481 // code depends on this.
4482 $sort .= ' , ra.userid ASC, ra.depth DESC';
4483 $sortby .= ' , ra.userid ASC, ra.depth DESC ';
4485 $rs = get_recordset_sql($select.$from.$where.$sortby);
4488 // Process the user accounts+RAs, folding repeats together...
4490 // The processing for this recordset is tricky - to fold
4491 // the role/perms of users with multiple role-assignments
4492 // correctly while still processing one-row-at-a-time
4493 // we need to add a few additional 'private' fields to
4494 // the results array - so we can treat the rows as a
4495 // state machine to track the cap/perms and at what RA-depth
4496 // and RC-depth they were defined.
4498 // So what we do here is:
4499 // - loop over rows, checking pagination limits
4500 // - when we find a new user, if we are in the page add it to the
4501 // $results, and start building $ras array with its role-assignments
4502 // - when we are dealing with the next user, or are at the end of the userlist
4503 // (last rec or last in page), trigger the check-permission idiom
4504 // - the check permission idiom will
4505 // - add the default enrolment if needed
4506 // - call has_capability_from_rarc(), which based on RAs and RCs will return a bool
4507 // (should be fairly tight code ;-) )
4508 // - if the user has permission, all is good, just $c++ (counter)
4509 // - ...else, decrease the counter - so pagination is kept straight,
4510 // and (if we are in the page) remove from the results
4514 // pagination controls
4516 $limitfrom = (int)$limitfrom;
4517 $limitnum = (int)$limitnum;
4520 // Track our last user id so we know when we are dealing
4521 // with a new user...
4526 // $ras: role assignments, multidimensional array
4527 // treat as a stack - going from local to general
4528 // $ras = (( roleid=> x, $depth=>y) , ( roleid=> x, $depth=>y))
4530 while ($user = rs_fetch_next_record($rs)) {
4532 //error_log(" Record: " . print_r($user,1));
4535 // Pagination controls
4536 // Note that we might end up removing a user
4537 // that ends up _not_ having the rights,
4538 // therefore rolling back $c
4540 if ($lastuserid != $user->id
) {
4542 // Did the last user end up with a positive permission?
4543 if ($lastuserid !=0) {
4544 if ($defaultroleinteresting) {
4545 // add the role at the end of $ras
4546 $ras[] = array( 'roleid' => $CFG->defaultuserroleid
,
4549 if (has_capability_from_rarc($ras, $roleperms, $capability, $doanything)) {
4552 // remove the user from the result set,
4553 // only if we are 'in the page'
4554 if ($limitfrom === 0 ||
$c >= $limitfrom) {
4555 unset($results[$lastuserid]);
4560 // Did we hit pagination limit?
4561 if ($limitnum !==0 && $c >= ($limitfrom+
$limitnum)) { // we are done!
4565 // New user setup, and $ras reset
4566 $lastuserid = $user->id
;
4568 if (!empty($user->roleid
)) {
4569 $ras[] = array( 'roleid' => (int)$user->roleid
,
4570 'depth' => (int)$user->depth
);
4573 // if we are 'in the page', also add the rec
4574 // to the results...
4575 if ($limitfrom === 0 ||
$c >= $limitfrom) {
4576 $results[$user->id
] = $user; // trivial
4579 // Additional RA for $lastuserid
4580 $ras[] = array( 'roleid'=>(int)$user->roleid
,
4581 'depth'=>(int)$user->depth
);
4584 } // end while(fetch)
4586 // Prune last entry if necessary
4587 if ($lastuserid !=0) {
4588 if ($defaultroleinteresting) {
4589 // add the role at the end of $ras
4590 $ras[] = array( 'roleid' => $CFG->defaultuserroleid
,
4593 if (!has_capability_from_rarc($ras, $roleperms, $capability, $doanything)) {
4594 // remove the user from the result set,
4595 // only if we are 'in the page'
4596 if ($limitfrom === 0 ||
$c >= $limitfrom) {
4597 if (isset($results[$lastuserid])) {
4598 unset($results[$lastuserid]);
4608 * Fast (fast!) utility function to resolve if a capability is granted,
4609 * based on Role Assignments and Role Capabilities.
4611 * Used (at least) by get_users_by_capability().
4613 * If PHP had fast built-in memoize functions, we could
4614 * add a $contextid parameter and memoize the return values.
4616 * @param array $ras - role assignments
4617 * @param array $roleperms - role permissions
4618 * @param string $capability - name of the capability
4619 * @param bool $doanything
4623 function has_capability_from_rarc($ras, $roleperms, $capability, $doanything) {
4624 // Mini-state machine, using $hascap
4625 // $hascap[ 'moodle/foo:bar' ]->perm = CAP_SOMETHING (numeric constant)
4626 // $hascap[ 'moodle/foo:bar' ]->radepth = depth of the role assignment that set it
4627 // $hascap[ 'moodle/foo:bar' ]->rcdepth = depth of the rolecap that set it
4628 // -- when resolving conflicts, we need to look into radepth first, if unresolved
4630 $caps = array($capability);
4632 $caps[] = 'moodle/site:candoanything';
4638 // Compute which permission/roleassignment/rolecap
4639 // wins for each capability we are walking
4641 foreach ($ras as $ra) {
4642 foreach ($caps as $cap) {
4643 if (!isset($roleperms[$cap][$ra['roleid']])) {
4644 // nothing set for this cap - skip
4647 // We explicitly clone here as we
4648 // add more properties to it
4649 // that must stay separate from the
4650 // original roleperm data structure
4651 $rp = clone($roleperms[$cap][$ra['roleid']]);
4652 $rp->radepth
= $ra['depth'];
4654 // Trivial case, we are the first to set
4655 if (!isset($hascap[$cap])) {
4656 $hascap[$cap] = $rp;
4660 // Resolve who prevails, in order of precendence
4661 // - Prohibits always wins
4666 if ($rp->perm
=== CAP_PROHIBIT
) {
4667 $hascap[$cap] = $rp;
4670 if ($hascap[$cap]->perm
=== CAP_PROHIBIT
) {
4674 // Locality of RA - the look is ordered by depth DESC
4675 // so from local to general -
4676 // Higher RA loses to local RA... unless perm===0
4677 /// Thanks to the order of the records, $rp->radepth <= $hascap[$cap]->radepth
4678 if ($rp->radepth
> $hascap[$cap]->radepth
) {
4679 error_log('Should not happen @ ' . __FUNCTION__
.':'.__LINE__
);
4681 if ($rp->radepth
< $hascap[$cap]->radepth
) {
4682 if ($hascap[$cap]->perm
!==0) {
4683 // Wider RA loses to local RAs...
4686 // "Higher RA resolves conflict" case,
4687 // local RAs had cancelled eachother
4688 $hascap[$cap] = $rp;
4692 // Same ralevel - locality of RC wins
4693 if ($rp->rcdepth
> $hascap[$cap]->rcdepth
) {
4694 $hascap[$cap] = $rp;
4697 if ($rp->rcdepth
> $hascap[$cap]->rcdepth
) {
4700 // We match depth - add them
4701 $hascap[$cap]->perm +
= $rp->perm
;
4704 if ($hascap[$capability]->perm
> 0
4705 ||
($doanything && isset($hascap['moodle/site:candoanything'])
4706 && $hascap['moodle/site:candoanything']->perm
> 0)) {
4713 * Will re-sort a $users results array (from get_users_by_capability(), usually)
4714 * based on a sorting policy. This is to support the odd practice of
4715 * sorting teachers by 'authority', where authority was "lowest id of the role
4718 * Will execute 1 database query. Only suitable for small numbers of users, as it
4719 * uses an u.id IN() clause.
4721 * Notes about the sorting criteria.
4723 * As a default, we cannot rely on role.sortorder because then
4724 * admins/coursecreators will always win. That is why the sane
4725 * rule "is locality matters most", with sortorder as 2nd
4728 * If you want role.sortorder, use the 'sortorder' policy, and
4729 * name explicitly what roles you want to cover. It's probably
4730 * a good idea to see what roles have the capabilities you want
4731 * (array_diff() them against roiles that have 'can-do-anything'
4732 * to weed out admin-ish roles. Or fetch a list of roles from
4733 * variables like $CFG->coursemanagers .
4735 * @param array users Users' array, keyed on userid
4736 * @param object context
4737 * @param array roles - ids of the roles to include, optional
4738 * @param string policy - defaults to locality, more about
4739 * @return array - sorted copy of the array
4741 function sort_by_roleassignment_authority($users, $context, $roles=array(), $sortpolicy='locality') {
4744 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
4745 $contextwhere = ' ra.contextid IN ('.str_replace('/', ',',substr($context->path
, 1)).')';
4746 if (empty($roles)) {
4749 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
4752 $sql = "SELECT ra.userid
4753 FROM {$CFG->prefix}role_assignments ra
4754 JOIN {$CFG->prefix}role r
4756 JOIN {$CFG->prefix}context ctx
4757 ON ra.contextid=ctx.id
4764 // Default 'locality' policy -- read PHPDoc notes
4765 // about sort policies...
4766 $orderby = 'ORDER BY
4767 ctx.depth DESC, /* locality wins */
4768 r.sortorder ASC, /* rolesorting 2nd criteria */
4769 ra.id /* role assignment order tie-breaker */';
4770 if ($sortpolicy === 'sortorder') {
4771 $orderby = 'ORDER BY
4772 r.sortorder ASC, /* rolesorting 2nd criteria */
4773 ra.id /* role assignment order tie-breaker */';
4776 $sortedids = get_fieldset_sql($sql . $orderby);
4777 $sortedusers = array();
4780 foreach ($sortedids as $id) {
4782 if (isset($seen[$id])) {
4788 $sortedusers[$id] = $users[$id];
4790 return $sortedusers;
4794 * gets all the users assigned this role in this context or higher
4795 * @param int roleid (can also be an array of ints!)
4796 * @param int contextid
4797 * @param bool parent if true, get list of users assigned in higher context too
4798 * @param string fields - fields from user (u.) , role assignment (ra) or role (r.)
4799 * @param string sort - sort from user (u.) , role assignment (ra) or role (r.)
4800 * @param bool gethidden - whether to fetch hidden enrolments too
4803 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $gethidden=true, $group='', $limitfrom='', $limitnum='') {
4806 if (empty($fields)) {
4807 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
4808 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
4809 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4810 'u.emailstop, u.lang, u.timezone, r.name as rolename';
4813 // whether this assignment is hidden
4814 $hiddensql = $gethidden ?
'': ' AND ra.hidden = 0 ';
4816 $parentcontexts = '';
4818 $parentcontexts = substr($context->path
, 1); // kill leading slash
4819 $parentcontexts = str_replace('/', ',', $parentcontexts);
4820 if ($parentcontexts !== '') {
4821 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4825 if (is_array($roleid)) {
4826 $roleselect = ' AND ra.roleid IN (' . implode(',',$roleid) .')';
4827 } elseif (!empty($roleid)) { // should not test for int, because it can come in as a string
4828 $roleselect = "AND ra.roleid = $roleid";
4834 $groupjoin = "JOIN {$CFG->prefix}groups_members gm
4835 ON gm.userid = u.id";
4836 $groupselect = " AND gm.groupid = $group ";
4842 $SQL = "SELECT $fields, ra.roleid
4843 FROM {$CFG->prefix}role_assignments ra
4844 JOIN {$CFG->prefix}user u
4846 JOIN {$CFG->prefix}role r
4849 WHERE (ra.contextid = $context->id $parentcontexts)
4854 "; // join now so that we can just use fullname() later
4856 return get_records_sql($SQL, $limitfrom, $limitnum);
4860 * Counts all the users assigned this role in this context or higher
4862 * @param int contextid
4863 * @param bool parent if true, get list of users assigned in higher context too
4866 function count_role_users($roleid, $context, $parent=false) {
4870 if ($contexts = get_parent_contexts($context)) {
4871 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4873 $parentcontexts = '';
4876 $parentcontexts = '';
4879 $SQL = "SELECT count(u.id)
4880 FROM {$CFG->prefix}role_assignments r
4881 JOIN {$CFG->prefix}user u
4883 WHERE (r.contextid = $context->id $parentcontexts)
4884 AND r.roleid = $roleid
4887 return count_records_sql($SQL);
4891 * This function gets the list of courses that this user has a particular capability in.
4892 * It is still not very efficient.
4893 * @param string $capability Capability in question
4894 * @param int $userid User ID or null for current user
4895 * @param bool $doanything True if 'doanything' is permitted (default)
4896 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4897 * otherwise use a comma-separated list of the fields you require, not including id
4898 * @param string $orderby If set, use a comma-separated list of fields from course
4899 * table with sql modifiers (DESC) if needed
4900 * @return array Array of courses, may have zero entries. Or false if query failed.
4902 function get_user_capability_course($capability, $userid=NULL,$doanything=true,$fieldsexceptid='',$orderby='') {
4903 // Convert fields list and ordering
4905 if($fieldsexceptid) {
4906 $fields=explode(',',$fieldsexceptid);
4907 foreach($fields as $field) {
4908 $fieldlist.=',c.'.$field;
4912 $fields=explode(',',$orderby);
4914 foreach($fields as $field) {
4918 $orderby.='c.'.$field;
4920 $orderby='ORDER BY '.$orderby;
4923 // Obtain a list of everything relevant about all courses including context.
4924 // Note the result can be used directly as a context (we are going to), the course
4925 // fields are just appended.
4927 $rs=get_recordset_sql("
4929 x.*,c.id AS courseid$fieldlist
4931 {$CFG->prefix}course c
4932 INNER JOIN {$CFG->prefix}context x ON c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE
."
4939 // Check capability for each course in turn
4941 while($coursecontext=rs_fetch_next_record($rs)) {
4942 if(has_capability($capability,$coursecontext,$userid,$doanything)) {
4943 // We've got the capability. Make the record look like a course record
4945 $coursecontext->id
=$coursecontext->courseid
;
4946 unset($coursecontext->courseid
);
4947 unset($coursecontext->contextlevel
);
4948 unset($coursecontext->instanceid
);
4949 $courses[]=$coursecontext;
4955 /** This function finds the roles assigned directly to this context only
4956 * i.e. no parents role
4957 * @param object $context
4960 function get_roles_on_exact_context($context) {
4964 return get_records_sql("SELECT r.*
4965 FROM {$CFG->prefix}role_assignments ra,
4966 {$CFG->prefix}role r
4967 WHERE ra.roleid = r.id
4968 AND ra.contextid = $context->id");
4973 * Switches the current user to another role for the current session and only
4974 * in the given context.
4976 * The caller *must* check
4977 * - that this op is allowed
4978 * - that the requested role can be assigned in this ctx
4979 * (hint, use get_assignable_roles())
4980 * - that the requested role is NOT $CFG->defaultuserroleid
4982 * To "unswitch" pass 0 as the roleid.
4984 * This function *will* modify $USER->access - beware
4986 * @param integer $roleid
4987 * @param object $context
4990 function role_switch($roleid, $context) {
4996 // - Add the ghost RA to $USER->access
4997 // as $USER->access['rsw'][$path] = $roleid
4999 // - Make sure $USER->access['rdef'] has the roledefs
5000 // it needs to honour the switcheroo
5002 // Roledefs will get loaded "deep" here - down to the last child
5003 // context. Note that
5005 // - When visiting subcontexts, our selective accessdata loading
5006 // will still work fine - though those ra/rdefs will be ignored
5007 // appropriately while the switch is in place
5009 // - If a switcheroo happens at a category with tons of courses
5010 // (that have many overrides for switched-to role), the session
5011 // will get... quite large. Sometimes you just can't win.
5013 // To un-switch just unset($USER->access['rsw'][$path])
5016 // Add the switch RA
5017 if (!isset($USER->access
['rsw'])) {
5018 $USER->access
['rsw'] = array();
5022 unset($USER->access
['rsw'][$context->path
]);
5023 if (empty($USER->access
['rsw'])) {
5024 unset($USER->access
['rsw']);
5029 $USER->access
['rsw'][$context->path
]=$roleid;
5032 $USER->access
= get_role_access_bycontext($roleid, $context,
5035 /* DO WE NEED THIS AT ALL???
5036 // Add some permissions we are really going
5037 // to always need, even if the role doesn't have them!
5039 $USER->capabilities[$context->id]['moodle/course:view'] = CAP_ALLOW;
5046 // get any role that has an override on exact context
5047 function get_roles_with_override_on_context($context) {
5051 return get_records_sql("SELECT r.*
5052 FROM {$CFG->prefix}role_capabilities rc,
5053 {$CFG->prefix}role r
5054 WHERE rc.roleid = r.id
5055 AND rc.contextid = $context->id");
5058 // get all capabilities for this role on this context (overrids)
5059 function get_capabilities_from_role_on_context($role, $context) {
5063 return get_records_sql("SELECT *
5064 FROM {$CFG->prefix}role_capabilities
5065 WHERE contextid = $context->id
5066 AND roleid = $role->id");
5069 // find out which roles has assignment on this context
5070 function get_roles_with_assignment_on_context($context) {
5074 return get_records_sql("SELECT r.*
5075 FROM {$CFG->prefix}role_assignments ra,
5076 {$CFG->prefix}role r
5077 WHERE ra.roleid = r.id
5078 AND ra.contextid = $context->id");
5084 * Find all user assignemnt of users for this role, on this context
5086 function get_users_from_role_on_context($role, $context) {
5090 return get_records_sql("SELECT *
5091 FROM {$CFG->prefix}role_assignments
5092 WHERE contextid = $context->id
5093 AND roleid = $role->id");
5097 * Simple function returning a boolean true if roles exist, otherwise false
5099 function user_has_role_assignment($userid, $roleid, $contextid=0) {
5102 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
5104 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
5109 * Get role name or alias if exists and format the text.
5110 * @param object $role role object
5111 * @param object $coursecontext
5112 * @return $string name of role in course context
5114 function role_get_name($role, $coursecontext) {
5115 if ($r = get_record('role_names','roleid', $role->id
,'contextid', $coursecontext->id
)) {
5116 return strip_tags(format_string($r->name
));
5118 return strip_tags(format_string($role->name
));
5123 * Prepare list of roles for display, apply aliases and format text
5124 * @param array $roleoptions array roleid=>rolename
5125 * @param object $context
5126 * @return array of role names
5128 function role_fix_names($roleoptions, $context, $rolenamedisplay=ROLENAME_ALIAS
) {
5129 if ($rolenamedisplay != ROLENAME_ORIGINAL
&& !empty($context->id
)) {
5130 if ($context->contextlevel
== CONTEXT_MODULE ||
$context->contextlevel
== CONTEXT_BLOCK
) { // find the parent course context
5131 if ($parentcontextid = array_shift(get_parent_contexts($context))) {
5132 $context = get_context_instance_by_id($parentcontextid);
5135 if ($aliasnames = get_records('role_names', 'contextid', $context->id
)) {
5136 if ($rolenamedisplay == ROLENAME_ALIAS
) {
5137 foreach ($aliasnames as $alias) {
5138 if (isset($roleoptions[$alias->roleid
])) {
5139 $roleoptions[$alias->roleid
] = format_string($alias->name
);
5142 } else if ($rolenamedisplay == ROLENAME_BOTH
) {
5143 foreach ($aliasnames as $alias) {
5144 if (isset($roleoptions[$alias->roleid
])) {
5145 $roleoptions[$alias->roleid
] = format_string($alias->name
).' ('.format_string($roleoptions[$alias->roleid
]).')';
5151 foreach ($roleoptions as $rid => $name) {
5152 $roleoptions[$rid] = strip_tags($name);
5154 return $roleoptions;
5158 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
5159 * when we read in a new capability
5160 * most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
5161 * but when we are in grade, all reports/import/export capabilites should be together
5162 * @param string a - component string a
5163 * @param string b - component string b
5164 * @return bool - whether 2 component are in different "sections"
5166 function component_level_changed($cap, $comp, $contextlevel) {
5168 if ($cap->component
== 'enrol/authorize' && $comp =='enrol/authorize') {
5172 if (strstr($cap->component
, '/') && strstr($comp, '/')) {
5173 $compsa = explode('/', $cap->component
);
5174 $compsb = explode('/', $comp);
5178 // we are in gradebook, still
5179 if (($compsa[0] == 'gradeexport' ||
$compsa[0] == 'gradeimport' ||
$compsa[0] == 'gradereport') &&
5180 ($compsb[0] == 'gradeexport' ||
$compsb[0] == 'gradeimport' ||
$compsb[0] == 'gradereport')) {
5185 return ($cap->component
!= $comp ||
$cap->contextlevel
!= $contextlevel);
5189 * Populate context.path and context.depth where missing.
5190 * @param bool $force force a complete rebuild of the path and depth fields.
5191 * @param bool $feedback display feedback (during upgrade usually)
5194 function build_context_path($force=false, $feedback=false) {
5196 require_once($CFG->libdir
.'/ddllib.php');
5199 $sitectx = get_system_context(!$force);
5200 $base = '/'.$sitectx->id
;
5203 $sitecoursectx = get_record('context',
5204 'contextlevel', CONTEXT_COURSE
,
5205 'instanceid', SITEID
);
5206 if ($force ||
$sitecoursectx->path
!== "$base/{$sitecoursectx->id}") {
5207 set_field('context', 'path', "$base/{$sitecoursectx->id}",
5208 'id', $sitecoursectx->id
);
5209 set_field('context', 'depth', 2,
5210 'id', $sitecoursectx->id
);
5211 $sitecoursectx = get_record('context',
5212 'contextlevel', CONTEXT_COURSE
,
5213 'instanceid', SITEID
);
5216 $ctxemptyclause = " AND (ctx.path IS NULL
5218 $emptyclause = " AND ({$CFG->prefix}context.path IS NULL
5219 OR {$CFG->prefix}context.depth=0) ";
5221 $ctxemptyclause = $emptyclause = '';
5225 * - mysql does not allow to use FROM in UPDATE statements
5226 * - using two tables after UPDATE works in mysql, but might give unexpected
5227 * results in pg 8 (depends on configuration)
5228 * - using table alias in UPDATE does not work in pg < 8.2
5230 if ($CFG->dbfamily
== 'mysql') {
5231 $updatesql = "UPDATE {$CFG->prefix}context ct, {$CFG->prefix}context_temp temp
5232 SET ct.path = temp.path,
5233 ct.depth = temp.depth
5234 WHERE ct.id = temp.id";
5235 } else if ($CFG->dbfamily
== 'oracle') {
5236 $updatesql = "UPDATE {$CFG->prefix}context ct
5237 SET (ct.path, ct.depth) =
5238 (SELECT temp.path, temp.depth
5239 FROM {$CFG->prefix}context_temp temp
5240 WHERE temp.id=ct.id)
5241 WHERE EXISTS (SELECT 'x'
5242 FROM {$CFG->prefix}context_temp temp
5243 WHERE temp.id = ct.id)";
5245 $updatesql = "UPDATE {$CFG->prefix}context
5246 SET path = temp.path,
5248 FROM {$CFG->prefix}context_temp temp
5249 WHERE temp.id={$CFG->prefix}context.id";
5252 $udelsql = "TRUNCATE TABLE {$CFG->prefix}context_temp";
5254 // Top level categories
5255 $sql = "UPDATE {$CFG->prefix}context
5256 SET depth=2, path=" . sql_concat("'$base/'", 'id') . "
5257 WHERE contextlevel=".CONTEXT_COURSECAT
."
5258 AND EXISTS (SELECT 'x'
5259 FROM {$CFG->prefix}course_categories cc
5260 WHERE cc.id = {$CFG->prefix}context.instanceid
5264 execute_sql($sql, $feedback);
5266 execute_sql($udelsql, $feedback);
5268 // Deeper categories - one query per depthlevel
5269 $maxdepth = get_field_sql("SELECT MAX(depth)
5270 FROM {$CFG->prefix}course_categories");
5271 for ($n=2;$n<=$maxdepth;$n++
) {
5272 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5273 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", $n+1
5274 FROM {$CFG->prefix}context ctx
5275 JOIN {$CFG->prefix}course_categories c ON ctx.instanceid=c.id
5276 JOIN {$CFG->prefix}context pctx ON c.parent=pctx.instanceid
5277 WHERE ctx.contextlevel=".CONTEXT_COURSECAT
."
5278 AND pctx.contextlevel=".CONTEXT_COURSECAT
."
5280 AND NOT EXISTS (SELECT 'x'
5281 FROM {$CFG->prefix}context_temp temp
5282 WHERE temp.id = ctx.id)
5284 execute_sql($sql, $feedback);
5286 // this is needed after every loop
5288 execute_sql($updatesql, $feedback);
5289 execute_sql($udelsql, $feedback);
5292 // Courses -- except sitecourse
5293 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5294 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5295 FROM {$CFG->prefix}context ctx
5296 JOIN {$CFG->prefix}course c ON ctx.instanceid=c.id
5297 JOIN {$CFG->prefix}context pctx ON c.category=pctx.instanceid
5298 WHERE ctx.contextlevel=".CONTEXT_COURSE
."
5299 AND c.id!=".SITEID
."
5300 AND pctx.contextlevel=".CONTEXT_COURSECAT
."
5301 AND NOT EXISTS (SELECT 'x'
5302 FROM {$CFG->prefix}context_temp temp
5303 WHERE temp.id = ctx.id)
5305 execute_sql($sql, $feedback);
5307 execute_sql($updatesql, $feedback);
5308 execute_sql($udelsql, $feedback);
5311 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5312 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5313 FROM {$CFG->prefix}context ctx
5314 JOIN {$CFG->prefix}course_modules cm ON ctx.instanceid=cm.id
5315 JOIN {$CFG->prefix}context pctx ON cm.course=pctx.instanceid
5316 WHERE ctx.contextlevel=".CONTEXT_MODULE
."
5317 AND pctx.contextlevel=".CONTEXT_COURSE
."
5318 AND NOT EXISTS (SELECT 'x'
5319 FROM {$CFG->prefix}context_temp temp
5320 WHERE temp.id = ctx.id)
5322 execute_sql($sql, $feedback);
5324 execute_sql($updatesql, $feedback);
5325 execute_sql($udelsql, $feedback);
5327 // Blocks - non-pinned course-view only
5328 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5329 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5330 FROM {$CFG->prefix}context ctx
5331 JOIN {$CFG->prefix}block_instance bi ON ctx.instanceid = bi.id
5332 JOIN {$CFG->prefix}context pctx ON bi.pageid=pctx.instanceid
5333 WHERE ctx.contextlevel=".CONTEXT_BLOCK
."
5334 AND pctx.contextlevel=".CONTEXT_COURSE
."
5335 AND bi.pagetype='course-view'
5336 AND NOT EXISTS (SELECT 'x'
5337 FROM {$CFG->prefix}context_temp temp
5338 WHERE temp.id = ctx.id)
5340 execute_sql($sql, $feedback);
5342 execute_sql($updatesql, $feedback);
5343 execute_sql($udelsql, $feedback);
5346 $sql = "UPDATE {$CFG->prefix}context
5347 SET depth=2, path=".sql_concat("'$base/'", 'id')."
5348 WHERE contextlevel=".CONTEXT_BLOCK
."
5349 AND EXISTS (SELECT 'x'
5350 FROM {$CFG->prefix}block_instance bi
5351 WHERE bi.id = {$CFG->prefix}context.instanceid
5352 AND bi.pagetype!='course-view')
5354 execute_sql($sql, $feedback);
5357 $sql = "UPDATE {$CFG->prefix}context
5358 SET depth=2, path=".sql_concat("'$base/'", 'id')."
5359 WHERE contextlevel=".CONTEXT_USER
."
5360 AND EXISTS (SELECT 'x'
5361 FROM {$CFG->prefix}user u
5362 WHERE u.id = {$CFG->prefix}context.instanceid)
5364 execute_sql($sql, $feedback);
5368 //TODO: fix group contexts
5370 // reset static course cache - it might have incorrect cached data
5371 global $context_cache, $context_cache_id;
5372 $context_cache = array();
5373 $context_cache_id = array();
5378 * Update the path field of the context and
5379 * all the dependent subcontexts that follow
5382 * The most important thing here is to be as
5383 * DB efficient as possible. This op can have a
5384 * massive impact in the DB.
5386 * @param obj current context obj
5387 * @param obj newparent new parent obj
5390 function context_moved($context, $newparent) {
5393 $frompath = $context->path
;
5394 $newpath = $newparent->path
. '/' . $context->id
;
5397 if (($newparent->depth +
1) != $context->depth
) {
5398 $setdepth = ", depth= depth + ({$newparent->depth} - {$context->depth}) + 1";
5400 $sql = "UPDATE {$CFG->prefix}context
5403 WHERE path='$frompath'";
5404 execute_sql($sql,false);
5406 $len = strlen($frompath);
5407 $sql = "UPDATE {$CFG->prefix}context
5408 SET path = ".sql_concat("'$newpath'", 'SUBSTR(path, '.$len.' +1)')."
5410 WHERE path LIKE '{$frompath}/%'";
5411 execute_sql($sql,false);
5413 mark_context_dirty($frompath);
5414 mark_context_dirty($newpath);
5419 * Turn the ctx* fields in an objectlike record
5420 * into a context subobject. This allows
5421 * us to SELECT from major tables JOINing with
5422 * context at no cost, saving a ton of context
5425 function make_context_subobj($rec) {
5426 $ctx = new StdClass
;
5427 $ctx->id
= $rec->ctxid
; unset($rec->ctxid
);
5428 $ctx->path
= $rec->ctxpath
; unset($rec->ctxpath
);
5429 $ctx->depth
= $rec->ctxdepth
; unset($rec->ctxdepth
);
5430 $ctx->contextlevel
= $rec->ctxlevel
; unset($rec->ctxlevel
);
5431 $ctx->instanceid
= $rec->id
;
5433 $rec->context
= $ctx;
5438 * Fetch recent dirty contexts to know cheaply whether our $USER->access
5439 * is stale and needs to be reloaded.
5443 * @return array of dirty contexts
5445 function get_dirty_contexts($time) {
5446 return get_cache_flags('accesslib/dirtycontexts', $time-2);
5450 * Mark a context as dirty (with timestamp)
5451 * so as to force reloading of the context.
5452 * @param string $path context path
5454 function mark_context_dirty($path) {
5455 global $CFG, $DIRTYCONTEXTS;
5456 // only if it is a non-empty string
5457 if (is_string($path) && $path !== '') {
5458 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+
$CFG->sessiontimeout
);
5459 if (isset($DIRTYCONTEXTS)) {
5460 $DIRTYCONTEXTS[$path] = 1;
5466 * Will walk the contextpath to answer whether
5467 * the contextpath is dirty
5469 * @param array $contexts array of strings
5470 * @param obj/array dirty contexts from get_dirty_contexts()
5473 function is_contextpath_dirty($pathcontexts, $dirty) {
5475 foreach ($pathcontexts as $ctx) {
5476 $path = $path.'/'.$ctx;
5477 if (isset($dirty[$path])) {
5486 * switch role order (used in admin/roles/manage.php)
5488 * @param int $first id of role to move down
5489 * @param int $second id of role to move up
5491 * @return bool success or failure
5493 function switch_roles($first, $second) {
5495 //first find temorary sortorder number
5496 $tempsort = count_records('role') +
3;
5497 while (get_record('role','sortorder', $tempsort)) {
5502 $r1->id
= $first->id
;
5503 $r1->sortorder
= $tempsort;
5505 $r2->id
= $second->id
;
5506 $r2->sortorder
= $first->sortorder
;
5508 if (!update_record('role', $r1)) {
5509 debugging("Can not update role with ID $r1->id!");
5513 if (!update_record('role', $r2)) {
5514 debugging("Can not update role with ID $r2->id!");
5518 $r1->sortorder
= $second->sortorder
;
5519 if (!update_record('role', $r1)) {
5520 debugging("Can not update role with ID $r1->id!");
5528 * duplicates all the base definitions of a role
5530 * @param object $sourcerole role to copy from
5531 * @param int $targetrole id of role to copy to
5535 function role_cap_duplicate($sourcerole, $targetrole) {
5537 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
5538 $caps = get_records_sql("SELECT * FROM {$CFG->prefix}role_capabilities
5539 WHERE roleid = $sourcerole->id
5540 AND contextid = $systemcontext->id");
5541 // adding capabilities
5542 foreach ($caps as $cap) {
5544 $cap->roleid
= $targetrole;
5545 insert_record('role_capabilities', $cap);