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 $courses = explode('/',get_course_from_path($context->path
));
1257 $targetid = array_pop($courses);
1258 $context = get_context_instance_by_id($targetid);
1263 // Role assignments in the context and below
1265 $sql = "SELECT ctx.path, ra.roleid
1266 FROM {$CFG->prefix}role_assignments ra
1267 JOIN {$CFG->prefix}context ctx
1268 ON ra.contextid=ctx.id
1269 WHERE ra.userid = $userid
1270 AND (ctx.path = '{$context->path}' OR ctx.path LIKE '{$context->path}/%')
1271 ORDER BY ctx.depth, ctx.path";
1272 $rs = get_recordset_sql($sql);
1277 $localroles = array();
1278 while ($ra = rs_fetch_next_record($rs)) {
1279 if (!isset($accessdata['ra'][$ra->path
])) {
1280 $accessdata['ra'][$ra->path
] = array();
1282 array_push($accessdata['ra'][$ra->path
], $ra->roleid
);
1283 array_push($localroles, $ra->roleid
);
1288 // Walk up and down the tree to grab all the roledefs
1289 // of interest to our user...
1292 // - we use IN() but the number of roles is very limited.
1294 $courseroles = aggregate_roles_from_accessdata($context, $accessdata);
1296 // Do we have any interesting "local" roles?
1297 $localroles = array_diff($localroles,$courseroles); // only "new" local roles
1298 $wherelocalroles='';
1299 if (count($localroles)) {
1300 // Role defs for local roles in 'higher' contexts...
1301 $contexts = substr($context->path
, 1); // kill leading slash
1302 $contexts = str_replace('/', ',', $contexts);
1303 $localroleids = implode(',',$localroles);
1304 $wherelocalroles="OR (rc.roleid IN ({$localroleids})
1305 AND ctx.id IN ($contexts))" ;
1308 // We will want overrides for all of them
1310 if ($roleids = implode(',',array_merge($courseroles,$localroles))) {
1311 $whereroles = "rc.roleid IN ($roleids) AND";
1313 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1314 FROM {$CFG->prefix}role_capabilities rc
1315 JOIN {$CFG->prefix}context ctx
1316 ON rc.contextid=ctx.id
1318 (ctx.id={$context->id} OR ctx.path LIKE '{$context->path}/%'))
1320 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1322 $newrdefs = array();
1323 if ($rs = get_recordset_sql($sql)) {
1324 while ($rd = rs_fetch_next_record($rs)) {
1325 $k = "{$rd->path}:{$rd->roleid}";
1326 if (!array_key_exists($k, $newrdefs)) {
1327 $newrdefs[$k] = array();
1329 $newrdefs[$k][$rd->capability
] = $rd->permission
;
1333 debugging('Bad SQL encountered!');
1336 compact_rdefs($newrdefs);
1337 foreach ($newrdefs as $key=>$value) {
1338 $accessdata['rdef'][$key] =& $newrdefs[$key];
1341 // error_log("loaded {$context->path}");
1342 $accessdata['loaded'][] = $context->path
;
1346 * It add to the access ctrl array the data
1347 * needed by a role for a given context.
1349 * The data is added in the rdef key.
1351 * This role-centric function is useful for role_switching
1352 * and to get an overview of what a role gets under a
1353 * given context and below...
1355 * @param $roleid integer - the id of the user
1356 * @param $context context obj - needs path!
1357 * @param $accessdata accessdata array
1360 function get_role_access_bycontext($roleid, $context, $accessdata=NULL) {
1364 /* Get the relevant rolecaps into rdef
1365 * - relevant role caps
1366 * - at ctx and above
1370 if (is_null($accessdata)) {
1371 $accessdata = array(); // named list
1372 $accessdata['ra'] = array();
1373 $accessdata['rdef'] = array();
1374 $accessdata['loaded'] = array();
1377 $contexts = substr($context->path
, 1); // kill leading slash
1378 $contexts = str_replace('/', ',', $contexts);
1381 // Walk up and down the tree to grab all the roledefs
1382 // of interest to our role...
1384 // NOTE: we use an IN clauses here - which
1385 // might explode on huge sites with very convoluted nesting of
1386 // categories... - extremely unlikely that the number of nested
1387 // categories is so large that we hit the limits of IN()
1389 $sql = "SELECT ctx.path, rc.capability, rc.permission
1390 FROM {$CFG->prefix}role_capabilities rc
1391 JOIN {$CFG->prefix}context ctx
1392 ON rc.contextid=ctx.id
1393 WHERE rc.roleid=$roleid AND
1394 ( ctx.id IN ($contexts) OR
1395 ctx.path LIKE '{$context->path}/%' )
1396 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1398 $rs = get_recordset_sql($sql);
1399 while ($rd = rs_fetch_next_record($rs)) {
1400 $k = "{$rd->path}:{$roleid}";
1401 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
1409 * Load accessdata for a user
1410 * into the $ACCESS global
1412 * Used by has_capability() - but feel free
1413 * to call it if you are about to run a BIG
1414 * cron run across a bazillion users.
1417 function load_user_accessdata($userid) {
1418 global $ACCESS,$CFG;
1420 $base = '/'.SYSCONTEXTID
;
1422 $accessdata = get_user_access_sitewide($userid);
1423 $frontpagecontext = get_context_instance(CONTEXT_COURSE
, SITEID
);
1425 // provide "default role" & set 'dr'
1427 if (!empty($CFG->defaultuserroleid
)) {
1428 $accessdata = get_role_access($CFG->defaultuserroleid
, $accessdata);
1429 if (!isset($accessdata['ra'][$base])) {
1430 $accessdata['ra'][$base] = array($CFG->defaultuserroleid
);
1432 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid
);
1434 $accessdata['dr'] = $CFG->defaultuserroleid
;
1438 // provide "default frontpage role"
1440 if (!empty($CFG->defaultfrontpageroleid
)) {
1441 $base = '/'. SYSCONTEXTID
.'/'. $frontpagecontext->id
;
1442 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid
, $accessdata);
1443 if (!isset($accessdata['ra'][$base])) {
1444 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid
);
1446 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid
);
1449 // for dirty timestamps in cron
1450 $accessdata['time'] = time();
1452 $ACCESS[$userid] = $accessdata;
1453 compact_rdefs($ACCESS[$userid]['rdef']);
1459 * Use shared copy of role definistions stored in $RDEFS;
1460 * @param array $rdefs array of role definitions in contexts
1462 function compact_rdefs(&$rdefs) {
1466 * This is a basic sharing only, we could also
1467 * use md5 sums of values. The main purpose is to
1468 * reduce mem in cron jobs - many users in $ACCESS array.
1471 foreach ($rdefs as $key => $value) {
1472 if (!array_key_exists($key, $RDEFS)) {
1473 $RDEFS[$key] = $rdefs[$key];
1475 $rdefs[$key] =& $RDEFS[$key];
1480 * A convenience function to completely load all the capabilities
1481 * for the current user. This is what gets called from complete_user_login()
1482 * for example. Call it only _after_ you've setup $USER and called
1483 * check_enrolment_plugins();
1486 function load_all_capabilities() {
1487 global $USER, $CFG, $DIRTYCONTEXTS;
1489 $base = '/'.SYSCONTEXTID
;
1491 if (isguestuser()) {
1492 $guest = get_guest_role();
1495 $USER->access
= get_role_access($guest->id
);
1496 // Put the ghost enrolment in place...
1497 $USER->access
['ra'][$base] = array($guest->id
);
1500 } else if (isloggedin()) {
1502 $accessdata = get_user_access_sitewide($USER->id
);
1505 // provide "default role" & set 'dr'
1507 if (!empty($CFG->defaultuserroleid
)) {
1508 $accessdata = get_role_access($CFG->defaultuserroleid
, $accessdata);
1509 if (!isset($accessdata['ra'][$base])) {
1510 $accessdata['ra'][$base] = array($CFG->defaultuserroleid
);
1512 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid
);
1514 $accessdata['dr'] = $CFG->defaultuserroleid
;
1517 $frontpagecontext = get_context_instance(CONTEXT_COURSE
, SITEID
);
1520 // provide "default frontpage role"
1522 if (!empty($CFG->defaultfrontpageroleid
)) {
1523 $base = '/'. SYSCONTEXTID
.'/'. $frontpagecontext->id
;
1524 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid
, $accessdata);
1525 if (!isset($accessdata['ra'][$base])) {
1526 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid
);
1528 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid
);
1531 $USER->access
= $accessdata;
1533 } else if (!empty($CFG->notloggedinroleid
)) {
1534 $USER->access
= get_role_access($CFG->notloggedinroleid
);
1535 $USER->access
['ra'][$base] = array($CFG->notloggedinroleid
);
1538 // Timestamp to read dirty context timestamps later
1539 $USER->access
['time'] = time();
1540 $DIRTYCONTEXTS = array();
1542 // Clear to force a refresh
1543 unset($USER->mycourses
);
1547 * A convenience function to completely reload all the capabilities
1548 * for the current user when roles have been updated in a relevant
1549 * context -- but PRESERVING switchroles and loginas.
1551 * That is - completely transparent to the user.
1553 * Note: rewrites $USER->access completely.
1556 function reload_all_capabilities() {
1559 // error_log("reloading");
1562 if (isset($USER->access
['rsw'])) {
1563 $sw = $USER->access
['rsw'];
1564 // error_log(print_r($sw,1));
1567 unset($USER->access
);
1568 unset($USER->mycourses
);
1570 load_all_capabilities();
1572 foreach ($sw as $path => $roleid) {
1573 $context = get_record('context', 'path', $path);
1574 role_switch($roleid, $context);
1580 * Adds a temp role to an accessdata array.
1582 * Useful for the "temporary guest" access
1583 * we grant to logged-in users.
1585 * Note - assumes a course context!
1588 function load_temp_role($context, $roleid, $accessdata) {
1593 // Load rdefs for the role in -
1595 // - all the parents
1596 // - and below - IOWs overrides...
1599 // turn the path into a list of context ids
1600 $contexts = substr($context->path
, 1); // kill leading slash
1601 $contexts = str_replace('/', ',', $contexts);
1603 $sql = "SELECT ctx.path,
1604 rc.capability, rc.permission
1605 FROM {$CFG->prefix}context ctx
1606 JOIN {$CFG->prefix}role_capabilities rc
1607 ON rc.contextid=ctx.id
1608 WHERE (ctx.id IN ($contexts)
1609 OR ctx.path LIKE '{$context->path}/%')
1610 AND rc.roleid = {$roleid}
1611 ORDER BY ctx.depth, ctx.path";
1612 $rs = get_recordset_sql($sql);
1613 while ($rd = rs_fetch_next_record($rs)) {
1614 $k = "{$rd->path}:{$roleid}";
1615 $accessdata['rdef'][$k][$rd->capability
] = $rd->permission
;
1620 // Say we loaded everything for the course context
1621 // - which we just did - if the user gets a proper
1622 // RA in this session, this data will need to be reloaded,
1623 // but that is handled by the complete accessdata reload
1625 array_push($accessdata['loaded'], $context->path
);
1630 if (isset($accessdata['ra'][$context->path
])) {
1631 array_push($accessdata['ra'][$context->path
], $roleid);
1633 $accessdata['ra'][$context->path
] = array($roleid);
1641 * Check all the login enrolment information for the given user object
1642 * by querying the enrolment plugins
1644 function check_enrolment_plugins(&$user) {
1647 static $inprogress; // To prevent this function being called more than once in an invocation
1649 if (!empty($inprogress[$user->id
])) {
1653 $inprogress[$user->id
] = true; // Set the flag
1655 require_once($CFG->dirroot
.'/enrol/enrol.class.php');
1657 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled
))) {
1658 $plugins = array($CFG->enrol
);
1661 foreach ($plugins as $plugin) {
1662 $enrol = enrolment_factory
::factory($plugin);
1663 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1664 $enrol->setup_enrolments($user);
1665 } else { /// Run legacy enrolment methods
1666 if (method_exists($enrol, 'get_student_courses')) {
1667 $enrol->get_student_courses($user);
1669 if (method_exists($enrol, 'get_teacher_courses')) {
1670 $enrol->get_teacher_courses($user);
1673 /// deal with $user->students and $user->teachers stuff
1674 unset($user->student
);
1675 unset($user->teacher
);
1680 unset($inprogress[$user->id
]); // Unset the flag
1684 * Installs the roles system.
1685 * This function runs on a fresh install as well as on an upgrade from the old
1686 * hard-coded student/teacher/admin etc. roles to the new roles system.
1688 function moodle_install_roles() {
1692 /// Create a system wide context for assignemnt.
1693 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM
);
1696 /// Create default/legacy roles and capabilities.
1697 /// (1 legacy capability per legacy role at system level).
1699 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1700 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1701 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1702 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1703 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1704 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1705 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1706 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1707 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1708 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1709 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1710 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
1711 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1712 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
1714 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1716 if (!assign_capability('moodle/site:doanything', CAP_ALLOW
, $adminrole, $systemcontext->id
)) {
1717 error('Could not assign moodle/site:doanything to the admin role');
1719 if (!update_capabilities()) {
1720 error('Had trouble upgrading the core capabilities for the Roles System');
1723 /// Look inside user_admin, user_creator, user_teachers, user_students and
1724 /// assign above new roles. If a user has both teacher and student role,
1725 /// only teacher role is assigned. The assignment should be system level.
1727 $dbtables = $db->MetaTables('TABLES');
1729 /// Set up the progress bar
1731 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1733 $totalcount = $progresscount = 0;
1734 foreach ($usertables as $usertable) {
1735 if (in_array($CFG->prefix
.$usertable, $dbtables)) {
1736 $totalcount +
= count_records($usertable);
1740 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1742 /// Upgrade the admins.
1743 /// Sort using id ASC, first one is primary admin.
1745 if (in_array($CFG->prefix
.'user_admins', $dbtables)) {
1746 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix
.'user_admins ORDER BY ID ASC')) {
1747 while ($admin = rs_fetch_next_record($rs)) {
1748 role_assign($adminrole, $admin->userid
, 0, $systemcontext->id
);
1750 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1755 // This is a fresh install.
1759 /// Upgrade course creators.
1760 if (in_array($CFG->prefix
.'user_coursecreators', $dbtables)) {
1761 if ($rs = get_recordset('user_coursecreators')) {
1762 while ($coursecreator = rs_fetch_next_record($rs)) {
1763 role_assign($coursecreatorrole, $coursecreator->userid
, 0, $systemcontext->id
);
1765 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1772 /// Upgrade editting teachers and non-editting teachers.
1773 if (in_array($CFG->prefix
.'user_teachers', $dbtables)) {
1774 if ($rs = get_recordset('user_teachers')) {
1775 while ($teacher = rs_fetch_next_record($rs)) {
1777 // removed code here to ignore site level assignments
1778 // since the contexts are separated now
1780 // populate the user_lastaccess table
1781 $access = new object();
1782 $access->timeaccess
= $teacher->timeaccess
;
1783 $access->userid
= $teacher->userid
;
1784 $access->courseid
= $teacher->course
;
1785 insert_record('user_lastaccess', $access);
1787 // assign the default student role
1788 $coursecontext = get_context_instance(CONTEXT_COURSE
, $teacher->course
); // needs cache
1790 if ($teacher->authority
== 0) {
1796 if ($teacher->editall
) { // editting teacher
1797 role_assign($editteacherrole, $teacher->userid
, 0, $coursecontext->id
, $teacher->timestart
, $teacher->timeend
, $hiddenteacher, $teacher->enrol
, $teacher->timemodified
);
1799 role_assign($noneditteacherrole, $teacher->userid
, 0, $coursecontext->id
, $teacher->timestart
, $teacher->timeend
, $hiddenteacher, $teacher->enrol
, $teacher->timemodified
);
1802 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1809 /// Upgrade students.
1810 if (in_array($CFG->prefix
.'user_students', $dbtables)) {
1811 if ($rs = get_recordset('user_students')) {
1812 while ($student = rs_fetch_next_record($rs)) {
1814 // populate the user_lastaccess table
1815 $access = new object;
1816 $access->timeaccess
= $student->timeaccess
;
1817 $access->userid
= $student->userid
;
1818 $access->courseid
= $student->course
;
1819 insert_record('user_lastaccess', $access);
1821 // assign the default student role
1822 $coursecontext = get_context_instance(CONTEXT_COURSE
, $student->course
);
1823 role_assign($studentrole, $student->userid
, 0, $coursecontext->id
, $student->timestart
, $student->timeend
, 0, $student->enrol
, $student->time
);
1825 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1832 /// Upgrade guest (only 1 entry).
1833 if ($guestuser = get_record('user', 'username', 'guest')) {
1834 role_assign($guestrole, $guestuser->id
, 0, $systemcontext->id
);
1836 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1839 /// Insert the correct records for legacy roles
1840 allow_assign($adminrole, $adminrole);
1841 allow_assign($adminrole, $coursecreatorrole);
1842 allow_assign($adminrole, $noneditteacherrole);
1843 allow_assign($adminrole, $editteacherrole);
1844 allow_assign($adminrole, $studentrole);
1845 allow_assign($adminrole, $guestrole);
1847 allow_assign($coursecreatorrole, $noneditteacherrole);
1848 allow_assign($coursecreatorrole, $editteacherrole);
1849 allow_assign($coursecreatorrole, $studentrole);
1850 allow_assign($coursecreatorrole, $guestrole);
1852 allow_assign($editteacherrole, $noneditteacherrole);
1853 allow_assign($editteacherrole, $studentrole);
1854 allow_assign($editteacherrole, $guestrole);
1856 /// Set up default permissions for overrides
1857 allow_override($adminrole, $adminrole);
1858 allow_override($adminrole, $coursecreatorrole);
1859 allow_override($adminrole, $noneditteacherrole);
1860 allow_override($adminrole, $editteacherrole);
1861 allow_override($adminrole, $studentrole);
1862 allow_override($adminrole, $guestrole);
1863 allow_override($adminrole, $userrole);
1866 /// Delete the old user tables when we are done
1868 $tables = array('user_students', 'user_teachers', 'user_coursecreators', 'user_admins');
1869 foreach ($tables as $tablename) {
1870 $table = new XMLDBTable($tablename);
1871 if (table_exists($table)) {
1878 * Returns array of all legacy roles.
1880 function get_legacy_roles() {
1882 'admin' => 'moodle/legacy:admin',
1883 'coursecreator' => 'moodle/legacy:coursecreator',
1884 'editingteacher' => 'moodle/legacy:editingteacher',
1885 'teacher' => 'moodle/legacy:teacher',
1886 'student' => 'moodle/legacy:student',
1887 'guest' => 'moodle/legacy:guest',
1888 'user' => 'moodle/legacy:user'
1892 function get_legacy_type($roleid) {
1893 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
1894 $legacyroles = get_legacy_roles();
1897 foreach($legacyroles as $ltype=>$lcap) {
1898 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
1899 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
1900 //choose first selected legacy capability - reset the rest
1901 if (empty($result)) {
1904 unassign_capability($lcap, $roleid);
1913 * Assign the defaults found in this capabality definition to roles that have
1914 * the corresponding legacy capabilities assigned to them.
1915 * @param $legacyperms - an array in the format (example):
1916 * 'guest' => CAP_PREVENT,
1917 * 'student' => CAP_ALLOW,
1918 * 'teacher' => CAP_ALLOW,
1919 * 'editingteacher' => CAP_ALLOW,
1920 * 'coursecreator' => CAP_ALLOW,
1921 * 'admin' => CAP_ALLOW
1922 * @return boolean - success or failure.
1924 function assign_legacy_capabilities($capability, $legacyperms) {
1926 $legacyroles = get_legacy_roles();
1928 foreach ($legacyperms as $type => $perm) {
1930 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
1932 if (!array_key_exists($type, $legacyroles)) {
1933 error('Incorrect legacy role definition for type: '.$type);
1936 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW
)) {
1937 foreach ($roles as $role) {
1938 // Assign a site level capability.
1939 if (!assign_capability($capability, $perm, $role->id
, $systemcontext->id
)) {
1950 * Checks to see if a capability is a legacy capability.
1951 * @param $capabilityname
1954 function islegacy($capabilityname) {
1955 if (strpos($capabilityname, 'moodle/legacy') === 0) {
1964 /**********************************
1965 * Context Manipulation functions *
1966 **********************************/
1969 * Create a new context record for use by all roles-related stuff
1970 * assumes that the caller has done the homework.
1973 * @param $instanceid
1975 * @return object newly created context
1977 function create_context($contextlevel, $instanceid) {
1981 if ($contextlevel == CONTEXT_SYSTEM
) {
1982 return create_system_context();
1985 $context = new object();
1986 $context->contextlevel
= $contextlevel;
1987 $context->instanceid
= $instanceid;
1989 // Define $context->path based on the parent
1990 // context. In other words... Who is your daddy?
1991 $basepath = '/' . SYSCONTEXTID
;
1996 switch ($contextlevel) {
1997 case CONTEXT_COURSECAT
:
1998 $sql = "SELECT ctx.path, ctx.depth
1999 FROM {$CFG->prefix}context ctx
2000 JOIN {$CFG->prefix}course_categories cc
2001 ON (cc.parent=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT
.")
2002 WHERE cc.id={$instanceid}";
2003 if ($p = get_record_sql($sql)) {
2004 $basepath = $p->path
;
2005 $basedepth = $p->depth
;
2006 } else if ($category = get_record('course_categories', 'id', $instanceid)) {
2007 if (empty($category->parent
)) {
2008 // ok - this is a top category
2009 } else if ($parent = get_context_instance(CONTEXT_COURSECAT
, $category->parent
)) {
2010 $basepath = $parent->path
;
2011 $basedepth = $parent->depth
;
2013 // wrong parent category - no big deal, this can be fixed later
2018 // incorrect category id
2023 case CONTEXT_COURSE
:
2024 $sql = "SELECT ctx.path, ctx.depth
2025 FROM {$CFG->prefix}context ctx
2026 JOIN {$CFG->prefix}course c
2027 ON (c.category=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT
.")
2028 WHERE c.id={$instanceid} AND c.id !=" . SITEID
;
2029 if ($p = get_record_sql($sql)) {
2030 $basepath = $p->path
;
2031 $basedepth = $p->depth
;
2032 } else if ($course = get_record('course', 'id', $instanceid)) {
2033 if ($course->id
== SITEID
) {
2034 //ok - no parent category
2035 } else if ($parent = get_context_instance(CONTEXT_COURSECAT
, $course->category
)) {
2036 $basepath = $parent->path
;
2037 $basedepth = $parent->depth
;
2039 // wrong parent category of course - no big deal, this can be fixed later
2043 } else if ($instanceid == SITEID
) {
2044 // no errors for missing site course during installation
2047 // incorrect course id
2052 case CONTEXT_MODULE
:
2053 $sql = "SELECT ctx.path, ctx.depth
2054 FROM {$CFG->prefix}context ctx
2055 JOIN {$CFG->prefix}course_modules cm
2056 ON (cm.course=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
2057 WHERE cm.id={$instanceid}";
2058 if ($p = get_record_sql($sql)) {
2059 $basepath = $p->path
;
2060 $basedepth = $p->depth
;
2061 } else if ($cm = get_record('course_modules', 'id', $instanceid)) {
2062 if ($parent = get_context_instance(CONTEXT_COURSE
, $cm->course
)) {
2063 $basepath = $parent->path
;
2064 $basedepth = $parent->depth
;
2066 // course does not exist - modules can not exist without a course
2070 // cm does not exist
2076 // Only non-pinned & course-page based
2077 $sql = "SELECT ctx.path, ctx.depth
2078 FROM {$CFG->prefix}context ctx
2079 JOIN {$CFG->prefix}block_instance bi
2080 ON (bi.pageid=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE
.")
2081 WHERE bi.id={$instanceid} AND bi.pagetype='course-view'";
2082 if ($p = get_record_sql($sql)) {
2083 $basepath = $p->path
;
2084 $basedepth = $p->depth
;
2085 } else if ($bi = get_record('block_instance', 'id', $instanceid)) {
2086 if ($bi->pagetype
!= 'course-view') {
2087 // ok - not a course block
2088 } else if ($parent = get_context_instance(CONTEXT_COURSE
, $bi->pageid
)) {
2089 $basepath = $parent->path
;
2090 $basedepth = $parent->depth
;
2092 // parent course does not exist - course blocks can not exist without a course
2096 // block does not exist
2101 // default to basepath
2105 // if grandparents unknown, maybe rebuild_context_path() will solve it later
2106 if ($basedepth != 0) {
2107 $context->depth
= $basedepth+
1;
2110 if ($result and $id = insert_record('context', $context)) {
2111 // can't set the full path till we know the id!
2112 if ($basedepth != 0 and !empty($basepath)) {
2113 set_field('context', 'path', $basepath.'/'. $id, 'id', $id);
2115 return get_context_instance_by_id($id);
2118 debugging('Error: could not insert new context level "'.
2119 s($contextlevel).'", instance "'.
2120 s($instanceid).'".');
2126 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
2128 function get_system_context($cache=true) {
2129 static $cached = null;
2130 if ($cache and defined('SYSCONTEXTID')) {
2131 if (is_null($cached)) {
2132 $cached = new object();
2133 $cached->id
= SYSCONTEXTID
;
2134 $cached->contextlevel
= CONTEXT_SYSTEM
;
2135 $cached->instanceid
= 0;
2136 $cached->path
= '/'.SYSCONTEXTID
;
2142 if (!$context = get_record('context', 'contextlevel', CONTEXT_SYSTEM
)) {
2143 $context = new object();
2144 $context->contextlevel
= CONTEXT_SYSTEM
;
2145 $context->instanceid
= 0;
2146 $context->depth
= 1;
2147 $context->path
= NULL; //not known before insert
2149 if (!$context->id
= insert_record('context', $context)) {
2150 // better something than nothing - let's hope it will work somehow
2151 if (!defined('SYSCONTEXTID')) {
2152 define('SYSCONTEXTID', 1);
2154 debugging('Can not create system context');
2155 $context->id
= SYSCONTEXTID
;
2156 $context->path
= '/'.SYSCONTEXTID
;
2161 if (!isset($context->depth
) or $context->depth
!= 1 or $context->instanceid
!= 0 or $context->path
!= '/'.$context->id
) {
2162 $context->instanceid
= 0;
2163 $context->path
= '/'.$context->id
;
2164 $context->depth
= 1;
2165 update_record('context', $context);
2168 if (!defined('SYSCONTEXTID')) {
2169 define('SYSCONTEXTID', $context->id
);
2177 * Remove a context record and any dependent entries,
2178 * removes context from static context cache too
2180 * @param $instanceid
2182 * @return bool properly deleted
2184 function delete_context($contextlevel, $instanceid) {
2185 global $context_cache, $context_cache_id;
2187 // do not use get_context_instance(), because the related object might not exist,
2188 // or the context does not exist yet and it would be created now
2189 if ($context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instanceid)) {
2190 $result = delete_records('role_assignments', 'contextid', $context->id
) &&
2191 delete_records('role_capabilities', 'contextid', $context->id
) &&
2192 delete_records('context', 'id', $context->id
);
2194 // do not mark dirty contexts if parents unknown
2195 if (!is_null($context->path
) and $context->depth
> 0) {
2196 mark_context_dirty($context->path
);
2199 // purge static context cache if entry present
2200 unset($context_cache[$contextlevel][$instanceid]);
2201 unset($context_cache_id[$context->id
]);
2211 * Precreates all contexts including all parents
2212 * @param int $contextlevel, empty means all
2213 * @param bool $buildpaths update paths and depths
2214 * @param bool $feedback show sql feedback
2217 function create_contexts($contextlevel=null, $buildpaths=true, $feedback=false) {
2220 //make sure system context exists
2221 $syscontext = get_system_context(false);
2223 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSECAT
2224 or $contextlevel == CONTEXT_COURSE
2225 or $contextlevel == CONTEXT_MODULE
2226 or $contextlevel == CONTEXT_BLOCK
) {
2227 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2228 SELECT ".CONTEXT_COURSECAT
.", cc.id
2229 FROM {$CFG->prefix}course_categories cc
2230 WHERE NOT EXISTS (SELECT 'x'
2231 FROM {$CFG->prefix}context cx
2232 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT
.")";
2233 execute_sql($sql, $feedback);
2237 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSE
2238 or $contextlevel == CONTEXT_MODULE
2239 or $contextlevel == CONTEXT_BLOCK
) {
2240 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2241 SELECT ".CONTEXT_COURSE
.", c.id
2242 FROM {$CFG->prefix}course c
2243 WHERE NOT EXISTS (SELECT 'x'
2244 FROM {$CFG->prefix}context cx
2245 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE
.")";
2246 execute_sql($sql, $feedback);
2250 if (empty($contextlevel) or $contextlevel == CONTEXT_MODULE
) {
2251 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2252 SELECT ".CONTEXT_MODULE
.", cm.id
2253 FROM {$CFG->prefix}course_modules cm
2254 WHERE NOT EXISTS (SELECT 'x'
2255 FROM {$CFG->prefix}context cx
2256 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE
.")";
2257 execute_sql($sql, $feedback);
2260 if (empty($contextlevel) or $contextlevel == CONTEXT_BLOCK
) {
2261 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2262 SELECT ".CONTEXT_BLOCK
.", bi.id
2263 FROM {$CFG->prefix}block_instance bi
2264 WHERE NOT EXISTS (SELECT 'x'
2265 FROM {$CFG->prefix}context cx
2266 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK
.")";
2267 execute_sql($sql, $feedback);
2270 if (empty($contextlevel) or $contextlevel == CONTEXT_USER
) {
2271 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2272 SELECT ".CONTEXT_USER
.", u.id
2273 FROM {$CFG->prefix}user u
2275 AND NOT EXISTS (SELECT 'x'
2276 FROM {$CFG->prefix}context cx
2277 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER
.")";
2278 execute_sql($sql, $feedback);
2283 build_context_path(false, $feedback);
2288 * Remove stale context records
2292 function cleanup_contexts() {
2295 $sql = " SELECT c.contextlevel,
2296 c.instanceid AS instanceid
2297 FROM {$CFG->prefix}context c
2298 LEFT OUTER JOIN {$CFG->prefix}course_categories t
2299 ON c.instanceid = t.id
2300 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSECAT
. "
2302 SELECT c.contextlevel,
2304 FROM {$CFG->prefix}context c
2305 LEFT OUTER JOIN {$CFG->prefix}course t
2306 ON c.instanceid = t.id
2307 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSE
. "
2309 SELECT c.contextlevel,
2311 FROM {$CFG->prefix}context c
2312 LEFT OUTER JOIN {$CFG->prefix}course_modules t
2313 ON c.instanceid = t.id
2314 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_MODULE
. "
2316 SELECT c.contextlevel,
2318 FROM {$CFG->prefix}context c
2319 LEFT OUTER JOIN {$CFG->prefix}user t
2320 ON c.instanceid = t.id
2321 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_USER
. "
2323 SELECT c.contextlevel,
2325 FROM {$CFG->prefix}context c
2326 LEFT OUTER JOIN {$CFG->prefix}block_instance t
2327 ON c.instanceid = t.id
2328 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_BLOCK
. "
2330 SELECT c.contextlevel,
2332 FROM {$CFG->prefix}context c
2333 LEFT OUTER JOIN {$CFG->prefix}groups t
2334 ON c.instanceid = t.id
2335 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_GROUP
. "
2337 if ($rs = get_recordset_sql($sql)) {
2340 while ($tx && $ctx = rs_fetch_next_record($rs)) {
2341 $tx = $tx && delete_context($ctx->contextlevel
, $ctx->instanceid
);
2356 * Get the context instance as an object. This function will create the
2357 * context instance if it does not exist yet.
2358 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2359 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
2360 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
2361 * @return object The context object.
2363 function get_context_instance($contextlevel, $instance=0) {
2365 global $context_cache, $context_cache_id, $CFG;
2366 static $allowed_contexts = array(CONTEXT_SYSTEM
, CONTEXT_USER
, CONTEXT_COURSECAT
, CONTEXT_COURSE
, CONTEXT_GROUP
, CONTEXT_MODULE
, CONTEXT_BLOCK
);
2368 if ($contextlevel === 'clearcache') {
2369 // TODO: Remove for v2.0
2370 // No longer needed, but we'll catch it to avoid erroring out on custom code.
2371 // This used to be a fix for MDL-9016
2372 // "Restoring into existing course, deleting first
2373 // deletes context and doesn't recreate it"
2377 /// System context has special cache
2378 if ($contextlevel == CONTEXT_SYSTEM
) {
2379 return get_system_context();
2382 /// check allowed context levels
2383 if (!in_array($contextlevel, $allowed_contexts)) {
2384 // fatal error, code must be fixed - probably typo or switched parameters
2385 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
2388 if (!is_array($instance)) {
2390 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2391 return $context_cache[$contextlevel][$instance];
2394 /// Get it from the database, or create it
2395 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
2396 $context = create_context($contextlevel, $instance);
2399 /// Only add to cache if context isn't empty.
2400 if (!empty($context)) {
2401 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
2402 $context_cache_id[$context->id
] = $context; // Cache it for later
2409 /// ok, somebody wants to load several contexts to save some db queries ;-)
2410 $instances = $instance;
2413 foreach ($instances as $key=>$instance) {
2414 /// Check the cache first
2415 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2416 $result[$instance] = $context_cache[$contextlevel][$instance];
2417 unset($instances[$key]);
2423 if (count($instances) > 1) {
2424 $instanceids = implode(',', $instances);
2425 $instanceids = "instanceid IN ($instanceids)";
2427 $instance = reset($instances);
2428 $instanceids = "instanceid = $instance";
2431 if (!$contexts = get_records_sql("SELECT instanceid, id, contextlevel, path, depth
2432 FROM {$CFG->prefix}context
2433 WHERE contextlevel=$contextlevel AND $instanceids")) {
2434 $contexts = array();
2437 foreach ($instances as $instance) {
2438 if (isset($contexts[$instance])) {
2439 $context = $contexts[$instance];
2441 $context = create_context($contextlevel, $instance);
2444 if (!empty($context)) {
2445 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
2446 $context_cache_id[$context->id
] = $context; // Cache it for later
2449 $result[$instance] = $context;
2458 * Get a context instance as an object, from a given context id.
2459 * @param mixed $id a context id or array of ids.
2460 * @return mixed object or array of the context object.
2462 function get_context_instance_by_id($id) {
2464 global $context_cache, $context_cache_id;
2466 if ($id == SYSCONTEXTID
) {
2467 return get_system_context();
2470 if (isset($context_cache_id[$id])) { // Already cached
2471 return $context_cache_id[$id];
2474 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
2475 $context_cache[$context->contextlevel
][$context->instanceid
] = $context;
2476 $context_cache_id[$context->id
] = $context;
2485 * Get the local override (if any) for a given capability in a role in a context
2488 * @param $capability
2490 function get_local_override($roleid, $contextid, $capability) {
2491 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
2496 /************************************
2497 * DB TABLE RELATED FUNCTIONS *
2498 ************************************/
2501 * function that creates a role
2502 * @param name - role name
2503 * @param shortname - role short name
2504 * @param description - role description
2505 * @param legacy - optional legacy capability
2506 * @return id or false
2508 function create_role($name, $shortname, $description, $legacy='') {
2510 // check for duplicate role name
2512 if ($role = get_record('role','name', $name)) {
2513 error('there is already a role with this name!');
2516 if ($role = get_record('role','shortname', $shortname)) {
2517 error('there is already a role with this shortname!');
2520 $role = new object();
2521 $role->name
= $name;
2522 $role->shortname
= $shortname;
2523 $role->description
= $description;
2525 //find free sortorder number
2526 $role->sortorder
= count_records('role');
2527 while (get_record('role','sortorder', $role->sortorder
)) {
2528 $role->sortorder +
= 1;
2531 if (!$context = get_context_instance(CONTEXT_SYSTEM
)) {
2535 if ($id = insert_record('role', $role)) {
2537 assign_capability($legacy, CAP_ALLOW
, $id, $context->id
);
2540 /// By default, users with role:manage at site level
2541 /// should be able to assign users to this new role, and override this new role's capabilities
2543 // find all admin roles
2544 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW
, $context)) {
2545 // foreach admin role
2546 foreach ($adminroles as $arole) {
2547 // write allow_assign and allow_overrid
2548 allow_assign($arole->id
, $id);
2549 allow_override($arole->id
, $id);
2561 * function that deletes a role and cleanups up after it
2562 * @param roleid - id of role to delete
2565 function delete_role($roleid) {
2569 // mdl 10149, check if this is the last active admin role
2570 // if we make the admin role not deletable then this part can go
2572 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
2574 if ($role = get_record('role', 'id', $roleid)) {
2575 if (record_exists('role_capabilities', 'contextid', $systemcontext->id
, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
2576 // deleting an admin role
2578 if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW
, $systemcontext)) {
2579 foreach ($adminroles as $adminrole) {
2580 if ($adminrole->id
!= $roleid) {
2581 // some other admin role
2582 if (record_exists('role_assignments', 'roleid', $adminrole->id
, 'contextid', $systemcontext->id
)) {
2583 // found another admin role with at least 1 user assigned
2590 if ($status !== true) {
2591 error ('You can not delete this role because there is no other admin roles with users assigned');
2596 // first unssign all users
2597 if (!role_unassign($roleid)) {
2598 debugging("Error while unassigning all users from role with ID $roleid!");
2602 // cleanup all references to this role, ignore errors
2605 // MDL-10679 find all contexts where this role has an override
2606 $contexts = get_records_sql("SELECT contextid, contextid
2607 FROM {$CFG->prefix}role_capabilities
2608 WHERE roleid = $roleid");
2610 delete_records('role_capabilities', 'roleid', $roleid);
2612 delete_records('role_allow_assign', 'roleid', $roleid);
2613 delete_records('role_allow_assign', 'allowassign', $roleid);
2614 delete_records('role_allow_override', 'roleid', $roleid);
2615 delete_records('role_allow_override', 'allowoverride', $roleid);
2616 delete_records('role_names', 'roleid', $roleid);
2619 // finally delete the role itself
2620 // get this before the name is gone for logging
2621 $rolename = get_field('role', 'name', 'id', $roleid);
2623 if ($success and !delete_records('role', 'id', $roleid)) {
2624 debugging("Could not delete role record with ID $roleid!");
2629 add_to_log(SITEID
, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '', $USER->id
);
2636 * Function to write context specific overrides, or default capabilities.
2637 * @param module - string name
2638 * @param capability - string name
2639 * @param contextid - context id
2640 * @param roleid - role id
2641 * @param permission - int 1,-1 or -1000
2642 * should not be writing if permission is 0
2644 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2648 if (empty($permission) ||
$permission == CAP_INHERIT
) { // if permission is not set
2649 unassign_capability($capability, $roleid, $contextid);
2653 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
2655 if ($existing and !$overwrite) { // We want to keep whatever is there already
2660 $cap->contextid
= $contextid;
2661 $cap->roleid
= $roleid;
2662 $cap->capability
= $capability;
2663 $cap->permission
= $permission;
2664 $cap->timemodified
= time();
2665 $cap->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2668 $cap->id
= $existing->id
;
2669 return update_record('role_capabilities', $cap);
2671 $c = get_record('context', 'id', $contextid);
2672 return insert_record('role_capabilities', $cap);
2677 * Unassign a capability from a role.
2678 * @param $roleid - the role id
2679 * @param $capability - the name of the capability
2680 * @return boolean - success or failure
2682 function unassign_capability($capability, $roleid, $contextid=NULL) {
2684 if (isset($contextid)) {
2685 // delete from context rel, if this is the last override in this context
2686 $status = delete_records('role_capabilities', 'capability', $capability,
2687 'roleid', $roleid, 'contextid', $contextid);
2689 $status = delete_records('role_capabilities', 'capability', $capability,
2697 * Get the roles that have a given capability assigned to it. This function
2698 * does not resolve the actual permission of the capability. It just checks
2699 * for assignment only.
2700 * @param $capability - capability name (string)
2701 * @param $permission - optional, the permission defined for this capability
2702 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2703 * @return array or role objects
2705 function get_roles_with_capability($capability, $permission=NULL, $context='') {
2710 if ($contexts = get_parent_contexts($context)) {
2711 $listofcontexts = '('.implode(',', $contexts).')';
2713 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
2714 $listofcontexts = '('.$sitecontext->id
.')'; // must be site
2716 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
2721 $selectroles = "SELECT r.*
2722 FROM {$CFG->prefix}role r,
2723 {$CFG->prefix}role_capabilities rc
2724 WHERE rc.capability = '$capability'
2725 AND rc.roleid = r.id $contextstr";
2727 if (isset($permission)) {
2728 $selectroles .= " AND rc.permission = '$permission'";
2730 return get_records_sql($selectroles);
2735 * This function makes a role-assignment (a role for a user or group in a particular context)
2736 * @param $roleid - the role of the id
2737 * @param $userid - userid
2738 * @param $groupid - group id
2739 * @param $contextid - id of the context
2740 * @param $timestart - time this assignment becomes effective
2741 * @param $timeend - time this assignemnt ceases to be effective
2743 * @return id - new id of the assigment
2745 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
2748 /// Do some data validation
2750 if (empty($roleid)) {
2751 debugging('Role ID not provided');
2755 if (empty($userid) && empty($groupid)) {
2756 debugging('Either userid or groupid must be provided');
2760 if ($userid && !record_exists('user', 'id', $userid)) {
2761 debugging('User ID '.intval($userid).' does not exist!');
2765 if ($groupid && !groups_group_exists($groupid)) {
2766 debugging('Group ID '.intval($groupid).' does not exist!');
2770 if (!$context = get_context_instance_by_id($contextid)) {
2771 debugging('Context ID '.intval($contextid).' does not exist!');
2775 if (($timestart and $timeend) and ($timestart > $timeend)) {
2776 debugging('The end time can not be earlier than the start time');
2780 if (!$timemodified) {
2781 $timemodified = time();
2784 /// Check for existing entry
2786 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'userid', $userid);
2788 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id
, 'groupid', $groupid);
2792 $newra = new object;
2794 if (empty($ra)) { // Create a new entry
2795 $newra->roleid
= $roleid;
2796 $newra->contextid
= $context->id
;
2797 $newra->userid
= $userid;
2798 $newra->hidden
= $hidden;
2799 $newra->enrol
= $enrol;
2800 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2801 /// by repeating queries with the same exact parameters in a 100 secs time window
2802 $newra->timestart
= round($timestart, -2);
2803 $newra->timeend
= $timeend;
2804 $newra->timemodified
= $timemodified;
2805 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2807 $success = insert_record('role_assignments', $newra);
2809 } else { // We already have one, just update it
2811 $newra->id
= $ra->id
;
2812 $newra->hidden
= $hidden;
2813 $newra->enrol
= $enrol;
2814 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2815 /// by repeating queries with the same exact parameters in a 100 secs time window
2816 $newra->timestart
= round($timestart, -2);
2817 $newra->timeend
= $timeend;
2818 $newra->timemodified
= $timemodified;
2819 $newra->modifierid
= empty($USER->id
) ?
0 : $USER->id
;
2821 $success = update_record('role_assignments', $newra);
2824 if ($success) { /// Role was assigned, so do some other things
2826 /// mark context as dirty - modules might use has_capability() in xxx_role_assing()
2827 /// again expensive, but needed
2828 mark_context_dirty($context->path
);
2830 if (!empty($USER->id
) && $USER->id
== $userid) {
2831 /// If the user is the current user, then do full reload of capabilities too.
2832 load_all_capabilities();
2835 /// Ask all the modules if anything needs to be done for this user
2836 if ($mods = get_list_of_plugins('mod')) {
2837 foreach ($mods as $mod) {
2838 include_once($CFG->dirroot
.'/mod/'.$mod.'/lib.php');
2839 $functionname = $mod.'_role_assign';
2840 if (function_exists($functionname)) {
2841 $functionname($userid, $context, $roleid);
2847 /// now handle metacourse role assignments if in course context
2848 if ($success and $context->contextlevel
== CONTEXT_COURSE
) {
2849 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2850 foreach ($parents as $parent) {
2851 sync_metacourse($parent->parent_course
);
2861 * Deletes one or more role assignments. You must specify at least one parameter.
2866 * @param $enrol unassign only if enrolment type matches, NULL means anything
2867 * @return boolean - success or failure
2869 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
2875 $args = array('roleid', 'userid', 'groupid', 'contextid');
2877 foreach ($args as $arg) {
2879 $select[] = $arg.' = '.$
$arg;
2882 if (!empty($enrol)) {
2883 $select[] = "enrol='$enrol'";
2887 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2888 $mods = get_list_of_plugins('mod');
2889 foreach($ras as $ra) {
2890 /// infinite loop protection when deleting recursively
2891 if (!$ra = get_record('role_assignments', 'id', $ra->id
)) {
2894 $success = delete_records('role_assignments', 'id', $ra->id
) and $success;
2896 if (!$context = get_context_instance_by_id($ra->contextid
)) {
2897 // strange error, not much to do
2901 /* mark contexts as dirty here, because we need the refreshed
2902 * caps bellow to delete group membership and user_lastaccess!
2903 * and yes, this is very expensive for bulk operations :-(
2905 mark_context_dirty($context->path
);
2907 /// If the user is the current user, then do full reload of capabilities too.
2908 if (!empty($USER->id
) && $USER->id
== $ra->userid
) {
2909 load_all_capabilities();
2912 /// Ask all the modules if anything needs to be done for this user
2913 foreach ($mods as $mod) {
2914 include_once($CFG->dirroot
.'/mod/'.$mod.'/lib.php');
2915 $functionname = $mod.'_role_unassign';
2916 if (function_exists($functionname)) {
2917 $functionname($ra->userid
, $context); // watch out, $context might be NULL if something goes wrong
2921 /// now handle metacourse role unassigment and removing from goups if in course context
2922 if ($context->contextlevel
== CONTEXT_COURSE
) {
2924 // cleanup leftover course groups/subscriptions etc when user has
2925 // no capability to view course
2926 // this may be slow, but this is the proper way of doing it
2927 if (!has_capability('moodle/course:view', $context, $ra->userid
)) {
2928 // remove from groups
2929 if ($groups = groups_get_all_groups($context->instanceid
)) {
2930 foreach ($groups as $group) {
2931 delete_records('groups_members', 'groupid', $group->id
, 'userid', $ra->userid
);
2935 // delete lastaccess records
2936 delete_records('user_lastaccess', 'userid', $ra->userid
, 'courseid', $context->instanceid
);
2939 //unassign roles in metacourses if needed
2940 if ($parents = get_records('course_meta', 'child_course', $context->instanceid
)) {
2941 foreach ($parents as $parent) {
2942 sync_metacourse($parent->parent_course
);
2954 * A convenience function to take care of the common case where you
2955 * just want to enrol someone using the default role into a course
2957 * @param object $course
2958 * @param object $user
2959 * @param string $enrol - the plugin used to do this enrolment
2961 function enrol_into_course($course, $user, $enrol) {
2963 $timestart = time();
2964 // remove time part from the timestamp and keep only the date part
2965 $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
2966 if ($course->enrolperiod
) {
2967 $timeend = $timestart +
$course->enrolperiod
;
2972 if ($role = get_default_course_role($course)) {
2974 $context = get_context_instance(CONTEXT_COURSE
, $course->id
);
2976 if (!role_assign($role->id
, $user->id
, 0, $context->id
, $timestart, $timeend, 0, $enrol)) {
2980 // force accessdata refresh for users visiting this context...
2981 mark_context_dirty($context->path
);
2983 email_welcome_message_to_user($course, $user);
2985 add_to_log($course->id
, 'course', 'enrol',
2986 'view.php?id='.$course->id
, $course->id
);
2995 * Loads the capability definitions for the component (from file). If no
2996 * capabilities are defined for the component, we simply return an empty array.
2997 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
2998 * @return array of capabilities
3000 function load_capability_def($component) {
3003 if ($component == 'moodle') {
3004 $defpath = $CFG->libdir
.'/db/access.php';
3005 $varprefix = 'moodle';
3007 $compparts = explode('/', $component);
3009 if ($compparts[0] == 'block') {
3010 // Blocks are an exception. Blocks directory is 'blocks', and not
3011 // 'block'. So we need to jump through hoops.
3012 $defpath = $CFG->dirroot
.'/'.$compparts[0].
3013 's/'.$compparts[1].'/db/access.php';
3014 $varprefix = $compparts[0].'_'.$compparts[1];
3016 } else if ($compparts[0] == 'format') {
3017 // Similar to the above, course formats are 'format' while they
3018 // are stored in 'course/format'.
3019 $defpath = $CFG->dirroot
.'/course/'.$component.'/db/access.php';
3020 $varprefix = $compparts[0].'_'.$compparts[1];
3022 } else if ($compparts[0] == 'gradeimport') {
3023 $defpath = $CFG->dirroot
.'/grade/import/'.$compparts[1].'/db/access.php';
3024 $varprefix = $compparts[0].'_'.$compparts[1];
3026 } else if ($compparts[0] == 'gradeexport') {
3027 $defpath = $CFG->dirroot
.'/grade/export/'.$compparts[1].'/db/access.php';
3028 $varprefix = $compparts[0].'_'.$compparts[1];
3030 } else if ($compparts[0] == 'gradereport') {
3031 $defpath = $CFG->dirroot
.'/grade/report/'.$compparts[1].'/db/access.php';
3032 $varprefix = $compparts[0].'_'.$compparts[1];
3035 $defpath = $CFG->dirroot
.'/'.$component.'/db/access.php';
3036 $varprefix = str_replace('/', '_', $component);
3039 $capabilities = array();
3041 if (file_exists($defpath)) {
3043 $capabilities = $
{$varprefix.'_capabilities'};
3045 return $capabilities;
3050 * Gets the capabilities that have been cached in the database for this
3052 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3053 * @return array of capabilities
3055 function get_cached_capabilities($component='moodle') {
3056 if ($component == 'moodle') {
3057 $storedcaps = get_records_select('capabilities',
3058 "name LIKE 'moodle/%:%'");
3059 } else if ($component == 'local') {
3060 $storedcaps = get_records_select('capabilities',
3061 "name LIKE 'moodle/local:%'");
3063 $storedcaps = get_records_select('capabilities',
3064 "name LIKE '$component:%'");
3070 * Returns default capabilities for given legacy role type.
3072 * @param string legacy role name
3075 function get_default_capabilities($legacyrole) {
3076 if (!$allcaps = get_records('capabilities')) {
3077 error('Error: no capabilitites defined!');
3080 $defaults = array();
3081 $components = array();
3082 foreach ($allcaps as $cap) {
3083 if (!in_array($cap->component
, $components)) {
3084 $components[] = $cap->component
;
3085 $alldefs = array_merge($alldefs, load_capability_def($cap->component
));
3088 foreach($alldefs as $name=>$def) {
3089 if (isset($def['legacy'][$legacyrole])) {
3090 $defaults[$name] = $def['legacy'][$legacyrole];
3095 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW
;
3096 if ($legacyrole == 'admin') {
3097 $defaults['moodle/site:doanything'] = CAP_ALLOW
;
3103 * Reset role capabilitites to default according to selected legacy capability.
3104 * If several legacy caps selected, use the first from get_default_capabilities.
3105 * If no legacy selected, removes all capabilities.
3107 * @param int @roleid
3109 function reset_role_capabilities($roleid) {
3110 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
3111 $legacyroles = get_legacy_roles();
3113 $defaultcaps = array();
3114 foreach($legacyroles as $ltype=>$lcap) {
3115 $localoverride = get_local_override($roleid, $sitecontext->id
, $lcap);
3116 if (!empty($localoverride->permission
) and $localoverride->permission
== CAP_ALLOW
) {
3117 //choose first selected legacy capability
3118 $defaultcaps = get_default_capabilities($ltype);
3123 delete_records('role_capabilities', 'roleid', $roleid);
3124 if (!empty($defaultcaps)) {
3125 foreach($defaultcaps as $cap=>$permission) {
3126 assign_capability($cap, $permission, $roleid, $sitecontext->id
);
3132 * Updates the capabilities table with the component capability definitions.
3133 * If no parameters are given, the function updates the core moodle
3136 * Note that the absence of the db/access.php capabilities definition file
3137 * will cause any stored capabilities for the component to be removed from
3140 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3143 function update_capabilities($component='moodle') {
3145 $storedcaps = array();
3147 $filecaps = load_capability_def($component);
3148 $cachedcaps = get_cached_capabilities($component);
3150 foreach ($cachedcaps as $cachedcap) {
3151 array_push($storedcaps, $cachedcap->name
);
3152 // update risk bitmasks and context levels in existing capabilities if needed
3153 if (array_key_exists($cachedcap->name
, $filecaps)) {
3154 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name
])) {
3155 $filecaps[$cachedcap->name
]['riskbitmask'] = 0; // no risk if not specified
3157 if ($cachedcap->riskbitmask
!= $filecaps[$cachedcap->name
]['riskbitmask']) {
3158 $updatecap = new object();
3159 $updatecap->id
= $cachedcap->id
;
3160 $updatecap->riskbitmask
= $filecaps[$cachedcap->name
]['riskbitmask'];
3161 if (!update_record('capabilities', $updatecap)) {
3166 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name
])) {
3167 $filecaps[$cachedcap->name
]['contextlevel'] = 0; // no context level defined
3169 if ($cachedcap->contextlevel
!= $filecaps[$cachedcap->name
]['contextlevel']) {
3170 $updatecap = new object();
3171 $updatecap->id
= $cachedcap->id
;
3172 $updatecap->contextlevel
= $filecaps[$cachedcap->name
]['contextlevel'];
3173 if (!update_record('capabilities', $updatecap)) {
3181 // Are there new capabilities in the file definition?
3184 foreach ($filecaps as $filecap => $def) {
3186 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
3187 if (!array_key_exists('riskbitmask', $def)) {
3188 $def['riskbitmask'] = 0; // no risk if not specified
3190 $newcaps[$filecap] = $def;
3193 // Add new capabilities to the stored definition.
3194 foreach ($newcaps as $capname => $capdef) {
3195 $capability = new object;
3196 $capability->name
= $capname;
3197 $capability->captype
= $capdef['captype'];
3198 $capability->contextlevel
= $capdef['contextlevel'];
3199 $capability->component
= $component;
3200 $capability->riskbitmask
= $capdef['riskbitmask'];
3202 if (!insert_record('capabilities', $capability, false, 'id')) {
3207 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
3208 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
3209 foreach ($rolecapabilities as $rolecapability){
3210 //assign_capability will update rather than insert if capability exists
3211 if (!assign_capability($capname, $rolecapability->permission
,
3212 $rolecapability->roleid
, $rolecapability->contextid
, true)){
3213 notify('Could not clone capabilities for '.$capname);
3217 // Do we need to assign the new capabilities to roles that have the
3218 // legacy capabilities moodle/legacy:* as well?
3219 // we ignore legacy key if we have cloned permissions
3220 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
3221 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
3222 notify('Could not assign legacy capabilities for '.$capname);
3225 // Are there any capabilities that have been removed from the file
3226 // definition that we need to delete from the stored capabilities and
3227 // role assignments?
3228 capabilities_cleanup($component, $filecaps);
3235 * Deletes cached capabilities that are no longer needed by the component.
3236 * Also unassigns these capabilities from any roles that have them.
3237 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3238 * @param $newcapdef - array of the new capability definitions that will be
3239 * compared with the cached capabilities
3240 * @return int - number of deprecated capabilities that have been removed
3242 function capabilities_cleanup($component, $newcapdef=NULL) {
3246 if ($cachedcaps = get_cached_capabilities($component)) {
3247 foreach ($cachedcaps as $cachedcap) {
3248 if (empty($newcapdef) ||
3249 array_key_exists($cachedcap->name
, $newcapdef) === false) {
3251 // Remove from capabilities cache.
3252 if (!delete_records('capabilities', 'name', $cachedcap->name
)) {
3253 error('Could not delete deprecated capability '.$cachedcap->name
);
3257 // Delete from roles.
3258 if($roles = get_roles_with_capability($cachedcap->name
)) {
3259 foreach($roles as $role) {
3260 if (!unassign_capability($cachedcap->name
, $role->id
)) {
3261 error('Could not unassign deprecated capability '.
3262 $cachedcap->name
.' from role '.$role->name
);
3269 return $removedcount;
3280 * prints human readable context identifier.
3282 function print_context_name($context, $withprefix = true, $short = false) {
3285 switch ($context->contextlevel
) {
3287 case CONTEXT_SYSTEM
: // by now it's a definite an inherit
3288 $name = get_string('coresystem');
3292 if ($user = get_record('user', 'id', $context->instanceid
)) {
3294 $name = get_string('user').': ';
3296 $name .= fullname($user);
3300 case CONTEXT_COURSECAT
: // Coursecat -> coursecat or site
3301 if ($category = get_record('course_categories', 'id', $context->instanceid
)) {
3303 $name = get_string('category').': ';
3305 $name .=format_string($category->name
);
3309 case CONTEXT_COURSE
: // 1 to 1 to course cat
3310 if ($course = get_record('course', 'id', $context->instanceid
)) {
3312 if ($context->instanceid
== SITEID
) {
3313 $name = get_string('site').': ';
3315 $name = get_string('course').': ';
3319 $name .=format_string($course->shortname
);
3321 $name .=format_string($course->fullname
);
3327 case CONTEXT_GROUP
: // 1 to 1 to course
3328 if ($name = groups_get_group_name($context->instanceid
)) {
3330 $name = get_string('group').': '. $name;
3335 case CONTEXT_MODULE
: // 1 to 1 to course
3336 if ($cm = get_record('course_modules','id',$context->instanceid
)) {
3337 if ($module = get_record('modules','id',$cm->module
)) {
3338 if ($mod = get_record($module->name
, 'id', $cm->instance
)) {
3340 $name = get_string('activitymodule').': ';
3342 $name .= $mod->name
;
3348 case CONTEXT_BLOCK
: // not necessarily 1 to 1 to course
3349 if ($blockinstance = get_record('block_instance','id',$context->instanceid
)) {
3350 if ($block = get_record('block','id',$blockinstance->blockid
)) {
3352 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
3353 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
3354 $blockname = "block_$block->name";
3355 if ($blockobject = new $blockname()) {
3357 $name = get_string('block').': ';
3359 $name .= $blockobject->title
;
3366 error ('This is an unknown context (' . $context->contextlevel
. ') in print_context_name!');
3375 * Extracts the relevant capabilities given a contextid.
3376 * All case based, example an instance of forum context.
3377 * Will fetch all forum related capabilities, while course contexts
3378 * Will fetch all capabilities
3379 * @param object context
3383 * `name` varchar(150) NOT NULL,
3384 * `captype` varchar(50) NOT NULL,
3385 * `contextlevel` int(10) NOT NULL,
3386 * `component` varchar(100) NOT NULL,
3388 function fetch_context_capabilities($context) {
3392 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
3394 switch ($context->contextlevel
) {
3396 case CONTEXT_SYSTEM
: // all
3397 $SQL = "select * from {$CFG->prefix}capabilities";
3402 FROM {$CFG->prefix}capabilities
3403 WHERE contextlevel = ".CONTEXT_USER
;
3406 case CONTEXT_COURSECAT
: // all
3407 $SQL = "select * from {$CFG->prefix}capabilities";
3410 case CONTEXT_COURSE
: // all
3411 $SQL = "select * from {$CFG->prefix}capabilities";
3414 case CONTEXT_GROUP
: // group caps
3417 case CONTEXT_MODULE
: // mod caps
3418 $cm = get_record('course_modules', 'id', $context->instanceid
);
3419 $module = get_record('modules', 'id', $cm->module
);
3421 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE
."
3422 and component = 'mod/$module->name'";
3425 case CONTEXT_BLOCK
: // block caps
3426 $cb = get_record('block_instance', 'id', $context->instanceid
);
3427 $block = get_record('block', 'id', $cb->blockid
);
3429 $SQL = "select * from {$CFG->prefix}capabilities where (contextlevel = ".CONTEXT_BLOCK
." AND component = 'moodle')
3430 OR (component = 'block/$block->name')";
3437 if (!$records = get_records_sql($SQL.' '.$sort)) {
3441 /// the rest of code is a bit hacky, think twice before modifying it :-(
3443 // special sorting of core system capabiltites and enrollments
3444 if (in_array($context->contextlevel
, array(CONTEXT_SYSTEM
, CONTEXT_COURSECAT
, CONTEXT_COURSE
))) {
3446 foreach ($records as $key=>$record) {
3447 if (preg_match('|^moodle/|', $record->name
) and $record->contextlevel
== CONTEXT_SYSTEM
) {
3448 $first[$key] = $record;
3449 unset($records[$key]);
3450 } else if (count($first)){
3454 if (count($first)) {
3455 $records = $first +
$records; // merge the two arrays keeping the keys
3458 $contextindependentcaps = fetch_context_independent_capabilities();
3459 $records = array_merge($contextindependentcaps, $records);
3468 * Gets the context-independent capabilities that should be overrridable in
3470 * @return array of capability records from the capabilities table.
3472 function fetch_context_independent_capabilities() {
3474 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
3475 $contextindependentcaps = array(
3476 'moodle/site:accessallgroups'
3481 foreach ($contextindependentcaps as $capname) {
3482 $record = get_record('capabilities', 'name', $capname);
3483 array_push($records, $record);
3490 * This function pulls out all the resolved capabilities (overrides and
3491 * defaults) of a role used in capability overrides in contexts at a given
3493 * @param obj $context
3494 * @param int $roleid
3495 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
3498 function role_context_capabilities($roleid, $context, $cap='') {
3501 $contexts = get_parent_contexts($context);
3502 $contexts[] = $context->id
;
3503 $contexts = '('.implode(',', $contexts).')';
3506 $search = " AND rc.capability = '$cap' ";
3512 FROM {$CFG->prefix}role_capabilities rc,
3513 {$CFG->prefix}context c
3514 WHERE rc.contextid in $contexts
3515 AND rc.roleid = $roleid
3516 AND rc.contextid = c.id $search
3517 ORDER BY c.contextlevel DESC,
3518 rc.capability DESC";
3520 $capabilities = array();
3522 if ($records = get_records_sql($SQL)) {
3523 // We are traversing via reverse order.
3524 foreach ($records as $record) {
3525 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3526 if (!isset($capabilities[$record->capability
]) ||
$record->permission
<-500) {
3527 $capabilities[$record->capability
] = $record->permission
;
3531 return $capabilities;
3535 * Recursive function which, given a context, find all parent context ids,
3536 * and return the array in reverse order, i.e. parent first, then grand
3539 * @param object $context
3542 function get_parent_contexts($context) {
3544 if ($context->path
== '') {
3548 $parentcontexts = substr($context->path
, 1); // kill leading slash
3549 $parentcontexts = explode('/', $parentcontexts);
3550 array_pop($parentcontexts); // and remove its own id
3552 return array_reverse($parentcontexts);
3556 * Return the id of the parent of this context, or false if there is no parent (only happens if this
3557 * is the site context.)
3559 * @param object $context
3560 * @return integer the id of the parent context.
3562 function get_parent_contextid($context) {
3563 $parentcontexts = get_parent_contexts($context);
3564 if (count($parentcontexts) == 0) {
3567 return array_shift($parentcontexts);
3571 * Recursive function which, given a context, find all its children context ids.
3573 * When called for a course context, it will return the modules and blocks
3574 * displayed in the course page.
3576 * For course category contexts it will return categories and courses. It will
3577 * NOT recurse into courses - if you want to do that, call it on the returned
3580 * If called on a course context it _will_ populate the cache with the appropriate
3583 * @param object $context.
3584 * @return array of child records
3586 function get_child_contexts($context) {
3588 global $CFG, $context_cache;
3590 // We *MUST* populate the context_cache as the callers
3591 // will probably ask for the full record anyway soon after
3592 // soon after calling us ;-)
3594 switch ($context->contextlevel
) {
3601 case CONTEXT_MODULE
:
3611 case CONTEXT_COURSE
:
3613 // - module instances - easy
3615 // - blocks assigned to the course-view page explicitly - easy
3616 // - blocks pinned (note! we get all of them here, regardless of vis)
3617 $sql = " SELECT ctx.*
3618 FROM {$CFG->prefix}context ctx
3619 WHERE ctx.path LIKE '{$context->path}/%'
3620 AND ctx.contextlevel IN (".CONTEXT_MODULE
.",".CONTEXT_BLOCK
.")
3623 FROM {$CFG->prefix}context ctx
3624 JOIN {$CFG->prefix}groups g
3625 ON (ctx.instanceid=g.id AND ctx.contextlevel=".CONTEXT_GROUP
.")
3626 WHERE g.courseid={$context->instanceid}
3629 FROM {$CFG->prefix}context ctx
3630 JOIN {$CFG->prefix}block_pinned b
3631 ON (ctx.instanceid=b.blockid AND ctx.contextlevel=".CONTEXT_BLOCK
.")
3632 WHERE b.pagetype='course-view'
3634 $rs = get_recordset_sql($sql);
3636 while ($rec = rs_fetch_next_record($rs)) {
3637 $records[$rec->id
] = $rec;
3638 $context_cache[$rec->contextlevel
][$rec->instanceid
] = $rec;
3644 case CONTEXT_COURSECAT
:
3648 $sql = " SELECT ctx.*
3649 FROM {$CFG->prefix}context ctx
3650 WHERE ctx.path LIKE '{$context->path}/%'
3651 AND ctx.contextlevel IN (".CONTEXT_COURSECAT
.",".CONTEXT_COURSE
.")
3653 $rs = get_recordset_sql($sql);
3655 while ($rec = rs_fetch_next_record($rs)) {
3656 $records[$rec->id
] = $rec;
3657 $context_cache[$rec->contextlevel
][$rec->instanceid
] = $rec;
3668 case CONTEXT_SYSTEM
:
3669 // Just get all the contexts except for CONTEXT_SYSTEM level
3670 // and hope we don't OOM in the process - don't cache
3671 $sql = 'SELECT c.*'.
3672 'FROM '.$CFG->prefix
.'context c '.
3673 'WHERE contextlevel != '.CONTEXT_SYSTEM
;
3675 return get_records_sql($sql);
3679 error('This is an unknown context (' . $context->contextlevel
. ') in get_child_contexts!');
3686 * Gets a string for sql calls, searching for stuff in this context or above
3687 * @param object $context
3690 function get_related_contexts_string($context) {
3691 if ($parents = get_parent_contexts($context)) {
3692 return (' IN ('.$context->id
.','.implode(',', $parents).')');
3694 return (' ='.$context->id
);
3699 * Returns the human-readable, translated version of the capability.
3700 * Basically a big switch statement.
3701 * @param $capabilityname - e.g. mod/choice:readresponses
3703 function get_capability_string($capabilityname) {
3705 // Typical capabilityname is mod/choice:readresponses
3707 $names = split('/', $capabilityname);
3708 $stringname = $names[1]; // choice:readresponses
3709 $components = split(':', $stringname);
3710 $componentname = $components[0]; // choice
3712 switch ($names[0]) {
3714 $string = get_string($stringname, $componentname);
3718 $string = get_string($stringname, 'block_'.$componentname);
3722 if ($componentname == 'local') {
3723 $string = get_string($stringname, 'local');
3725 $string = get_string($stringname, 'role');
3730 $string = get_string($stringname, 'enrol_'.$componentname);
3734 $string = get_string($stringname, 'format_'.$componentname);
3738 $string = get_string($stringname, 'gradeexport_'.$componentname);
3742 $string = get_string($stringname, 'gradeimport_'.$componentname);
3746 $string = get_string($stringname, 'gradereport_'.$componentname);
3750 $string = get_string($stringname);
3759 * This gets the mod/block/course/core etc strings.
3761 * @param $contextlevel
3763 function get_component_string($component, $contextlevel) {
3765 switch ($contextlevel) {
3767 case CONTEXT_SYSTEM
:
3768 if (preg_match('|^enrol/|', $component)) {
3769 $langname = str_replace('/', '_', $component);
3770 $string = get_string('enrolname', $langname);
3771 } else if (preg_match('|^block/|', $component)) {
3772 $langname = str_replace('/', '_', $component);
3773 $string = get_string('blockname', $langname);
3774 } else if (preg_match('|^local|', $component)) {
3775 $langname = str_replace('/', '_', $component);
3776 $string = get_string('local');
3778 $string = get_string('coresystem');
3783 $string = get_string('users');
3786 case CONTEXT_COURSECAT
:
3787 $string = get_string('categories');
3790 case CONTEXT_COURSE
:
3791 if (preg_match('|^gradeimport/|', $component)
3792 ||
preg_match('|^gradeexport/|', $component)
3793 ||
preg_match('|^gradereport/|', $component)) {
3794 $string = get_string('gradebook', 'admin');
3796 $string = get_string('course');
3801 $string = get_string('group');
3804 case CONTEXT_MODULE
:
3805 $string = get_string('modulename', basename($component));
3809 if( $component == 'moodle' ){
3810 $string = get_string('block');
3812 $string = get_string('blockname', 'block_'.basename($component));
3817 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
3825 * Gets the list of roles assigned to this context and up (parents)
3826 * @param object $context
3827 * @param view - set to true when roles are pulled for display only
3828 * this is so that we can filter roles with no visible
3829 * assignment, for example, you might want to "hide" all
3830 * course creators when browsing the course participants
3834 function get_roles_used_in_context($context, $view = false) {
3838 // filter for roles with all hidden assignments
3839 // no need to return when only pulling roles for reviewing
3840 // e.g. participants page.
3841 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3842 $contextlist = get_related_contexts_string($context);
3844 $sql = "SELECT DISTINCT r.id,
3848 FROM {$CFG->prefix}role_assignments ra,
3849 {$CFG->prefix}role r
3850 WHERE r.id = ra.roleid
3851 AND ra.contextid $contextlist
3853 ORDER BY r.sortorder ASC";
3855 return get_records_sql($sql);
3859 * This function is used to print roles column in user profile page.
3861 * @param object context
3864 function get_user_roles_in_context($userid, $context, $view=true){
3868 $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';
3869 $rolenames = array();
3870 if ($roles = get_records_sql($SQL)) {
3871 foreach ($roles as $userrole) {
3872 // MDL-12544, if we are in view mode and current user has no capability to view hidden assignment, skip it
3873 if ($userrole->hidden
&& $view && !has_capability('moodle/role:viewhiddenassigns', $context)) {
3876 $rolenames[$userrole->roleid
] = $userrole->name
;
3879 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
3881 foreach ($rolenames as $roleid => $rolename) {
3882 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot
.'/user/index.php?contextid='.$context->id
.'&roleid='.$roleid.'">'.$rolename.'</a>';
3884 $rolestring = implode(',', $rolenames);
3891 * Checks if a user can override capabilities of a particular role in this context
3892 * @param object $context
3893 * @param int targetroleid - the id of the role you want to override
3896 function user_can_override($context, $targetroleid) {
3897 // first check if user has override capability
3898 // if not return false;
3899 if (!has_capability('moodle/role:override', $context)) {
3902 // pull out all active roles of this user from this context(or above)
3903 if ($userroles = get_user_roles($context)) {
3904 foreach ($userroles as $userrole) {
3905 // if any in the role_allow_override table, then it's ok
3906 if (get_record('role_allow_override', 'roleid', $userrole->roleid
, 'allowoverride', $targetroleid)) {
3917 * Checks if a user can assign users to a particular role in this context
3918 * @param object $context
3919 * @param int targetroleid - the id of the role you want to assign users to
3922 function user_can_assign($context, $targetroleid) {
3924 // first check if user has override capability
3925 // if not return false;
3926 if (!has_capability('moodle/role:assign', $context)) {
3929 // pull out all active roles of this user from this context(or above)
3930 if ($userroles = get_user_roles($context)) {
3931 foreach ($userroles as $userrole) {
3932 // if any in the role_allow_override table, then it's ok
3933 if (get_record('role_allow_assign', 'roleid', $userrole->roleid
, 'allowassign', $targetroleid)) {
3942 /** Returns all site roles in correct sort order.
3945 function get_all_roles() {
3946 return get_records('role', '', '', 'sortorder ASC');
3950 * gets all the user roles assigned in this context, or higher contexts
3951 * this is mainly used when checking if a user can assign a role, or overriding a role
3952 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3953 * allow_override tables
3954 * @param object $context
3955 * @param int $userid
3956 * @param view - set to true when roles are pulled for display only
3957 * this is so that we can filter roles with no visible
3958 * assignment, for example, you might want to "hide" all
3959 * course creators when browsing the course participants
3963 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
3965 global $USER, $CFG, $db;
3967 if (empty($userid)) {
3968 if (empty($USER->id
)) {
3971 $userid = $USER->id
;
3973 // set up hidden sql
3974 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))?
' AND ra.hidden = 0 ':'';
3976 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
3977 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id
.')';
3979 $contexts = ' ra.contextid = \''.$context->id
.'\'';
3982 if (!$return = get_records_sql('SELECT ra.*, r.name, r.shortname
3983 FROM '.$CFG->prefix
.'role_assignments ra,
3984 '.$CFG->prefix
.'role r,
3985 '.$CFG->prefix
.'context c
3986 WHERE ra.userid = '.$userid.'
3987 AND ra.roleid = r.id
3988 AND ra.contextid = c.id
3989 AND '.$contexts . $hiddensql .'
3990 ORDER BY '.$order)) {
3998 * Creates a record in the allow_override table
3999 * @param int sroleid - source roleid
4000 * @param int troleid - target roleid
4001 * @return int - id or false
4003 function allow_override($sroleid, $troleid) {
4004 $record = new object();
4005 $record->roleid
= $sroleid;
4006 $record->allowoverride
= $troleid;
4007 return insert_record('role_allow_override', $record);
4011 * Creates a record in the allow_assign table
4012 * @param int sroleid - source roleid
4013 * @param int troleid - target roleid
4014 * @return int - id or false
4016 function allow_assign($sroleid, $troleid) {
4017 $record = new object;
4018 $record->roleid
= $sroleid;
4019 $record->allowassign
= $troleid;
4020 return insert_record('role_allow_assign', $record);
4024 * Gets a list of roles that this user can assign in this context
4025 * @param object $context
4026 * @param string $field
4029 function get_assignable_roles ($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS
) {
4034 $ras = get_user_roles($context);
4036 foreach ($ras as $ra) {
4037 $roleids[] = $ra->roleid
;
4041 if (count($roleids)===0) {
4045 $roleids = implode(',',$roleids);
4047 // The subselect scopes the DISTINCT down to
4048 // the role ids - a DISTINCT over the whole of
4049 // the role table is much more expensive on some DBs
4050 $sql = "SELECT r.id, r.$field
4051 FROM {$CFG->prefix}role r
4052 JOIN ( SELECT DISTINCT allowassign as allowedrole
4053 FROM {$CFG->prefix}role_allow_assign raa
4054 WHERE raa.roleid IN ($roleids) ) ar
4055 ON r.id=ar.allowedrole
4056 ORDER BY sortorder ASC";
4058 $rs = get_recordset_sql($sql);
4060 while ($r = rs_fetch_next_record($rs)) {
4061 $roles[$r->id
] = $r->{$field};
4065 return role_fix_names($roles, $context, $rolenamedisplay);
4069 * Gets a list of roles that this user can assign in this context, for the switchrole menu
4071 * This is a quick-fix for MDL-13459 until MDL-8312 is sorted out...
4072 * @param object $context
4073 * @param string $field
4076 function get_assignable_roles_for_switchrole ($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS
) {
4081 $ras = get_user_roles($context);
4083 foreach ($ras as $ra) {
4084 $roleids[] = $ra->roleid
;
4088 if (count($roleids)===0) {
4092 $roleids = implode(',',$roleids);
4094 // The subselect scopes the DISTINCT down to
4095 // the role ids - a DISTINCT over the whole of
4096 // the role table is much more expensive on some DBs
4097 $sql = "SELECT r.id, r.$field
4098 FROM {$CFG->prefix}role r
4099 JOIN ( SELECT DISTINCT allowassign as allowedrole
4100 FROM {$CFG->prefix}role_allow_assign raa
4101 WHERE raa.roleid IN ($roleids) ) ar
4102 ON r.id=ar.allowedrole
4103 JOIN {$CFG->prefix}role_capabilities rc
4104 ON (r.id = rc.roleid AND rc.capability = 'moodle/course:view'
4105 AND rc.capability != 'moodle/site:doanything')
4106 ORDER BY sortorder ASC";
4108 $rs = get_recordset_sql($sql);
4110 while ($r = rs_fetch_next_record($rs)) {
4111 $roles[$r->id
] = $r->{$field};
4115 return role_fix_names($roles, $context, $rolenamedisplay);
4119 * Gets a list of roles that this user can override in this context
4120 * @param object $context
4123 function get_overridable_roles($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS
) {
4127 if ($roles = get_all_roles()) {
4128 foreach ($roles as $role) {
4129 if (user_can_override($context, $role->id
)) {
4130 $options[$role->id
] = $role->$field;
4135 return role_fix_names($options, $context, $rolenamedisplay);
4139 * Returns a role object that is the default role for new enrolments
4142 * @param object $course
4143 * @return object $role
4145 function get_default_course_role($course) {
4148 /// First let's take the default role the course may have
4149 if (!empty($course->defaultrole
)) {
4150 if ($role = get_record('role', 'id', $course->defaultrole
)) {
4155 /// Otherwise the site setting should tell us
4156 if ($CFG->defaultcourseroleid
) {
4157 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid
)) {
4162 /// It's unlikely we'll get here, but just in case, try and find a student role
4163 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW
)) {
4164 return array_shift($studentroles); /// Take the first one
4172 * Who has this capability in this context?
4174 * This can be a very expensive call - use sparingly and keep
4175 * the results if you are going to need them again soon.
4177 * Note if $fields is empty this function attempts to get u.*
4178 * which can get rather large - and has a serious perf impact
4181 * @param $context - object
4182 * @param $capability - string capability
4183 * @param $fields - fields to be pulled
4184 * @param $sort - the sort order
4185 * @param $limitfrom - number of records to skip (offset)
4186 * @param $limitnum - number of records to fetch
4187 * @param $groups - single group or array of groups - only return
4188 * users who are in one of these group(s).
4189 * @param $exceptions - list of users to exclude
4190 * @param view - set to true when roles are pulled for display only
4191 * this is so that we can filter roles with no visible
4192 * assignment, for example, you might want to "hide" all
4193 * course creators when browsing the course participants
4195 * @param boolean $useviewallgroups if $groups is set the return users who
4196 * have capability both $capability and moodle/site:accessallgroups
4197 * in this context, as well as users who have $capability and who are
4200 function get_users_by_capability($context, $capability, $fields='', $sort='',
4201 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true,
4202 $view=false, $useviewallgroups=false) {
4205 $ctxids = substr($context->path
, 1); // kill leading slash
4206 $ctxids = str_replace('/', ',', $ctxids);
4208 // Context is the frontpage
4209 $isfrontpage = false;
4210 $iscoursepage = false; // coursepage other than fp
4211 if ($context->contextlevel
== CONTEXT_COURSE
) {
4212 if ($context->instanceid
== SITEID
) {
4213 $isfrontpage = true;
4215 $iscoursepage = true;
4219 // What roles/rolecaps are interesting?
4220 $caps = "'$capability'";
4221 if ($doanything===true) {
4222 $caps.=",'moodle/site:doanything'";
4223 $doanything_join='';
4224 $doanything_cond='';
4226 // This is an outer join against
4227 // admin-ish roleids. Any row that succeeds
4228 // in JOINing here ends up removed from
4229 // the resultset. This means we remove
4230 // rolecaps from roles that also have
4231 // 'doanything' capabilities.
4232 $doanything_join="LEFT OUTER JOIN (
4233 SELECT DISTINCT rc.roleid
4234 FROM {$CFG->prefix}role_capabilities rc
4235 WHERE rc.capability='moodle/site:doanything'
4236 AND rc.permission=".CAP_ALLOW
."
4237 AND rc.contextid IN ($ctxids)
4239 ON rc.roleid=dar.roleid";
4240 $doanything_cond="AND dar.roleid IS NULL";
4243 // fetch all capability records - we'll walk several
4244 // times over them, and should be a small set
4246 $negperm = false; // has any negative (<0) permission?
4249 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability,
4250 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
4251 FROM {$CFG->prefix}role_capabilities rc
4252 JOIN {$CFG->prefix}context ctx on rc.contextid = ctx.id
4254 WHERE rc.capability IN ($caps) AND ctx.id IN ($ctxids)
4256 ORDER BY rc.roleid ASC, ctx.depth ASC";
4257 if ($capdefs = get_records_sql($sql)) {
4258 foreach ($capdefs AS $rcid=>$rc) {
4259 $roleids[] = (int)$rc->roleid
;
4260 if ($rc->permission
< 0) {
4266 $roleids = array_unique($roleids);
4268 if (count($roleids)===0) { // noone here!
4272 // is the default role interesting? does it have
4273 // a relevant rolecap? (we use this a lot later)
4274 if (in_array((int)$CFG->defaultuserroleid
, $roleids, true)) {
4275 $defaultroleinteresting = true;
4277 $defaultroleinteresting = false;
4281 // Prepare query clauses
4283 $wherecond = array();
4286 if (is_array($groups)) {
4287 $grouptest = 'gm.groupid IN (' . implode(',', $groups) . ')';
4289 $grouptest = 'gm.groupid = ' . $groups;
4291 $grouptest = 'ra.userid IN (SELECT userid FROM ' .
4292 $CFG->prefix
. 'groups_members gm WHERE ' . $grouptest . ')';
4294 if ($useviewallgroups) {
4295 $viewallgroupsusers = get_users_by_capability($context,
4296 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
4297 $wherecond['groups'] = '('. $grouptest . ' OR ra.userid IN (' .
4298 implode(',', array_keys($viewallgroupsusers)) . '))';
4300 $wherecond['groups'] = '(' . $grouptest .')';
4305 if (!empty($exceptions)) {
4306 $wherecond['userexceptions'] = ' u.id NOT IN ('.$exceptions.')';
4309 /// Set up hidden role-assignments sql
4310 if ($view && !has_capability('moodle/role:viewhiddenassigns', $context)) {
4311 $condhiddenra = 'AND ra.hidden = 0 ';
4312 $sscondhiddenra = 'AND ssra.hidden = 0 ';
4315 $sscondhiddenra = '';
4318 // Collect WHERE conditions
4319 $where = implode(' AND ', array_values($wherecond));
4321 $where = 'WHERE ' . $where;
4324 /// Set up default fields
4325 if (empty($fields)) {
4326 if ($iscoursepage) {
4327 $fields = 'u.*, ul.timeaccess as lastaccess';
4333 /// Set up default sort
4334 if (empty($sort)) { // default to course lastaccess or just lastaccess
4335 if ($iscoursepage) {
4336 $sort = 'ul.timeaccess';
4338 $sort = 'u.lastaccess';
4341 $sortby = $sort ?
" ORDER BY $sort " : '';
4343 // User lastaccess JOIN
4344 if ((strpos($sort, 'ul.timeaccess') === FALSE) and (strpos($fields, 'ul.timeaccess') === FALSE)) { // user_lastaccess is not required MDL-13810
4347 $uljoin = "LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul
4348 ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
4352 // Simple cases - No negative permissions means we can take shortcuts
4356 // at the frontpage, and all site users have it - easy!
4357 if ($isfrontpage && !empty($CFG->defaultfrontpageroleid
)
4358 && in_array((int)$CFG->defaultfrontpageroleid
, $roleids, true)) {
4360 return get_records_sql("SELECT $fields
4361 FROM {$CFG->prefix}user u
4363 $limitfrom, $limitnum);
4366 // all site users have it, anyway
4367 // TODO: NOT ALWAYS! Check this case because this gets run for cases like this:
4368 // 1) Default role has the permission for a module thing like mod/choice:choose
4369 // 2) We are checking for an activity module context in a course
4370 // 3) Thus all users are returned even though course:view is also required
4371 if ($defaultroleinteresting) {
4372 $sql = "SELECT $fields
4373 FROM {$CFG->prefix}user u
4377 return get_records_sql($sql, $limitfrom, $limitnum);
4380 /// Simple SQL assuming no negative rolecaps.
4381 /// We use a subselect to grab the role assignments
4382 /// ensuring only one row per user -- even if they
4383 /// have many "relevant" role assignments.
4384 $select = " SELECT $fields";
4385 $from = " FROM {$CFG->prefix}user u
4386 JOIN (SELECT DISTINCT ssra.userid
4387 FROM {$CFG->prefix}role_assignments ssra
4388 WHERE ssra.contextid IN ($ctxids)
4389 AND ssra.roleid IN (".implode(',',$roleids) .")
4391 ) ra ON ra.userid = u.id
4393 $where = " WHERE u.deleted = 0 ";
4394 if (count(array_keys($wherecond))) {
4395 $where .= ' AND ' . implode(' AND ', array_values($wherecond));
4397 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
4401 // If there are any negative rolecaps, we need to
4402 // work through a subselect that will bring several rows
4403 // per user (one per RA).
4404 // Since we cannot do the job in pure SQL (not without SQL stored
4405 // procedures anyway), we end up tied to processing the data in PHP
4406 // all the way down to pagination.
4408 // In some cases, this will mean bringing across a ton of data --
4409 // when paginating, we have to walk the permisisons of all the rows
4410 // in the _previous_ pages to get the pagination correct in the case
4411 // of users that end up not having the permission - this removed.
4414 // Prepare the role permissions datastructure for fast lookups
4415 $roleperms = array(); // each role cap and depth
4416 foreach ($capdefs AS $rcid=>$rc) {
4418 $rid = (int)$rc->roleid
;
4419 $perm = (int)$rc->permission
;
4420 $rcdepth = (int)$rc->ctxdepth
;
4421 if (!isset($roleperms[$rc->capability
][$rid])) {
4422 $roleperms[$rc->capability
][$rid] = (object)array('perm' => $perm,
4423 'rcdepth' => $rcdepth);
4425 if ($roleperms[$rc->capability
][$rid]->perm
== CAP_PROHIBIT
) {
4428 // override - as we are going
4429 // from general to local perms
4430 // (as per the ORDER BY...depth ASC above)
4431 // and local perms win...
4432 $roleperms[$rc->capability
][$rid] = (object)array('perm' => $perm,
4433 'rcdepth' => $rcdepth);
4438 if ($context->contextlevel
== CONTEXT_SYSTEM
4440 ||
$defaultroleinteresting) {
4442 // Handle system / sitecourse / defaultrole-with-perhaps-neg-overrides
4443 // with a SELECT FROM user LEFT OUTER JOIN against ra -
4444 // This is expensive on the SQL and PHP sides -
4445 // moves a ton of data across the wire.
4446 $ss = "SELECT u.id as userid, ra.roleid,
4448 FROM {$CFG->prefix}user u
4449 LEFT OUTER JOIN {$CFG->prefix}role_assignments ra
4450 ON (ra.userid = u.id
4451 AND ra.contextid IN ($ctxids)
4452 AND ra.roleid IN (".implode(',',$roleids) .")
4454 LEFT OUTER JOIN {$CFG->prefix}context ctx
4455 ON ra.contextid=ctx.id
4458 // "Normal complex case" - the rolecaps we are after will
4459 // be defined in a role assignment somewhere.
4460 $ss = "SELECT ra.userid as userid, ra.roleid,
4462 FROM {$CFG->prefix}role_assignments ra
4463 JOIN {$CFG->prefix}context ctx
4464 ON ra.contextid=ctx.id
4465 WHERE ra.contextid IN ($ctxids)
4467 AND ra.roleid IN (".implode(',',$roleids) .")";
4470 $select = "SELECT $fields ,ra.roleid, ra.depth ";
4471 $from = "FROM ($ss) ra
4472 JOIN {$CFG->prefix}user u
4475 $where = "WHERE u.deleted = 0 ";
4476 if (count(array_keys($wherecond))) {
4477 $where .= ' AND ' . implode(' AND ', array_values($wherecond));
4480 // Each user's entries MUST come clustered together
4481 // and RAs ordered in depth DESC - the role/cap resolution
4482 // code depends on this.
4483 $sort .= ' , ra.userid ASC, ra.depth DESC';
4484 $sortby .= ' , ra.userid ASC, ra.depth DESC ';
4486 $rs = get_recordset_sql($select.$from.$where.$sortby);
4489 // Process the user accounts+RAs, folding repeats together...
4491 // The processing for this recordset is tricky - to fold
4492 // the role/perms of users with multiple role-assignments
4493 // correctly while still processing one-row-at-a-time
4494 // we need to add a few additional 'private' fields to
4495 // the results array - so we can treat the rows as a
4496 // state machine to track the cap/perms and at what RA-depth
4497 // and RC-depth they were defined.
4499 // So what we do here is:
4500 // - loop over rows, checking pagination limits
4501 // - when we find a new user, if we are in the page add it to the
4502 // $results, and start building $ras array with its role-assignments
4503 // - when we are dealing with the next user, or are at the end of the userlist
4504 // (last rec or last in page), trigger the check-permission idiom
4505 // - the check permission idiom will
4506 // - add the default enrolment if needed
4507 // - call has_capability_from_rarc(), which based on RAs and RCs will return a bool
4508 // (should be fairly tight code ;-) )
4509 // - if the user has permission, all is good, just $c++ (counter)
4510 // - ...else, decrease the counter - so pagination is kept straight,
4511 // and (if we are in the page) remove from the results
4515 // pagination controls
4517 $limitfrom = (int)$limitfrom;
4518 $limitnum = (int)$limitnum;
4521 // Track our last user id so we know when we are dealing
4522 // with a new user...
4527 // $ras: role assignments, multidimensional array
4528 // treat as a stack - going from local to general
4529 // $ras = (( roleid=> x, $depth=>y) , ( roleid=> x, $depth=>y))
4531 while ($user = rs_fetch_next_record($rs)) {
4533 //error_log(" Record: " . print_r($user,1));
4536 // Pagination controls
4537 // Note that we might end up removing a user
4538 // that ends up _not_ having the rights,
4539 // therefore rolling back $c
4541 if ($lastuserid != $user->id
) {
4543 // Did the last user end up with a positive permission?
4544 if ($lastuserid !=0) {
4545 if ($defaultroleinteresting) {
4546 // add the role at the end of $ras
4547 $ras[] = array( 'roleid' => $CFG->defaultuserroleid
,
4550 if (has_capability_from_rarc($ras, $roleperms, $capability, $doanything)) {
4553 // remove the user from the result set,
4554 // only if we are 'in the page'
4555 if ($limitfrom === 0 ||
$c >= $limitfrom) {
4556 unset($results[$lastuserid]);
4561 // Did we hit pagination limit?
4562 if ($limitnum !==0 && $c >= ($limitfrom+
$limitnum)) { // we are done!
4566 // New user setup, and $ras reset
4567 $lastuserid = $user->id
;
4569 if (!empty($user->roleid
)) {
4570 $ras[] = array( 'roleid' => (int)$user->roleid
,
4571 'depth' => (int)$user->depth
);
4574 // if we are 'in the page', also add the rec
4575 // to the results...
4576 if ($limitfrom === 0 ||
$c >= $limitfrom) {
4577 $results[$user->id
] = $user; // trivial
4580 // Additional RA for $lastuserid
4581 $ras[] = array( 'roleid'=>(int)$user->roleid
,
4582 'depth'=>(int)$user->depth
);
4585 } // end while(fetch)
4587 // Prune last entry if necessary
4588 if ($lastuserid !=0) {
4589 if ($defaultroleinteresting) {
4590 // add the role at the end of $ras
4591 $ras[] = array( 'roleid' => $CFG->defaultuserroleid
,
4594 if (!has_capability_from_rarc($ras, $roleperms, $capability, $doanything)) {
4595 // remove the user from the result set,
4596 // only if we are 'in the page'
4597 if ($limitfrom === 0 ||
$c >= $limitfrom) {
4598 if (isset($results[$lastuserid])) {
4599 unset($results[$lastuserid]);
4609 * Fast (fast!) utility function to resolve if a capability is granted,
4610 * based on Role Assignments and Role Capabilities.
4612 * Used (at least) by get_users_by_capability().
4614 * If PHP had fast built-in memoize functions, we could
4615 * add a $contextid parameter and memoize the return values.
4617 * @param array $ras - role assignments
4618 * @param array $roleperms - role permissions
4619 * @param string $capability - name of the capability
4620 * @param bool $doanything
4624 function has_capability_from_rarc($ras, $roleperms, $capability, $doanything) {
4625 // Mini-state machine, using $hascap
4626 // $hascap[ 'moodle/foo:bar' ]->perm = CAP_SOMETHING (numeric constant)
4627 // $hascap[ 'moodle/foo:bar' ]->radepth = depth of the role assignment that set it
4628 // $hascap[ 'moodle/foo:bar' ]->rcdepth = depth of the rolecap that set it
4629 // -- when resolving conflicts, we need to look into radepth first, if unresolved
4631 $caps = array($capability);
4633 $caps[] = 'moodle/site:candoanything';
4639 // Compute which permission/roleassignment/rolecap
4640 // wins for each capability we are walking
4642 foreach ($ras as $ra) {
4643 foreach ($caps as $cap) {
4644 if (!isset($roleperms[$cap][$ra['roleid']])) {
4645 // nothing set for this cap - skip
4648 // We explicitly clone here as we
4649 // add more properties to it
4650 // that must stay separate from the
4651 // original roleperm data structure
4652 $rp = clone($roleperms[$cap][$ra['roleid']]);
4653 $rp->radepth
= $ra['depth'];
4655 // Trivial case, we are the first to set
4656 if (!isset($hascap[$cap])) {
4657 $hascap[$cap] = $rp;
4661 // Resolve who prevails, in order of precendence
4662 // - Prohibits always wins
4667 if ($rp->perm
=== CAP_PROHIBIT
) {
4668 $hascap[$cap] = $rp;
4671 if ($hascap[$cap]->perm
=== CAP_PROHIBIT
) {
4675 // Locality of RA - the look is ordered by depth DESC
4676 // so from local to general -
4677 // Higher RA loses to local RA... unless perm===0
4678 /// Thanks to the order of the records, $rp->radepth <= $hascap[$cap]->radepth
4679 if ($rp->radepth
> $hascap[$cap]->radepth
) {
4680 error_log('Should not happen @ ' . __FUNCTION__
.':'.__LINE__
);
4682 if ($rp->radepth
< $hascap[$cap]->radepth
) {
4683 if ($hascap[$cap]->perm
!==0) {
4684 // Wider RA loses to local RAs...
4687 // "Higher RA resolves conflict" case,
4688 // local RAs had cancelled eachother
4689 $hascap[$cap] = $rp;
4693 // Same ralevel - locality of RC wins
4694 if ($rp->rcdepth
> $hascap[$cap]->rcdepth
) {
4695 $hascap[$cap] = $rp;
4698 if ($rp->rcdepth
> $hascap[$cap]->rcdepth
) {
4701 // We match depth - add them
4702 $hascap[$cap]->perm +
= $rp->perm
;
4705 if ($hascap[$capability]->perm
> 0
4706 ||
($doanything && isset($hascap['moodle/site:candoanything'])
4707 && $hascap['moodle/site:candoanything']->perm
> 0)) {
4714 * Will re-sort a $users results array (from get_users_by_capability(), usually)
4715 * based on a sorting policy. This is to support the odd practice of
4716 * sorting teachers by 'authority', where authority was "lowest id of the role
4719 * Will execute 1 database query. Only suitable for small numbers of users, as it
4720 * uses an u.id IN() clause.
4722 * Notes about the sorting criteria.
4724 * As a default, we cannot rely on role.sortorder because then
4725 * admins/coursecreators will always win. That is why the sane
4726 * rule "is locality matters most", with sortorder as 2nd
4729 * If you want role.sortorder, use the 'sortorder' policy, and
4730 * name explicitly what roles you want to cover. It's probably
4731 * a good idea to see what roles have the capabilities you want
4732 * (array_diff() them against roiles that have 'can-do-anything'
4733 * to weed out admin-ish roles. Or fetch a list of roles from
4734 * variables like $CFG->coursemanagers .
4736 * @param array users Users' array, keyed on userid
4737 * @param object context
4738 * @param array roles - ids of the roles to include, optional
4739 * @param string policy - defaults to locality, more about
4740 * @return array - sorted copy of the array
4742 function sort_by_roleassignment_authority($users, $context, $roles=array(), $sortpolicy='locality') {
4745 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
4746 $contextwhere = ' ra.contextid IN ('.str_replace('/', ',',substr($context->path
, 1)).')';
4747 if (empty($roles)) {
4750 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
4753 $sql = "SELECT ra.userid
4754 FROM {$CFG->prefix}role_assignments ra
4755 JOIN {$CFG->prefix}role r
4757 JOIN {$CFG->prefix}context ctx
4758 ON ra.contextid=ctx.id
4765 // Default 'locality' policy -- read PHPDoc notes
4766 // about sort policies...
4767 $orderby = 'ORDER BY
4768 ctx.depth DESC, /* locality wins */
4769 r.sortorder ASC, /* rolesorting 2nd criteria */
4770 ra.id /* role assignment order tie-breaker */';
4771 if ($sortpolicy === 'sortorder') {
4772 $orderby = 'ORDER BY
4773 r.sortorder ASC, /* rolesorting 2nd criteria */
4774 ra.id /* role assignment order tie-breaker */';
4777 $sortedids = get_fieldset_sql($sql . $orderby);
4778 $sortedusers = array();
4781 foreach ($sortedids as $id) {
4783 if (isset($seen[$id])) {
4789 $sortedusers[$id] = $users[$id];
4791 return $sortedusers;
4795 * gets all the users assigned this role in this context or higher
4796 * @param int roleid (can also be an array of ints!)
4797 * @param int contextid
4798 * @param bool parent if true, get list of users assigned in higher context too
4799 * @param string fields - fields from user (u.) , role assignment (ra) or role (r.)
4800 * @param string sort - sort from user (u.) , role assignment (ra) or role (r.)
4801 * @param bool gethidden - whether to fetch hidden enrolments too
4804 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $gethidden=true, $group='', $limitfrom='', $limitnum='') {
4807 if (empty($fields)) {
4808 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
4809 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
4810 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4811 'u.emailstop, u.lang, u.timezone, r.name as rolename';
4814 // whether this assignment is hidden
4815 $hiddensql = $gethidden ?
'': ' AND ra.hidden = 0 ';
4817 $parentcontexts = '';
4819 $parentcontexts = substr($context->path
, 1); // kill leading slash
4820 $parentcontexts = str_replace('/', ',', $parentcontexts);
4821 if ($parentcontexts !== '') {
4822 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4826 if (is_array($roleid)) {
4827 $roleselect = ' AND ra.roleid IN (' . implode(',',$roleid) .')';
4828 } elseif (!empty($roleid)) { // should not test for int, because it can come in as a string
4829 $roleselect = "AND ra.roleid = $roleid";
4835 $groupjoin = "JOIN {$CFG->prefix}groups_members gm
4836 ON gm.userid = u.id";
4837 $groupselect = " AND gm.groupid = $group ";
4843 $SQL = "SELECT $fields, ra.roleid
4844 FROM {$CFG->prefix}role_assignments ra
4845 JOIN {$CFG->prefix}user u
4847 JOIN {$CFG->prefix}role r
4850 WHERE (ra.contextid = $context->id $parentcontexts)
4855 "; // join now so that we can just use fullname() later
4857 return get_records_sql($SQL, $limitfrom, $limitnum);
4861 * Counts all the users assigned this role in this context or higher
4863 * @param int contextid
4864 * @param bool parent if true, get list of users assigned in higher context too
4867 function count_role_users($roleid, $context, $parent=false) {
4871 if ($contexts = get_parent_contexts($context)) {
4872 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4874 $parentcontexts = '';
4877 $parentcontexts = '';
4880 $SQL = "SELECT count(u.id)
4881 FROM {$CFG->prefix}role_assignments r
4882 JOIN {$CFG->prefix}user u
4884 WHERE (r.contextid = $context->id $parentcontexts)
4885 AND r.roleid = $roleid
4888 return count_records_sql($SQL);
4892 * This function gets the list of courses that this user has a particular capability in.
4893 * It is still not very efficient.
4894 * @param string $capability Capability in question
4895 * @param int $userid User ID or null for current user
4896 * @param bool $doanything True if 'doanything' is permitted (default)
4897 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4898 * otherwise use a comma-separated list of the fields you require, not including id
4899 * @param string $orderby If set, use a comma-separated list of fields from course
4900 * table with sql modifiers (DESC) if needed
4901 * @return array Array of courses, may have zero entries. Or false if query failed.
4903 function get_user_capability_course($capability, $userid=NULL,$doanything=true,$fieldsexceptid='',$orderby='') {
4904 // Convert fields list and ordering
4906 if($fieldsexceptid) {
4907 $fields=explode(',',$fieldsexceptid);
4908 foreach($fields as $field) {
4909 $fieldlist.=',c.'.$field;
4913 $fields=explode(',',$orderby);
4915 foreach($fields as $field) {
4919 $orderby.='c.'.$field;
4921 $orderby='ORDER BY '.$orderby;
4924 // Obtain a list of everything relevant about all courses including context.
4925 // Note the result can be used directly as a context (we are going to), the course
4926 // fields are just appended.
4928 $rs=get_recordset_sql("
4930 x.*,c.id AS courseid$fieldlist
4932 {$CFG->prefix}course c
4933 INNER JOIN {$CFG->prefix}context x ON c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE
."
4940 // Check capability for each course in turn
4942 while($coursecontext=rs_fetch_next_record($rs)) {
4943 if(has_capability($capability,$coursecontext,$userid,$doanything)) {
4944 // We've got the capability. Make the record look like a course record
4946 $coursecontext->id
=$coursecontext->courseid
;
4947 unset($coursecontext->courseid
);
4948 unset($coursecontext->contextlevel
);
4949 unset($coursecontext->instanceid
);
4950 $courses[]=$coursecontext;
4956 /** This function finds the roles assigned directly to this context only
4957 * i.e. no parents role
4958 * @param object $context
4961 function get_roles_on_exact_context($context) {
4965 return get_records_sql("SELECT r.*
4966 FROM {$CFG->prefix}role_assignments ra,
4967 {$CFG->prefix}role r
4968 WHERE ra.roleid = r.id
4969 AND ra.contextid = $context->id");
4974 * Switches the current user to another role for the current session and only
4975 * in the given context.
4977 * The caller *must* check
4978 * - that this op is allowed
4979 * - that the requested role can be assigned in this ctx
4980 * (hint, use get_assignable_roles())
4981 * - that the requested role is NOT $CFG->defaultuserroleid
4983 * To "unswitch" pass 0 as the roleid.
4985 * This function *will* modify $USER->access - beware
4987 * @param integer $roleid
4988 * @param object $context
4991 function role_switch($roleid, $context) {
4997 // - Add the ghost RA to $USER->access
4998 // as $USER->access['rsw'][$path] = $roleid
5000 // - Make sure $USER->access['rdef'] has the roledefs
5001 // it needs to honour the switcheroo
5003 // Roledefs will get loaded "deep" here - down to the last child
5004 // context. Note that
5006 // - When visiting subcontexts, our selective accessdata loading
5007 // will still work fine - though those ra/rdefs will be ignored
5008 // appropriately while the switch is in place
5010 // - If a switcheroo happens at a category with tons of courses
5011 // (that have many overrides for switched-to role), the session
5012 // will get... quite large. Sometimes you just can't win.
5014 // To un-switch just unset($USER->access['rsw'][$path])
5017 // Add the switch RA
5018 if (!isset($USER->access
['rsw'])) {
5019 $USER->access
['rsw'] = array();
5023 unset($USER->access
['rsw'][$context->path
]);
5024 if (empty($USER->access
['rsw'])) {
5025 unset($USER->access
['rsw']);
5030 $USER->access
['rsw'][$context->path
]=$roleid;
5033 $USER->access
= get_role_access_bycontext($roleid, $context,
5036 /* DO WE NEED THIS AT ALL???
5037 // Add some permissions we are really going
5038 // to always need, even if the role doesn't have them!
5040 $USER->capabilities[$context->id]['moodle/course:view'] = CAP_ALLOW;
5047 // get any role that has an override on exact context
5048 function get_roles_with_override_on_context($context) {
5052 return get_records_sql("SELECT r.*
5053 FROM {$CFG->prefix}role_capabilities rc,
5054 {$CFG->prefix}role r
5055 WHERE rc.roleid = r.id
5056 AND rc.contextid = $context->id");
5059 // get all capabilities for this role on this context (overrids)
5060 function get_capabilities_from_role_on_context($role, $context) {
5064 return get_records_sql("SELECT *
5065 FROM {$CFG->prefix}role_capabilities
5066 WHERE contextid = $context->id
5067 AND roleid = $role->id");
5070 // find out which roles has assignment on this context
5071 function get_roles_with_assignment_on_context($context) {
5075 return get_records_sql("SELECT r.*
5076 FROM {$CFG->prefix}role_assignments ra,
5077 {$CFG->prefix}role r
5078 WHERE ra.roleid = r.id
5079 AND ra.contextid = $context->id");
5085 * Find all user assignemnt of users for this role, on this context
5087 function get_users_from_role_on_context($role, $context) {
5091 return get_records_sql("SELECT *
5092 FROM {$CFG->prefix}role_assignments
5093 WHERE contextid = $context->id
5094 AND roleid = $role->id");
5098 * Simple function returning a boolean true if roles exist, otherwise false
5100 function user_has_role_assignment($userid, $roleid, $contextid=0) {
5103 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
5105 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
5110 * Get role name or alias if exists and format the text.
5111 * @param object $role role object
5112 * @param object $coursecontext
5113 * @return $string name of role in course context
5115 function role_get_name($role, $coursecontext) {
5116 if ($r = get_record('role_names','roleid', $role->id
,'contextid', $coursecontext->id
)) {
5117 return strip_tags(format_string($r->name
));
5119 return strip_tags(format_string($role->name
));
5124 * Prepare list of roles for display, apply aliases and format text
5125 * @param array $roleoptions array roleid=>rolename
5126 * @param object $context
5127 * @return array of role names
5129 function role_fix_names($roleoptions, $context, $rolenamedisplay=ROLENAME_ALIAS
) {
5130 if ($rolenamedisplay != ROLENAME_ORIGINAL
&& !empty($context->id
)) {
5131 if ($context->contextlevel
== CONTEXT_MODULE ||
$context->contextlevel
== CONTEXT_BLOCK
) { // find the parent course context
5132 if ($parentcontextid = array_shift(get_parent_contexts($context))) {
5133 $context = get_context_instance_by_id($parentcontextid);
5136 if ($aliasnames = get_records('role_names', 'contextid', $context->id
)) {
5137 if ($rolenamedisplay == ROLENAME_ALIAS
) {
5138 foreach ($aliasnames as $alias) {
5139 if (isset($roleoptions[$alias->roleid
])) {
5140 $roleoptions[$alias->roleid
] = format_string($alias->name
);
5143 } else if ($rolenamedisplay == ROLENAME_BOTH
) {
5144 foreach ($aliasnames as $alias) {
5145 if (isset($roleoptions[$alias->roleid
])) {
5146 $roleoptions[$alias->roleid
] = format_string($alias->name
).' ('.format_string($roleoptions[$alias->roleid
]).')';
5152 foreach ($roleoptions as $rid => $name) {
5153 $roleoptions[$rid] = strip_tags($name);
5155 return $roleoptions;
5159 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
5160 * when we read in a new capability
5161 * most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
5162 * but when we are in grade, all reports/import/export capabilites should be together
5163 * @param string a - component string a
5164 * @param string b - component string b
5165 * @return bool - whether 2 component are in different "sections"
5167 function component_level_changed($cap, $comp, $contextlevel) {
5169 if ($cap->component
== 'enrol/authorize' && $comp =='enrol/authorize') {
5173 if (strstr($cap->component
, '/') && strstr($comp, '/')) {
5174 $compsa = explode('/', $cap->component
);
5175 $compsb = explode('/', $comp);
5179 // we are in gradebook, still
5180 if (($compsa[0] == 'gradeexport' ||
$compsa[0] == 'gradeimport' ||
$compsa[0] == 'gradereport') &&
5181 ($compsb[0] == 'gradeexport' ||
$compsb[0] == 'gradeimport' ||
$compsb[0] == 'gradereport')) {
5186 return ($cap->component
!= $comp ||
$cap->contextlevel
!= $contextlevel);
5190 * Populate context.path and context.depth where missing.
5191 * @param bool $force force a complete rebuild of the path and depth fields.
5192 * @param bool $feedback display feedback (during upgrade usually)
5195 function build_context_path($force=false, $feedback=false) {
5197 require_once($CFG->libdir
.'/ddllib.php');
5200 $sitectx = get_system_context(!$force);
5201 $base = '/'.$sitectx->id
;
5204 $sitecoursectx = get_record('context',
5205 'contextlevel', CONTEXT_COURSE
,
5206 'instanceid', SITEID
);
5207 if ($force ||
$sitecoursectx->path
!== "$base/{$sitecoursectx->id}") {
5208 set_field('context', 'path', "$base/{$sitecoursectx->id}",
5209 'id', $sitecoursectx->id
);
5210 set_field('context', 'depth', 2,
5211 'id', $sitecoursectx->id
);
5212 $sitecoursectx = get_record('context',
5213 'contextlevel', CONTEXT_COURSE
,
5214 'instanceid', SITEID
);
5217 $ctxemptyclause = " AND (ctx.path IS NULL
5219 $emptyclause = " AND ({$CFG->prefix}context.path IS NULL
5220 OR {$CFG->prefix}context.depth=0) ";
5222 $ctxemptyclause = $emptyclause = '';
5226 * - mysql does not allow to use FROM in UPDATE statements
5227 * - using two tables after UPDATE works in mysql, but might give unexpected
5228 * results in pg 8 (depends on configuration)
5229 * - using table alias in UPDATE does not work in pg < 8.2
5231 if ($CFG->dbfamily
== 'mysql') {
5232 $updatesql = "UPDATE {$CFG->prefix}context ct, {$CFG->prefix}context_temp temp
5233 SET ct.path = temp.path,
5234 ct.depth = temp.depth
5235 WHERE ct.id = temp.id";
5236 } else if ($CFG->dbfamily
== 'oracle') {
5237 $updatesql = "UPDATE {$CFG->prefix}context ct
5238 SET (ct.path, ct.depth) =
5239 (SELECT temp.path, temp.depth
5240 FROM {$CFG->prefix}context_temp temp
5241 WHERE temp.id=ct.id)
5242 WHERE EXISTS (SELECT 'x'
5243 FROM {$CFG->prefix}context_temp temp
5244 WHERE temp.id = ct.id)";
5246 $updatesql = "UPDATE {$CFG->prefix}context
5247 SET path = temp.path,
5249 FROM {$CFG->prefix}context_temp temp
5250 WHERE temp.id={$CFG->prefix}context.id";
5253 $udelsql = "TRUNCATE TABLE {$CFG->prefix}context_temp";
5255 // Top level categories
5256 $sql = "UPDATE {$CFG->prefix}context
5257 SET depth=2, path=" . sql_concat("'$base/'", 'id') . "
5258 WHERE contextlevel=".CONTEXT_COURSECAT
."
5259 AND EXISTS (SELECT 'x'
5260 FROM {$CFG->prefix}course_categories cc
5261 WHERE cc.id = {$CFG->prefix}context.instanceid
5265 execute_sql($sql, $feedback);
5267 execute_sql($udelsql, $feedback);
5269 // Deeper categories - one query per depthlevel
5270 $maxdepth = get_field_sql("SELECT MAX(depth)
5271 FROM {$CFG->prefix}course_categories");
5272 for ($n=2;$n<=$maxdepth;$n++
) {
5273 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5274 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", $n+1
5275 FROM {$CFG->prefix}context ctx
5276 JOIN {$CFG->prefix}course_categories c ON ctx.instanceid=c.id
5277 JOIN {$CFG->prefix}context pctx ON c.parent=pctx.instanceid
5278 WHERE ctx.contextlevel=".CONTEXT_COURSECAT
."
5279 AND pctx.contextlevel=".CONTEXT_COURSECAT
."
5281 AND NOT EXISTS (SELECT 'x'
5282 FROM {$CFG->prefix}context_temp temp
5283 WHERE temp.id = ctx.id)
5285 execute_sql($sql, $feedback);
5287 // this is needed after every loop
5289 execute_sql($updatesql, $feedback);
5290 execute_sql($udelsql, $feedback);
5293 // Courses -- except sitecourse
5294 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5295 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5296 FROM {$CFG->prefix}context ctx
5297 JOIN {$CFG->prefix}course c ON ctx.instanceid=c.id
5298 JOIN {$CFG->prefix}context pctx ON c.category=pctx.instanceid
5299 WHERE ctx.contextlevel=".CONTEXT_COURSE
."
5300 AND c.id!=".SITEID
."
5301 AND pctx.contextlevel=".CONTEXT_COURSECAT
."
5302 AND NOT EXISTS (SELECT 'x'
5303 FROM {$CFG->prefix}context_temp temp
5304 WHERE temp.id = ctx.id)
5306 execute_sql($sql, $feedback);
5308 execute_sql($updatesql, $feedback);
5309 execute_sql($udelsql, $feedback);
5312 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5313 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5314 FROM {$CFG->prefix}context ctx
5315 JOIN {$CFG->prefix}course_modules cm ON ctx.instanceid=cm.id
5316 JOIN {$CFG->prefix}context pctx ON cm.course=pctx.instanceid
5317 WHERE ctx.contextlevel=".CONTEXT_MODULE
."
5318 AND pctx.contextlevel=".CONTEXT_COURSE
."
5319 AND NOT EXISTS (SELECT 'x'
5320 FROM {$CFG->prefix}context_temp temp
5321 WHERE temp.id = ctx.id)
5323 execute_sql($sql, $feedback);
5325 execute_sql($updatesql, $feedback);
5326 execute_sql($udelsql, $feedback);
5328 // Blocks - non-pinned course-view only
5329 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5330 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5331 FROM {$CFG->prefix}context ctx
5332 JOIN {$CFG->prefix}block_instance bi ON ctx.instanceid = bi.id
5333 JOIN {$CFG->prefix}context pctx ON bi.pageid=pctx.instanceid
5334 WHERE ctx.contextlevel=".CONTEXT_BLOCK
."
5335 AND pctx.contextlevel=".CONTEXT_COURSE
."
5336 AND bi.pagetype='course-view'
5337 AND NOT EXISTS (SELECT 'x'
5338 FROM {$CFG->prefix}context_temp temp
5339 WHERE temp.id = ctx.id)
5341 execute_sql($sql, $feedback);
5343 execute_sql($updatesql, $feedback);
5344 execute_sql($udelsql, $feedback);
5347 $sql = "UPDATE {$CFG->prefix}context
5348 SET depth=2, path=".sql_concat("'$base/'", 'id')."
5349 WHERE contextlevel=".CONTEXT_BLOCK
."
5350 AND EXISTS (SELECT 'x'
5351 FROM {$CFG->prefix}block_instance bi
5352 WHERE bi.id = {$CFG->prefix}context.instanceid
5353 AND bi.pagetype!='course-view')
5355 execute_sql($sql, $feedback);
5358 $sql = "UPDATE {$CFG->prefix}context
5359 SET depth=2, path=".sql_concat("'$base/'", 'id')."
5360 WHERE contextlevel=".CONTEXT_USER
."
5361 AND EXISTS (SELECT 'x'
5362 FROM {$CFG->prefix}user u
5363 WHERE u.id = {$CFG->prefix}context.instanceid)
5365 execute_sql($sql, $feedback);
5369 //TODO: fix group contexts
5371 // reset static course cache - it might have incorrect cached data
5372 global $context_cache, $context_cache_id;
5373 $context_cache = array();
5374 $context_cache_id = array();
5379 * Update the path field of the context and
5380 * all the dependent subcontexts that follow
5383 * The most important thing here is to be as
5384 * DB efficient as possible. This op can have a
5385 * massive impact in the DB.
5387 * @param obj current context obj
5388 * @param obj newparent new parent obj
5391 function context_moved($context, $newparent) {
5394 $frompath = $context->path
;
5395 $newpath = $newparent->path
. '/' . $context->id
;
5398 if (($newparent->depth +
1) != $context->depth
) {
5399 $setdepth = ", depth= depth + ({$newparent->depth} - {$context->depth}) + 1";
5401 $sql = "UPDATE {$CFG->prefix}context
5404 WHERE path='$frompath'";
5405 execute_sql($sql,false);
5407 $len = strlen($frompath);
5408 $sql = "UPDATE {$CFG->prefix}context
5409 SET path = ".sql_concat("'$newpath'", 'SUBSTR(path, '.$len.' +1)')."
5411 WHERE path LIKE '{$frompath}/%'";
5412 execute_sql($sql,false);
5414 mark_context_dirty($frompath);
5415 mark_context_dirty($newpath);
5420 * Turn the ctx* fields in an objectlike record
5421 * into a context subobject. This allows
5422 * us to SELECT from major tables JOINing with
5423 * context at no cost, saving a ton of context
5426 function make_context_subobj($rec) {
5427 $ctx = new StdClass
;
5428 $ctx->id
= $rec->ctxid
; unset($rec->ctxid
);
5429 $ctx->path
= $rec->ctxpath
; unset($rec->ctxpath
);
5430 $ctx->depth
= $rec->ctxdepth
; unset($rec->ctxdepth
);
5431 $ctx->contextlevel
= $rec->ctxlevel
; unset($rec->ctxlevel
);
5432 $ctx->instanceid
= $rec->id
;
5434 $rec->context
= $ctx;
5439 * Fetch recent dirty contexts to know cheaply whether our $USER->access
5440 * is stale and needs to be reloaded.
5444 * @return array of dirty contexts
5446 function get_dirty_contexts($time) {
5447 return get_cache_flags('accesslib/dirtycontexts', $time-2);
5451 * Mark a context as dirty (with timestamp)
5452 * so as to force reloading of the context.
5453 * @param string $path context path
5455 function mark_context_dirty($path) {
5456 global $CFG, $DIRTYCONTEXTS;
5457 // only if it is a non-empty string
5458 if (is_string($path) && $path !== '') {
5459 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+
$CFG->sessiontimeout
);
5460 if (isset($DIRTYCONTEXTS)) {
5461 $DIRTYCONTEXTS[$path] = 1;
5467 * Will walk the contextpath to answer whether
5468 * the contextpath is dirty
5470 * @param array $contexts array of strings
5471 * @param obj/array dirty contexts from get_dirty_contexts()
5474 function is_contextpath_dirty($pathcontexts, $dirty) {
5476 foreach ($pathcontexts as $ctx) {
5477 $path = $path.'/'.$ctx;
5478 if (isset($dirty[$path])) {
5487 * switch role order (used in admin/roles/manage.php)
5489 * @param int $first id of role to move down
5490 * @param int $second id of role to move up
5492 * @return bool success or failure
5494 function switch_roles($first, $second) {
5496 //first find temorary sortorder number
5497 $tempsort = count_records('role') +
3;
5498 while (get_record('role','sortorder', $tempsort)) {
5503 $r1->id
= $first->id
;
5504 $r1->sortorder
= $tempsort;
5506 $r2->id
= $second->id
;
5507 $r2->sortorder
= $first->sortorder
;
5509 if (!update_record('role', $r1)) {
5510 debugging("Can not update role with ID $r1->id!");
5514 if (!update_record('role', $r2)) {
5515 debugging("Can not update role with ID $r2->id!");
5519 $r1->sortorder
= $second->sortorder
;
5520 if (!update_record('role', $r1)) {
5521 debugging("Can not update role with ID $r1->id!");
5529 * duplicates all the base definitions of a role
5531 * @param object $sourcerole role to copy from
5532 * @param int $targetrole id of role to copy to
5536 function role_cap_duplicate($sourcerole, $targetrole) {
5538 $systemcontext = get_context_instance(CONTEXT_SYSTEM
);
5539 $caps = get_records_sql("SELECT * FROM {$CFG->prefix}role_capabilities
5540 WHERE roleid = $sourcerole->id
5541 AND contextid = $systemcontext->id");
5542 // adding capabilities
5543 foreach ($caps as $cap) {
5545 $cap->roleid
= $targetrole;
5546 insert_record('role_capabilities', $cap);