Replace low level $db->Concat() calls to Moodle sql_concat() cross-db alternative...
[moodle-linuxchix.git] / lib / accesslib.php
blobe57865e257bd706feb851d327b8e2e3e4af98a28
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
9 // //
10 // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * Public API vs internals
28 * -----------------------
30 * General users probably only care about
32 * Context handling
33 * - get_context_instance()
34 * - get_context_instance_by_id()
35 * - get_parent_contexts()
36 * - get_child_contexts()
38 * Whether the user can do something...
39 * - has_capability()
40 * - require_capability()
41 * - require_login() (from moodlelib)
43 * What courses has this user access to?
44 * - get_user_courses_bycap()
46 * What users can do X in this course or context?
47 * - get_context_users_bycap()
48 * - get_context_users_byrole()
50 * Enrol/unenrol
51 * - enrol_into_course()
52 * - role_assign()/role_unassign()
55 * Advanced use
56 * - load_all_capabilities()
57 * - reload_all_capabilities()
58 * - $ACCESS global
59 * - has_capability_in_accessdata()
60 * - is_siteadmin()
61 * - get_user_access_sitewide()
62 * - load_subcontext()
63 * - get_role_access_bycontext()
65 * Name conventions
66 * ----------------
68 * - "ctx" means context
70 * accessdata
71 * ----------
73 * Access control data is held in the "accessdata" array
74 * which - for the logged-in user, will be in $USER->access
76 * For other users can be generated and passed around (but see
77 * the $ACCESS global).
79 * $accessdata is a multidimensional array, holding
80 * role assignments (RAs), role-capabilities-perm sets
81 * (role defs) and a list of courses we have loaded
82 * data for.
84 * Things are keyed on "contextpaths" (the path field of
85 * the context table) for fast walking up/down the tree.
87 * $accessdata[ra][$contextpath]= array($roleid)
88 * [$contextpath]= array($roleid)
89 * [$contextpath]= array($roleid)
91 * Role definitions are stored like this
92 * (no cap merge is done - so it's compact)
94 * $accessdata[rdef][$contextpath:$roleid][mod/forum:viewpost] = 1
95 * [mod/forum:editallpost] = -1
96 * [mod/forum:startdiscussion] = -1000
98 * See how has_capability_in_accessdata() walks up/down the tree.
100 * Normally - specially for the logged-in user, we only load
101 * rdef and ra down to the course level, but not below. This
102 * keeps accessdata small and compact. Below-the-course ra/rdef
103 * are loaded as needed. We keep track of which courses we
104 * have loaded ra/rdef in
106 * $accessdata[loaded] = array($contextpath, $contextpath)
108 * Stale accessdata
109 * ----------------
111 * For the logged-in user, accessdata is long-lived.
113 * On each pageload we load $DIRTYPATHS which lists
114 * context paths affected by changes. Any check at-or-below
115 * a dirty context will trigger a transparent reload of accessdata.
117 * Changes at the sytem level will force the reload for everyone.
119 * Default role caps
120 * -----------------
121 * The default role assignment is not in the DB, so we
122 * add it manually to accessdata.
124 * This means that functions that work directly off the
125 * DB need to ensure that the default role caps
126 * are dealt with appropriately.
130 require_once $CFG->dirroot.'/lib/blocklib.php';
132 // permission definitions
133 define('CAP_INHERIT', 0);
134 define('CAP_ALLOW', 1);
135 define('CAP_PREVENT', -1);
136 define('CAP_PROHIBIT', -1000);
138 // context definitions
139 define('CONTEXT_SYSTEM', 10);
140 define('CONTEXT_USER', 30);
141 define('CONTEXT_COURSECAT', 40);
142 define('CONTEXT_COURSE', 50);
143 define('CONTEXT_GROUP', 60);
144 define('CONTEXT_MODULE', 70);
145 define('CONTEXT_BLOCK', 80);
147 // capability risks - see http://docs.moodle.org/en/Hardening_new_Roles_system
148 define('RISK_MANAGETRUST', 0x0001);
149 define('RISK_CONFIG', 0x0002);
150 define('RISK_XSS', 0x0004);
151 define('RISK_PERSONAL', 0x0008);
152 define('RISK_SPAM', 0x0010);
154 // rolename displays
155 define('ROLENAME_ORIGINAL', 0);// the name as defined in the role definition
156 define('ROLENAME_ALIAS', 1); // the name as defined by a role alias
157 define('ROLENAME_BOTH', 2); // Both, like this: Role alias (Original)
159 require_once($CFG->dirroot.'/group/lib.php');
161 $context_cache = array(); // Cache of all used context objects for performance (by level and instance)
162 $context_cache_id = array(); // Index to above cache by id
164 $DIRTYCONTEXTS = null; // dirty contexts cache
165 $ACCESS = array(); // cache of caps for cron user switching and has_capability for other users (==not $USER)
166 $RDEFS = array(); // role definitions cache - helps a lot with mem usage in cron
168 function get_role_context_caps($roleid, $context) {
169 //this is really slow!!!! - do not use above course context level!
170 $result = array();
171 $result[$context->id] = array();
173 // first emulate the parent context capabilities merging into context
174 $searchcontexts = array_reverse(get_parent_contexts($context));
175 array_push($searchcontexts, $context->id);
176 foreach ($searchcontexts as $cid) {
177 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
178 foreach ($capabilities as $cap) {
179 if (!array_key_exists($cap->capability, $result[$context->id])) {
180 $result[$context->id][$cap->capability] = 0;
182 $result[$context->id][$cap->capability] += $cap->permission;
187 // now go through the contexts bellow given context
188 $searchcontexts = array_keys(get_child_contexts($context));
189 foreach ($searchcontexts as $cid) {
190 if ($capabilities = get_records_select('role_capabilities', "roleid = $roleid AND contextid = $cid")) {
191 foreach ($capabilities as $cap) {
192 if (!array_key_exists($cap->contextid, $result)) {
193 $result[$cap->contextid] = array();
195 $result[$cap->contextid][$cap->capability] = $cap->permission;
200 return $result;
204 * Gets the accessdata for role "sitewide"
205 * (system down to course)
207 * @return array
209 function get_role_access($roleid, $accessdata=NULL) {
211 global $CFG;
213 /* Get it in 1 cheap DB query...
214 * - relevant role caps at the root and down
215 * to the course level - but not below
217 if (is_null($accessdata)) {
218 $accessdata = array(); // named list
219 $accessdata['ra'] = array();
220 $accessdata['rdef'] = array();
221 $accessdata['loaded'] = array();
225 // Overrides for the role IN ANY CONTEXTS
226 // down to COURSE - not below -
228 $sql = "SELECT ctx.path,
229 rc.capability, rc.permission
230 FROM {$CFG->prefix}context ctx
231 JOIN {$CFG->prefix}role_capabilities rc
232 ON rc.contextid=ctx.id
233 WHERE rc.roleid = {$roleid}
234 AND ctx.contextlevel <= ".CONTEXT_COURSE."
235 ORDER BY ctx.depth, ctx.path";
237 // we need extra caching in cron only
238 if (defined('FULLME') and FULLME === 'cron') {
239 static $cron_cache = array();
241 if (!isset($cron_cache[$roleid])) {
242 $cron_cache[$roleid] = array();
243 if ($rs = get_recordset_sql($sql)) {
244 while ($rd = rs_fetch_next_record($rs)) {
245 $cron_cache[$roleid][] = $rd;
247 rs_close($rs);
251 foreach ($cron_cache[$roleid] as $rd) {
252 $k = "{$rd->path}:{$roleid}";
253 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
256 } else {
257 if ($rs = get_recordset_sql($sql)) {
258 while ($rd = rs_fetch_next_record($rs)) {
259 $k = "{$rd->path}:{$roleid}";
260 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
262 unset($rd);
263 rs_close($rs);
267 return $accessdata;
271 * Gets the accessdata for role "sitewide"
272 * (system down to course)
274 * @return array
276 function get_default_frontpage_role_access($roleid, $accessdata=NULL) {
278 global $CFG;
280 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
281 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
284 // Overrides for the role in any contexts related to the course
286 $sql = "SELECT ctx.path,
287 rc.capability, rc.permission
288 FROM {$CFG->prefix}context ctx
289 JOIN {$CFG->prefix}role_capabilities rc
290 ON rc.contextid=ctx.id
291 WHERE rc.roleid = {$roleid}
292 AND (ctx.id = ".SYSCONTEXTID." OR ctx.path LIKE '$base/%')
293 AND ctx.contextlevel <= ".CONTEXT_COURSE."
294 ORDER BY ctx.depth, ctx.path";
296 if ($rs = get_recordset_sql($sql)) {
297 while ($rd = rs_fetch_next_record($rs)) {
298 $k = "{$rd->path}:{$roleid}";
299 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
301 unset($rd);
302 rs_close($rs);
305 return $accessdata;
310 * Get the default guest role
311 * @return object role
313 function get_guest_role() {
314 global $CFG;
316 if (empty($CFG->guestroleid)) {
317 if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
318 $guestrole = array_shift($roles); // Pick the first one
319 set_config('guestroleid', $guestrole->id);
320 return $guestrole;
321 } else {
322 debugging('Can not find any guest role!');
323 return false;
325 } else {
326 if ($guestrole = get_record('role','id', $CFG->guestroleid)) {
327 return $guestrole;
328 } else {
329 //somebody is messing with guest roles, remove incorrect setting and try to find a new one
330 set_config('guestroleid', '');
331 return get_guest_role();
337 * This function returns whether the current user has the capability of performing a function
338 * For example, we can do has_capability('mod/forum:replypost',$context) in forum
339 * @param string $capability - name of the capability (or debugcache or clearcache)
340 * @param object $context - a context object (record from context table)
341 * @param integer $userid - a userid number, empty if current $USER
342 * @param bool $doanything - if false, ignore do anything
343 * @return bool
345 function has_capability($capability, $context, $userid=NULL, $doanything=true) {
346 global $USER, $ACCESS, $CFG, $DIRTYCONTEXTS;
348 // the original $CONTEXT here was hiding serious errors
349 // for security reasons do not reuse previous context
350 if (empty($context)) {
351 debugging('Incorrect context specified');
352 return false;
355 /// Some sanity checks
356 if (debugging('',DEBUG_DEVELOPER)) {
357 static $capsnames = null; // one request per page only
359 if (is_null($capsnames)) {
360 if ($caps = get_records('capabilities', '', '', '', 'id, name')) {
361 $capsnames = array();
362 foreach ($caps as $cap) {
363 $capsnames[$cap->name] = true;
367 if ($capsnames) { // ignore if can not fetch caps
368 if (!isset($capsnames[$capability])) {
369 debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
372 if (!is_bool($doanything)) {
373 debugging('Capability parameter "doanything" is wierd ("'.$doanything.'"). This should be fixed in code.');
377 if (empty($userid)) { // we must accept null, 0, '0', '' etc. in $userid
378 $userid = $USER->id;
381 if (is_null($context->path) or $context->depth == 0) {
382 //this should not happen
383 $contexts = array(SYSCONTEXTID, $context->id);
384 $context->path = '/'.SYSCONTEXTID.'/'.$context->id;
385 debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()', DEBUG_DEVELOPER);
387 } else {
388 $contexts = explode('/', $context->path);
389 array_shift($contexts);
392 if (defined('FULLME') && FULLME === 'cron' && !isset($USER->access)) {
393 // In cron, some modules setup a 'fake' $USER,
394 // ensure we load the appropriate accessdata.
395 if (isset($ACCESS[$userid])) {
396 $DIRTYCONTEXTS = NULL; //load fresh dirty contexts
397 } else {
398 load_user_accessdata($userid);
399 $DIRTYCONTEXTS = array();
401 $USER->access = $ACCESS[$userid];
403 } else if ($USER->id == $userid && !isset($USER->access)) {
404 // caps not loaded yet - better to load them to keep BC with 1.8
405 // not-logged-in user or $USER object set up manually first time here
406 load_all_capabilities();
407 $ACCESS = array(); // reset the cache for other users too, the dirty contexts are empty now
408 $RDEFS = array();
411 // Load dirty contexts list if needed
412 if (!isset($DIRTYCONTEXTS)) {
413 if (isset($USER->access['time'])) {
414 $DIRTYCONTEXTS = get_dirty_contexts($USER->access['time']);
416 else {
417 $DIRTYCONTEXTS = array();
421 // Careful check for staleness...
422 if (count($DIRTYCONTEXTS) !== 0 and is_contextpath_dirty($contexts, $DIRTYCONTEXTS)) {
423 // reload all capabilities - preserving loginas, roleswitches, etc
424 // and then cleanup any marks of dirtyness... at least from our short
425 // term memory! :-)
426 $ACCESS = array();
427 $RDEFS = array();
429 if (defined('FULLME') && FULLME === 'cron') {
430 load_user_accessdata($userid);
431 $USER->access = $ACCESS[$userid];
432 $DIRTYCONTEXTS = array();
434 } else {
435 reload_all_capabilities();
439 // divulge how many times we are called
440 //// error_log("has_capability: id:{$context->id} path:{$context->path} userid:$userid cap:$capability");
442 if ($USER->id == $userid) { // we must accept strings and integers in $userid
444 // For the logged in user, we have $USER->access
445 // which will have all RAs and caps preloaded for
446 // course and above contexts.
448 // Contexts below courses && contexts that do not
449 // hang from courses are loaded into $USER->access
450 // on demand, and listed in $USER->access[loaded]
452 if ($context->contextlevel <= CONTEXT_COURSE) {
453 // Course and above are always preloaded
454 return has_capability_in_accessdata($capability, $context, $USER->access, $doanything);
456 // Load accessdata for below-the-course contexts
457 if (!path_inaccessdata($context->path,$USER->access)) {
458 // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
459 // $bt = debug_backtrace();
460 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
461 load_subcontext($USER->id, $context, $USER->access);
463 return has_capability_in_accessdata($capability, $context, $USER->access, $doanything);
466 if (!isset($ACCESS[$userid])) {
467 load_user_accessdata($userid);
469 if ($context->contextlevel <= CONTEXT_COURSE) {
470 // Course and above are always preloaded
471 return has_capability_in_accessdata($capability, $context, $ACCESS[$userid], $doanything);
473 // Load accessdata for below-the-course contexts as needed
474 if (!path_inaccessdata($context->path, $ACCESS[$userid])) {
475 // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
476 // $bt = debug_backtrace();
477 // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
478 load_subcontext($userid, $context, $ACCESS[$userid]);
480 return has_capability_in_accessdata($capability, $context, $ACCESS[$userid], $doanything);
484 * This function returns whether the current user has any of the capabilities in the
485 * $capabilities array. This is a simple wrapper around has_capability for convinience.
487 * There are probably tricks that could be done to improve the performance here, for example,
488 * check the capabilities that are already cached first.
490 * @param array $capabilities - an array of capability names.
491 * @param object $context - a context object (record from context table)
492 * @param integer $userid - a userid number, empty if current $USER
493 * @param bool $doanything - if false, ignore do anything
494 * @return bool
496 function has_any_capability($capabilities, $context, $userid=NULL, $doanything=true) {
497 foreach ($capabilities as $capability) {
498 if (has_capability($capability, $context, $userid, $doanything)) {
499 return true;
502 return false;
506 * Uses 1 DB query to answer whether a user is an admin at the sitelevel.
507 * It depends on DB schema >=1.7 but does not depend on the new datastructures
508 * in v1.9 (context.path, or $USER->access)
510 * Will return true if the userid has any of
511 * - moodle/site:config
512 * - moodle/legacy:admin
513 * - moodle/site:doanything
515 * @param int $userid
516 * @returns bool $isadmin
518 function is_siteadmin($userid) {
519 global $CFG;
521 $sql = "SELECT SUM(rc.permission)
522 FROM " . $CFG->prefix . "role_capabilities rc
523 JOIN " . $CFG->prefix . "context ctx
524 ON ctx.id=rc.contextid
525 JOIN " . $CFG->prefix . "role_assignments ra
526 ON ra.roleid=rc.roleid AND ra.contextid=ctx.id
527 WHERE ctx.contextlevel=10
528 AND ra.userid={$userid}
529 AND rc.capability IN ('moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything')
530 GROUP BY rc.capability
531 HAVING SUM(rc.permission) > 0";
533 $isadmin = record_exists_sql($sql);
534 return $isadmin;
537 function get_course_from_path ($path) {
538 // assume that nothing is more than 1 course deep
539 if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
540 return $matches[1];
542 return false;
545 function path_inaccessdata($path, $accessdata) {
547 // assume that contexts hang from sys or from a course
548 // this will only work well with stuff that hangs from a course
549 if (in_array($path, $accessdata['loaded'], true)) {
550 // error_log("found it!");
551 return true;
553 $base = '/' . SYSCONTEXTID;
554 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
555 $path = $matches[1];
556 if ($path === $base) {
557 return false;
559 if (in_array($path, $accessdata['loaded'], true)) {
560 return true;
563 return false;
567 * Walk the accessdata array and return true/false.
568 * Deals with prohibits, roleswitching, aggregating
569 * capabilities, etc.
571 * The main feature of here is being FAST and with no
572 * side effects.
574 * Notes:
576 * Switch Roles exits early
577 * -----------------------
578 * cap checks within a switchrole need to exit early
579 * in our bottom up processing so they don't "see" that
580 * there are real RAs that can do all sorts of things.
582 * Switch Role merges with default role
583 * ------------------------------------
584 * If you are a teacher in course X, you have at least
585 * teacher-in-X + defaultloggedinuser-sitewide. So in the
586 * course you'll have techer+defaultloggedinuser.
587 * We try to mimic that in switchrole.
589 * Local-most role definition and role-assignment wins
590 * ---------------------------------------------------
591 * So if the local context has said 'allow', it wins
592 * over a high-level context that says 'deny'.
593 * This is applied when walking rdefs, and RAs.
594 * Only at the same context the values are SUM()med.
596 * The exception is CAP_PROHIBIT.
598 * "Guest default role" exception
599 * ------------------------------
601 * See MDL-7513 and $ignoreguest below for details.
603 * The rule is that
605 * IF we are being asked about moodle/legacy:guest
606 * OR moodle/course:view
607 * FOR a real, logged-in user
608 * AND we reached the top of the path in ra and rdef
609 * AND that role has moodle/legacy:guest === 1...
610 * THEN we act as if we hadn't seen it.
613 * To Do:
615 * - Document how it works
616 * - Rewrite in ASM :-)
619 function has_capability_in_accessdata($capability, $context, $accessdata, $doanything) {
621 global $CFG;
623 $path = $context->path;
625 // build $contexts as a list of "paths" of the current
626 // contexts and parents with the order top-to-bottom
627 $contexts = array($path);
628 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
629 $path = $matches[1];
630 array_unshift($contexts, $path);
633 $ignoreguest = false;
634 if (isset($accessdata['dr'])
635 && ($capability == 'moodle/course:view'
636 || $capability == 'moodle/legacy:guest')) {
637 // At the base, ignore rdefs where moodle/legacy:guest
638 // is set
639 $ignoreguest = $accessdata['dr'];
642 // Coerce it to an int
643 $CAP_PROHIBIT = (int)CAP_PROHIBIT;
645 $cc = count($contexts);
647 $can = 0;
648 $capdepth = 0;
651 // role-switches loop
653 if (isset($accessdata['rsw'])) {
654 // check for isset() is fast
655 // empty() is slow...
656 if (empty($accessdata['rsw'])) {
657 unset($accessdata['rsw']); // keep things fast and unambiguous
658 break;
660 // From the bottom up...
661 for ($n=$cc-1;$n>=0;$n--) {
662 $ctxp = $contexts[$n];
663 if (isset($accessdata['rsw'][$ctxp])) {
664 // Found a switchrole assignment
665 // check for that role _plus_ the default user role
666 $ras = array($accessdata['rsw'][$ctxp],$CFG->defaultuserroleid);
667 for ($rn=0;$rn<2;$rn++) {
668 $roleid = (int)$ras[$rn];
669 // Walk the path for capabilities
670 // from the bottom up...
671 for ($m=$cc-1;$m>=0;$m--) {
672 $capctxp = $contexts[$m];
673 if (isset($accessdata['rdef']["{$capctxp}:$roleid"][$capability])) {
674 $perm = (int)$accessdata['rdef']["{$capctxp}:$roleid"][$capability];
676 // The most local permission (first to set) wins
677 // the only exception is CAP_PROHIBIT
678 if ($can === 0) {
679 $can = $perm;
680 } elseif ($perm === $CAP_PROHIBIT) {
681 $can = $perm;
682 break;
687 // As we are dealing with a switchrole,
688 // we return _here_, do _not_ walk up
689 // the hierarchy any further
690 if ($can < 1) {
691 if ($doanything) {
692 // didn't find it as an explicit cap,
693 // but maybe the user candoanything in this context...
694 return has_capability_in_accessdata('moodle/site:doanything', $context, $accessdata, false);
695 } else {
696 return false;
698 } else {
699 return true;
707 // Main loop for normal RAs
708 // From the bottom up...
710 for ($n=$cc-1;$n>=0;$n--) {
711 $ctxp = $contexts[$n];
712 if (isset($accessdata['ra'][$ctxp])) {
713 // Found role assignments on this leaf
714 $ras = $accessdata['ra'][$ctxp];
716 $rc = count($ras);
717 $ctxcan = 0;
718 $ctxcapdepth = 0;
719 for ($rn=0;$rn<$rc;$rn++) {
720 $roleid = (int)$ras[$rn];
721 $rolecan = 0;
722 $rolecapdepth = 0;
723 // Walk the path for capabilities
724 // from the bottom up...
725 for ($m=$cc-1;$m>=0;$m--) {
726 $capctxp = $contexts[$m];
727 // ignore some guest caps
728 // at base ra and rdef
729 if ($ignoreguest == $roleid
730 && $n === 0
731 && $m === 0
732 && isset($accessdata['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'])
733 && $accessdata['rdef']["{$capctxp}:$roleid"]['moodle/legacy:guest'] > 0) {
734 continue;
736 if (isset($accessdata['rdef']["{$capctxp}:$roleid"][$capability])) {
737 $perm = (int)$accessdata['rdef']["{$capctxp}:$roleid"][$capability];
738 // The most local permission (first to set) wins
739 // the only exception is CAP_PROHIBIT
740 if ($rolecan === 0) {
741 $rolecan = $perm;
742 $rolecapdepth = $m;
743 } elseif ($perm === $CAP_PROHIBIT) {
744 $rolecan = $perm;
745 $rolecapdepth = $m;
746 break;
750 // Rules for RAs at the same context...
751 // - prohibits always wins
752 // - permissions at the same ctxlevel & capdepth are added together
753 // - deeper capdepth wins
754 if ($ctxcan === $CAP_PROHIBIT || $rolecan === $CAP_PROHIBIT) {
755 $ctxcan = $CAP_PROHIBIT;
756 $ctxcapdepth = 0;
757 } elseif ($ctxcapdepth === $rolecapdepth) {
758 $ctxcan += $rolecan;
759 } elseif ($ctxcapdepth < $rolecapdepth) {
760 $ctxcan = $rolecan;
761 $ctxcapdepth = $rolecapdepth;
762 } else { // ctxcaptdepth is deeper
763 // rolecap ignored
766 // The most local RAs with a defined
767 // permission ($ctxcan) win, except
768 // for CAP_PROHIBIT
769 // NOTE: If we want the deepest RDEF to
770 // win regardless of the depth of the RA,
771 // change the elseif below to read
772 // ($can === 0 || $capdepth < $ctxcapdepth) {
773 if ($ctxcan === $CAP_PROHIBIT) {
774 $can = $ctxcan;
775 break;
776 } elseif ($can === 0) { // see note above
777 $can = $ctxcan;
778 $capdepth = $ctxcapdepth;
783 if ($can < 1) {
784 if ($doanything) {
785 // didn't find it as an explicit cap,
786 // but maybe the user candoanything in this context...
787 return has_capability_in_accessdata('moodle/site:doanything', $context, $accessdata, false);
788 } else {
789 return false;
791 } else {
792 return true;
797 function aggregate_roles_from_accessdata($context, $accessdata) {
799 $path = $context->path;
801 // build $contexts as a list of "paths" of the current
802 // contexts and parents with the order top-to-bottom
803 $contexts = array($path);
804 while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
805 $path = $matches[1];
806 array_unshift($contexts, $path);
809 $cc = count($contexts);
811 $roles = array();
812 // From the bottom up...
813 for ($n=$cc-1;$n>=0;$n--) {
814 $ctxp = $contexts[$n];
815 if (isset($accessdata['ra'][$ctxp]) && count($accessdata['ra'][$ctxp])) {
816 // Found assignments on this leaf
817 $addroles = $accessdata['ra'][$ctxp];
818 $roles = array_merge($roles, $addroles);
822 return array_unique($roles);
826 * This is an easy to use function, combining has_capability() with require_course_login().
827 * And will call those where needed.
829 * It checks for a capability assertion being true. If it isn't
830 * then the page is terminated neatly with a standard error message.
832 * If the user is not logged in, or is using 'guest' access or other special "users,
833 * it provides a logon prompt.
835 * @param string $capability - name of the capability
836 * @param object $context - a context object (record from context table)
837 * @param integer $userid - a userid number
838 * @param bool $doanything - if false, ignore do anything
839 * @param string $errorstring - an errorstring
840 * @param string $stringfile - which stringfile to get it from
842 function require_capability($capability, $context, $userid=NULL, $doanything=true,
843 $errormessage='nopermissions', $stringfile='') {
845 global $USER, $CFG;
847 /* Empty $userid means current user, if the current user is not logged in,
848 * then make sure they are (if needed).
849 * Originally there was a check for loaded permissions - it is not needed here.
850 * Context is now required parameter, the cached $CONTEXT was only hiding errors.
852 $errorlink = '';
854 if (empty($userid)) {
855 if ($context->contextlevel == CONTEXT_COURSE) {
856 require_login($context->instanceid);
858 } else if ($context->contextlevel == CONTEXT_MODULE) {
859 if (!$cm = get_record('course_modules', 'id', $context->instanceid)) {
860 error('Incorrect module');
862 if (!$course = get_record('course', 'id', $cm->course)) {
863 error('Incorrect course.');
865 require_course_login($course, true, $cm);
866 $errorlink = $CFG->wwwroot.'/course/view.php?id='.$cm->course;
868 } else if ($context->contextlevel == CONTEXT_SYSTEM) {
869 if (!empty($CFG->forcelogin)) {
870 require_login();
873 } else {
874 require_login();
878 /// OK, if they still don't have the capability then print a nice error message
880 if (!has_capability($capability, $context, $userid, $doanything)) {
881 $capabilityname = get_capability_string($capability);
882 print_error($errormessage, $stringfile, $errorlink, $capabilityname);
887 * Get an array of courses (with magic extra bits)
888 * where the accessdata and in DB enrolments show
889 * that the cap requested is available.
891 * The main use is for get_my_courses().
893 * Notes
895 * - $fields is an array of fieldnames to ADD
896 * so name the fields you really need, which will
897 * be added and uniq'd
899 * - the course records have $c->context which is a fully
900 * valid context object. Saves you a query per course!
902 * - the course records have $c->categorypath to make
903 * category lookups cheap
905 * - current implementation is split in -
907 * - if the user has the cap systemwide, stupidly
908 * grab *every* course for a capcheck. This eats
909 * a TON of bandwidth, specially on large sites
910 * with separate DBs...
912 * - otherwise, fetch "likely" courses with a wide net
913 * that should get us _cheaply_ at least the courses we need, and some
914 * we won't - we get courses that...
915 * - are in a category where user has the cap
916 * - or where use has a role-assignment (any kind)
917 * - or where the course has an override on for this cap
919 * - walk the courses recordset checking the caps oneach one
920 * the checks are all in memory and quite fast
921 * (though we could implement a specialised variant of the
922 * has_capability_in_accessdata() code to speed it up)
924 * @param string $capability - name of the capability
925 * @param array $accessdata - accessdata session array
926 * @param bool $doanything - if false, ignore do anything
927 * @param string $sort - sorting fields - prefix each fieldname with "c."
928 * @param array $fields - additional fields you are interested in...
929 * @param int $limit - set if you want to limit the number of courses
930 * @return array $courses - ordered array of course objects - see notes above
933 function get_user_courses_bycap($userid, $cap, $accessdata, $doanything, $sort='c.sortorder ASC', $fields=NULL, $limit=0) {
935 global $CFG;
937 // Slim base fields, let callers ask for what they need...
938 $basefields = array('id', 'sortorder', 'shortname', 'idnumber');
940 if (!is_null($fields)) {
941 $fields = array_merge($basefields, $fields);
942 $fields = array_unique($fields);
943 } else {
944 $fields = $basefields;
946 $coursefields = 'c.' .implode(',c.', $fields);
948 $sort = trim($sort);
949 if ($sort !== '') {
950 $sort = "ORDER BY $sort";
953 $sysctx = get_context_instance(CONTEXT_SYSTEM);
954 if (has_capability_in_accessdata($cap, $sysctx, $accessdata, $doanything)) {
956 // Apparently the user has the cap sitewide, so walk *every* course
957 // (the cap checks are moderately fast, but this moves massive bandwidth w the db)
958 // Yuck.
960 $sql = "SELECT $coursefields,
961 ctx.id AS ctxid, ctx.path AS ctxpath,
962 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel,
963 cc.path AS categorypath
964 FROM {$CFG->prefix}course c
965 JOIN {$CFG->prefix}course_categories cc
966 ON c.category=cc.id
967 JOIN {$CFG->prefix}context ctx
968 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
969 $sort ";
970 $rs = get_recordset_sql($sql);
971 } else {
973 // narrow down where we have the caps to a few contexts
974 // this will be a combination of
975 // - categories where we have the rights
976 // - courses where we have an explicit enrolment OR that have an override
978 $sql = "SELECT ctx.*
979 FROM {$CFG->prefix}context ctx
980 WHERE ctx.contextlevel=".CONTEXT_COURSECAT."
981 ORDER BY ctx.depth";
982 $rs = get_recordset_sql($sql);
983 $catpaths = array();
984 while ($catctx = rs_fetch_next_record($rs)) {
985 if ($catctx->path != ''
986 && has_capability_in_accessdata($cap, $catctx, $accessdata, $doanything)) {
987 $catpaths[] = $catctx->path;
990 rs_close($rs);
991 $catclause = '';
992 if (count($catpaths)) {
993 $cc = count($catpaths);
994 for ($n=0;$n<$cc;$n++) {
995 $catpaths[$n] = "ctx.path LIKE '{$catpaths[$n]}/%'";
997 $catclause = 'OR (' . implode(' OR ', $catpaths) .')';
999 unset($catpaths);
1001 $capany = '';
1002 if ($doanything) {
1003 $capany = " OR rc.capability='moodle/site:doanything'";
1006 // Note here that we *have* to have the compound clauses
1007 // in the LEFT OUTER JOIN condition for them to return NULL
1008 // appropriately and narrow things down...
1010 $sql = "SELECT $coursefields,
1011 ctx.id AS ctxid, ctx.path AS ctxpath,
1012 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel,
1013 cc.path AS categorypath
1014 FROM {$CFG->prefix}course c
1015 JOIN {$CFG->prefix}course_categories cc
1016 ON c.category=cc.id
1017 JOIN {$CFG->prefix}context ctx
1018 ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
1019 LEFT OUTER JOIN {$CFG->prefix}role_assignments ra
1020 ON (ra.contextid=ctx.id AND ra.userid=$userid)
1021 LEFT OUTER JOIN {$CFG->prefix}role_capabilities rc
1022 ON (rc.contextid=ctx.id AND (rc.capability='$cap' $capany))
1023 WHERE ra.id IS NOT NULL
1024 OR rc.id IS NOT NULL
1025 $catclause
1026 $sort ";
1027 $rs = get_recordset_sql($sql);
1029 $courses = array();
1030 $cc = 0; // keep count
1031 while ($c = rs_fetch_next_record($rs)) {
1032 // build the context obj
1033 $c = make_context_subobj($c);
1035 if (has_capability_in_accessdata($cap, $c->context, $accessdata, $doanything)) {
1036 $courses[] = $c;
1037 if ($limit > 0 && $cc++ > $limit) {
1038 break;
1042 rs_close($rs);
1043 return $courses;
1047 * Draft - use for the course participants list page
1049 * Uses 1 DB query (cheap too - 2~7ms).
1051 * TODO:
1052 * - implement additional where clauses
1053 * - sorting
1054 * - get course participants list to use it!
1056 * returns a users array, both sorted _and_ keyed
1057 * on id (as get_my_courses() does)
1059 * as a bonus, every user record comes with its own
1060 * personal context, as our callers need it straight away
1061 * {save 1 dbquery per user! yay!}
1064 function get_context_users_byrole ($context, $roleid, $fields=NULL, $where=NULL, $sort=NULL, $limit=0) {
1066 global $CFG;
1067 // Slim base fields, let callers ask for what they need...
1068 $basefields = array('id', 'username');
1070 if (!is_null($fields)) {
1071 $fields = array_merge($basefields, $fields);
1072 $fields = array_unique($fields);
1073 } else {
1074 $fields = $basefields;
1076 $userfields = 'u.' .implode(',u.', $fields);
1078 $contexts = substr($context->path, 1); // kill leading slash
1079 $contexts = str_replace('/', ',', $contexts);
1081 $sql = "SELECT $userfields,
1082 ctx.id AS ctxid, ctx.path AS ctxpath,
1083 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1084 FROM {$CFG->prefix}user u
1085 JOIN {$CFG->prefix}context ctx
1086 ON (u.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_USER.")
1087 JOIN {$CFG->prefix}role_assignments ra
1088 ON u.id = ra.userid
1089 WHERE ra.roleid = $roleid
1090 AND ra.contextid IN ($contexts)";
1092 $rs = get_recordset_sql($sql);
1094 $users = array();
1095 $cc = 0; // keep count
1096 while ($u = rs_fetch_next_record($rs)) {
1097 // build the context obj
1098 $u = make_context_subobj($u);
1100 $users[] = $u;
1101 if ($limit > 0 && $cc++ > $limit) {
1102 break;
1105 rs_close($rs);
1106 return $users;
1110 * Draft - use for the course participants list page
1112 * Uses 2 fast DB queries
1114 * TODO:
1115 * - automagically exclude roles that can-doanything sitewide (See callers)
1116 * - perhaps also allow sitewide do-anything via flag
1117 * - implement additional where clauses
1118 * - sorting
1119 * - get course participants list to use it!
1121 * returns a users array, both sorted _and_ keyed
1122 * on id (as get_my_courses() does)
1124 * as a bonus, every user record comes with its own
1125 * personal context, as our callers need it straight away
1126 * {save 1 dbquery per user! yay!}
1129 function get_context_users_bycap ($context, $capability='moodle/course:view', $fields=NULL, $where=NULL, $sort=NULL, $limit=0) {
1130 global $CFG;
1132 // Plan
1134 // - Get all the *interesting* roles -- those that
1135 // have some rolecap entry in our ctx.path contexts
1137 // - Get all RAs for any of those roles in any of our
1138 // interesting contexts, with userid & perm data
1139 // in a nice (per user?) order
1141 // - Walk the resultset, computing the permissions
1142 // - actually - this is all a SQL subselect
1144 // - Fetch user records against the subselect
1147 // Slim base fields, let callers ask for what they need...
1148 $basefields = array('id', 'username');
1150 if (!is_null($fields)) {
1151 $fields = array_merge($basefields, $fields);
1152 $fields = array_unique($fields);
1153 } else {
1154 $fields = $basefields;
1156 $userfields = 'u.' .implode(',u.', $fields);
1158 $contexts = substr($context->path, 1); // kill leading slash
1159 $contexts = str_replace('/', ',', $contexts);
1161 $roles = array();
1162 $sql = "SELECT DISTINCT rc.roleid
1163 FROM {$CFG->prefix}role_capabilities rc
1164 WHERE rc.capability = '$capability'
1165 AND rc.contextid IN ($contexts)";
1166 $rs = get_recordset_sql($sql);
1167 while ($u = rs_fetch_next_record($rs)) {
1168 $roles[] = $u->roleid;
1170 rs_close($rs);
1171 $roles = implode(',', $roles);
1173 if (empty($roles)) {
1174 return array();
1178 // User permissions subselect SQL
1180 // - the open join condition to
1181 // role_capabilities
1183 // - because both rc and ra entries are
1184 // _at or above_ our context, we don't care
1185 // about their depth, we just need to sum them
1187 $sql = "SELECT ra.userid, SUM(rc.permission) AS permission
1188 FROM {$CFG->prefix}role_assignments ra
1189 JOIN {$CFG->prefix}role_capabilities rc
1190 ON (ra.roleid = rc.roleid AND rc.contextid IN ($contexts))
1191 WHERE ra.contextid IN ($contexts)
1192 AND ra.roleid IN ($roles)
1193 GROUP BY ra.userid";
1195 // Get users
1196 $sql = "SELECT $userfields,
1197 ctx.id AS ctxid, ctx.path AS ctxpath,
1198 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
1199 FROM {$CFG->prefix}user u
1200 JOIN {$CFG->prefix}context ctx
1201 ON (u.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_USER.")
1202 JOIN ($sql) up
1203 ON u.id = up.userid
1204 WHERE up.permission > 0 AND u.username != 'guest'";
1206 $rs = get_recordset_sql($sql);
1208 $users = array();
1209 $cc = 0; // keep count
1210 while ($u = rs_fetch_next_record($rs)) {
1211 // build the context obj
1212 $u = make_context_subobj($u);
1214 $users[] = $u;
1215 if ($limit > 0 && $cc++ > $limit) {
1216 break;
1219 rs_close($rs);
1220 return $users;
1224 * It will return a nested array showing role assignments
1225 * all relevant role capabilities for the user at
1226 * site/metacourse/course_category/course levels
1228 * We do _not_ delve deeper than courses because the number of
1229 * overrides at the module/block levels is HUGE.
1231 * [ra] => [/path/] = array(roleid, roleid)
1232 * [rdef] => [/path/:roleid][capability]=permission
1233 * [loaded] => array('/path', '/path')
1235 * @param $userid integer - the id of the user
1238 function get_user_access_sitewide($userid) {
1240 global $CFG;
1242 // this flag has not been set!
1243 // (not clean install, or upgraded successfully to 1.7 and up)
1244 if (empty($CFG->rolesactive)) {
1245 return false;
1248 /* Get in 3 cheap DB queries...
1249 * - role assignments - with role_caps
1250 * - relevant role caps
1251 * - above this user's RAs
1252 * - below this user's RAs - limited to course level
1255 $accessdata = array(); // named list
1256 $accessdata['ra'] = array();
1257 $accessdata['rdef'] = array();
1258 $accessdata['loaded'] = array();
1260 $sitectx = get_system_context();
1261 $base = '/'.$sitectx->id;
1264 // Role assignments - and any rolecaps directly linked
1265 // because it's cheap to read rolecaps here over many
1266 // RAs
1268 $sql = "SELECT ctx.path, ra.roleid, rc.capability, rc.permission
1269 FROM {$CFG->prefix}role_assignments ra
1270 JOIN {$CFG->prefix}context ctx
1271 ON ra.contextid=ctx.id
1272 LEFT OUTER JOIN {$CFG->prefix}role_capabilities rc
1273 ON (rc.roleid=ra.roleid AND rc.contextid=ra.contextid)
1274 WHERE ra.userid = $userid AND ctx.contextlevel <= ".CONTEXT_COURSE."
1275 ORDER BY ctx.depth, ctx.path";
1276 $rs = get_recordset_sql($sql);
1278 // raparents collects paths & roles we need to walk up
1279 // the parenthood to build the rdef
1281 // the array will bulk up a bit with dups
1282 // which we'll later clear up
1284 $raparents = array();
1285 $lastseen = '';
1286 if ($rs) {
1287 while ($ra = rs_fetch_next_record($rs)) {
1288 // RAs leafs are arrays to support multi
1289 // role assignments...
1290 if (!isset($accessdata['ra'][$ra->path])) {
1291 $accessdata['ra'][$ra->path] = array();
1293 // only add if is not a repeat caused
1294 // by capability join...
1295 // (this check is cheaper than in_array())
1296 if ($lastseen !== $ra->path.':'.$ra->roleid) {
1297 $lastseen = $ra->path.':'.$ra->roleid;
1298 array_push($accessdata['ra'][$ra->path], $ra->roleid);
1299 $parentids = explode('/', $ra->path);
1300 array_shift($parentids); // drop empty leading "context"
1301 array_pop($parentids); // drop _this_ context
1303 if (isset($raparents[$ra->roleid])) {
1304 $raparents[$ra->roleid] = array_merge($raparents[$ra->roleid],
1305 $parentids);
1306 } else {
1307 $raparents[$ra->roleid] = $parentids;
1310 // Always add the roleded
1311 if (!empty($ra->capability)) {
1312 $k = "{$ra->path}:{$ra->roleid}";
1313 $accessdata['rdef'][$k][$ra->capability] = $ra->permission;
1316 unset($ra);
1317 rs_close($rs);
1320 // Walk up the tree to grab all the roledefs
1321 // of interest to our user...
1322 // NOTE: we use a series of IN clauses here - which
1323 // might explode on huge sites with very convoluted nesting of
1324 // categories... - extremely unlikely that the number of categories
1325 // and roletypes is so large that we hit the limits of IN()
1326 $clauses = array();
1327 foreach ($raparents as $roleid=>$contexts) {
1328 $contexts = implode(',', array_unique($contexts));
1329 if ($contexts ==! '') {
1330 $clauses[] = "(roleid=$roleid AND contextid IN ($contexts))";
1333 $clauses = implode(" OR ", $clauses);
1334 if ($clauses !== '') {
1335 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1336 FROM {$CFG->prefix}role_capabilities rc
1337 JOIN {$CFG->prefix}context ctx
1338 ON rc.contextid=ctx.id
1339 WHERE $clauses
1340 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1342 $rs = get_recordset_sql($sql);
1343 unset($clauses);
1345 if ($rs) {
1346 while ($rd = rs_fetch_next_record($rs)) {
1347 $k = "{$rd->path}:{$rd->roleid}";
1348 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1350 unset($rd);
1351 rs_close($rs);
1356 // Overrides for the role assignments IN SUBCONTEXTS
1357 // (though we still do _not_ go below the course level.
1359 // NOTE that the JOIN w sctx is with 3-way triangulation to
1360 // catch overrides to the applicable role in any subcontext, based
1361 // on the path field of the parent.
1363 $sql = "SELECT sctx.path, ra.roleid,
1364 ctx.path AS parentpath,
1365 rco.capability, rco.permission
1366 FROM {$CFG->prefix}role_assignments ra
1367 JOIN {$CFG->prefix}context ctx
1368 ON ra.contextid=ctx.id
1369 JOIN {$CFG->prefix}context sctx
1370 ON (sctx.path LIKE " . sql_concat('ctx.path',"'/%'"). " )
1371 JOIN {$CFG->prefix}role_capabilities rco
1372 ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
1373 WHERE ra.userid = $userid
1374 AND sctx.contextlevel <= ".CONTEXT_COURSE."
1375 ORDER BY sctx.depth, sctx.path, ra.roleid";
1377 $rs = get_recordset_sql($sql);
1378 if ($rs) {
1379 while ($rd = rs_fetch_next_record($rs)) {
1380 $k = "{$rd->path}:{$rd->roleid}";
1381 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1383 unset($rd);
1384 rs_close($rs);
1386 return $accessdata;
1390 * It add to the access ctrl array the data
1391 * needed by a user for a given context
1393 * @param $userid integer - the id of the user
1394 * @param $context context obj - needs path!
1395 * @param $accessdata array accessdata array
1397 function load_subcontext($userid, $context, &$accessdata) {
1399 global $CFG;
1403 /* Get the additional RAs and relevant rolecaps
1404 * - role assignments - with role_caps
1405 * - relevant role caps
1406 * - above this user's RAs
1407 * - below this user's RAs - limited to course level
1410 $base = "/" . SYSCONTEXTID;
1413 // Replace $context with the target context we will
1414 // load. Normally, this will be a course context, but
1415 // may be a different top-level context.
1417 // We have 3 cases
1419 // - Course
1420 // - BLOCK/PERSON/USER/COURSE(sitecourse) hanging from SYSTEM
1421 // - BLOCK/MODULE/GROUP hanging from a course
1423 // For course contexts, we _already_ have the RAs
1424 // but the cost of re-fetching is minimal so we don't care.
1426 if ($context->contextlevel !== CONTEXT_COURSE
1427 && $context->path !== "$base/{$context->id}") {
1428 // Case BLOCK/MODULE/GROUP hanging from a course
1429 // Assumption: the course _must_ be our parent
1430 // If we ever see stuff nested further this needs to
1431 // change to do 1 query over the exploded path to
1432 // find out which one is the course
1433 $targetid = array_pop(explode('/',get_course_from_path($context->path)));
1434 $context = get_context_instance_by_id($targetid);
1439 // Role assignments in the context and below
1441 $sql = "SELECT ctx.path, ra.roleid
1442 FROM {$CFG->prefix}role_assignments ra
1443 JOIN {$CFG->prefix}context ctx
1444 ON ra.contextid=ctx.id
1445 WHERE ra.userid = $userid
1446 AND (ctx.path = '{$context->path}' OR ctx.path LIKE '{$context->path}/%')
1447 ORDER BY ctx.depth, ctx.path";
1448 $rs = get_recordset_sql($sql);
1451 // Read in the RAs
1453 $localroles = array();
1454 while ($ra = rs_fetch_next_record($rs)) {
1455 if (!isset($accessdata['ra'][$ra->path])) {
1456 $accessdata['ra'][$ra->path] = array();
1458 array_push($accessdata['ra'][$ra->path], $ra->roleid);
1459 array_push($localroles, $ra->roleid);
1461 rs_close($rs);
1464 // Walk up and down the tree to grab all the roledefs
1465 // of interest to our user...
1467 // NOTES
1468 // - we use IN() but the number of roles is very limited.
1470 $courseroles = aggregate_roles_from_accessdata($context, $accessdata);
1472 // Do we have any interesting "local" roles?
1473 $localroles = array_diff($localroles,$courseroles); // only "new" local roles
1474 $wherelocalroles='';
1475 if (count($localroles)) {
1476 // Role defs for local roles in 'higher' contexts...
1477 $contexts = substr($context->path, 1); // kill leading slash
1478 $contexts = str_replace('/', ',', $contexts);
1479 $localroleids = implode(',',$localroles);
1480 $wherelocalroles="OR (rc.roleid IN ({$localroleids})
1481 AND ctx.id IN ($contexts))" ;
1484 // We will want overrides for all of them
1485 $whereroles = '';
1486 if ($roleids = implode(',',array_merge($courseroles,$localroles))) {
1487 $whereroles = "rc.roleid IN ($roleids) AND";
1489 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1490 FROM {$CFG->prefix}role_capabilities rc
1491 JOIN {$CFG->prefix}context ctx
1492 ON rc.contextid=ctx.id
1493 WHERE ($whereroles
1494 (ctx.id={$context->id} OR ctx.path LIKE '{$context->path}/%'))
1495 $wherelocalroles
1496 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1498 $newrdefs = array();
1499 if ($rs = get_recordset_sql($sql)) {
1500 while ($rd = rs_fetch_next_record($rs)) {
1501 $k = "{$rd->path}:{$rd->roleid}";
1502 if (!array_key_exists($k, $newrdefs)) {
1503 $newrdefs[$k] = array();
1505 $newrdefs[$k][$rd->capability] = $rd->permission;
1507 rs_close($rs);
1508 } else {
1509 debugging('Bad SQL encountered!');
1512 compact_rdefs($newrdefs);
1513 foreach ($newrdefs as $key=>$value) {
1514 $accessdata['rdef'][$key] =& $newrdefs[$key];
1517 // error_log("loaded {$context->path}");
1518 $accessdata['loaded'][] = $context->path;
1522 * It add to the access ctrl array the data
1523 * needed by a role for a given context.
1525 * The data is added in the rdef key.
1527 * This role-centric function is useful for role_switching
1528 * and to get an overview of what a role gets under a
1529 * given context and below...
1531 * @param $roleid integer - the id of the user
1532 * @param $context context obj - needs path!
1533 * @param $accessdata accessdata array
1536 function get_role_access_bycontext($roleid, $context, $accessdata=NULL) {
1538 global $CFG;
1540 /* Get the relevant rolecaps into rdef
1541 * - relevant role caps
1542 * - at ctx and above
1543 * - below this ctx
1546 if (is_null($accessdata)) {
1547 $accessdata = array(); // named list
1548 $accessdata['ra'] = array();
1549 $accessdata['rdef'] = array();
1550 $accessdata['loaded'] = array();
1553 $contexts = substr($context->path, 1); // kill leading slash
1554 $contexts = str_replace('/', ',', $contexts);
1557 // Walk up and down the tree to grab all the roledefs
1558 // of interest to our role...
1560 // NOTE: we use an IN clauses here - which
1561 // might explode on huge sites with very convoluted nesting of
1562 // categories... - extremely unlikely that the number of nested
1563 // categories is so large that we hit the limits of IN()
1565 $sql = "SELECT ctx.path, rc.capability, rc.permission
1566 FROM {$CFG->prefix}role_capabilities rc
1567 JOIN {$CFG->prefix}context ctx
1568 ON rc.contextid=ctx.id
1569 WHERE rc.roleid=$roleid AND
1570 ( ctx.id IN ($contexts) OR
1571 ctx.path LIKE '{$context->path}/%' )
1572 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1574 $rs = get_recordset_sql($sql);
1575 while ($rd = rs_fetch_next_record($rs)) {
1576 $k = "{$rd->path}:{$roleid}";
1577 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1579 rs_close($rs);
1581 return $accessdata;
1585 * Load accessdata for a user
1586 * into the $ACCESS global
1588 * Used by has_capability() - but feel free
1589 * to call it if you are about to run a BIG
1590 * cron run across a bazillion users.
1593 function load_user_accessdata($userid) {
1594 global $ACCESS,$CFG;
1596 $base = '/'.SYSCONTEXTID;
1598 $accessdata = get_user_access_sitewide($userid);
1599 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1601 // provide "default role" & set 'dr'
1603 if (!empty($CFG->defaultuserroleid)) {
1604 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1605 if (!isset($accessdata['ra'][$base])) {
1606 $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
1607 } else {
1608 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
1610 $accessdata['dr'] = $CFG->defaultuserroleid;
1614 // provide "default frontpage role"
1616 if (!empty($CFG->defaultfrontpageroleid)) {
1617 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1618 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1619 if (!isset($accessdata['ra'][$base])) {
1620 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
1621 } else {
1622 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
1625 // for dirty timestamps in cron
1626 $accessdata['time'] = time();
1628 $ACCESS[$userid] = $accessdata;
1629 compact_rdefs($ACCESS[$userid]['rdef']);
1631 return true;
1635 * Use shared copy of role definistions stored in $RDEFS;
1636 * @param array $rdefs array of role definitions in contexts
1638 function compact_rdefs(&$rdefs) {
1639 global $RDEFS;
1642 * This is a basic sharing only, we could also
1643 * use md5 sums of values. The main purpose is to
1644 * reduce mem in cron jobs - many users in $ACCESS array.
1647 foreach ($rdefs as $key => $value) {
1648 if (!array_key_exists($key, $RDEFS)) {
1649 $RDEFS[$key] = $rdefs[$key];
1651 $rdefs[$key] =& $RDEFS[$key];
1656 * A convenience function to completely load all the capabilities
1657 * for the current user. This is what gets called from complete_user_login()
1658 * for example. Call it only _after_ you've setup $USER and called
1659 * check_enrolment_plugins();
1662 function load_all_capabilities() {
1663 global $USER, $CFG, $DIRTYCONTEXTS;
1665 $base = '/'.SYSCONTEXTID;
1667 if (isguestuser()) {
1668 $guest = get_guest_role();
1670 // Load the rdefs
1671 $USER->access = get_role_access($guest->id);
1672 // Put the ghost enrolment in place...
1673 $USER->access['ra'][$base] = array($guest->id);
1676 } else if (isloggedin()) {
1678 $accessdata = get_user_access_sitewide($USER->id);
1681 // provide "default role" & set 'dr'
1683 if (!empty($CFG->defaultuserroleid)) {
1684 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1685 if (!isset($accessdata['ra'][$base])) {
1686 $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
1687 } else {
1688 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
1690 $accessdata['dr'] = $CFG->defaultuserroleid;
1693 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1696 // provide "default frontpage role"
1698 if (!empty($CFG->defaultfrontpageroleid)) {
1699 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1700 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1701 if (!isset($accessdata['ra'][$base])) {
1702 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
1703 } else {
1704 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
1707 $USER->access = $accessdata;
1709 } else if (!empty($CFG->notloggedinroleid)) {
1710 $USER->access = get_role_access($CFG->notloggedinroleid);
1711 $USER->access['ra'][$base] = array($CFG->notloggedinroleid);
1714 // Timestamp to read dirty context timestamps later
1715 $USER->access['time'] = time();
1716 $DIRTYCONTEXTS = array();
1718 // Clear to force a refresh
1719 unset($USER->mycourses);
1723 * A convenience function to completely reload all the capabilities
1724 * for the current user when roles have been updated in a relevant
1725 * context -- but PRESERVING switchroles and loginas.
1727 * That is - completely transparent to the user.
1729 * Note: rewrites $USER->access completely.
1732 function reload_all_capabilities() {
1733 global $USER,$CFG;
1735 // error_log("reloading");
1736 // copy switchroles
1737 $sw = array();
1738 if (isset($USER->access['rsw'])) {
1739 $sw = $USER->access['rsw'];
1740 // error_log(print_r($sw,1));
1743 unset($USER->access);
1744 unset($USER->mycourses);
1746 load_all_capabilities();
1748 foreach ($sw as $path => $roleid) {
1749 $context = get_record('context', 'path', $path);
1750 role_switch($roleid, $context);
1756 * Adds a temp role to an accessdata array.
1758 * Useful for the "temporary guest" access
1759 * we grant to logged-in users.
1761 * Note - assumes a course context!
1764 function load_temp_role($context, $roleid, $accessdata) {
1766 global $CFG;
1769 // Load rdefs for the role in -
1770 // - this context
1771 // - all the parents
1772 // - and below - IOWs overrides...
1775 // turn the path into a list of context ids
1776 $contexts = substr($context->path, 1); // kill leading slash
1777 $contexts = str_replace('/', ',', $contexts);
1779 $sql = "SELECT ctx.path,
1780 rc.capability, rc.permission
1781 FROM {$CFG->prefix}context ctx
1782 JOIN {$CFG->prefix}role_capabilities rc
1783 ON rc.contextid=ctx.id
1784 WHERE (ctx.id IN ($contexts)
1785 OR ctx.path LIKE '{$context->path}/%')
1786 AND rc.roleid = {$roleid}
1787 ORDER BY ctx.depth, ctx.path";
1788 $rs = get_recordset_sql($sql);
1789 while ($rd = rs_fetch_next_record($rs)) {
1790 $k = "{$rd->path}:{$roleid}";
1791 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1793 rs_close($rs);
1796 // Say we loaded everything for the course context
1797 // - which we just did - if the user gets a proper
1798 // RA in this session, this data will need to be reloaded,
1799 // but that is handled by the complete accessdata reload
1801 array_push($accessdata['loaded'], $context->path);
1804 // Add the ghost RA
1806 if (isset($accessdata['ra'][$context->path])) {
1807 array_push($accessdata['ra'][$context->path], $roleid);
1808 } else {
1809 $accessdata['ra'][$context->path] = array($roleid);
1812 return $accessdata;
1817 * Check all the login enrolment information for the given user object
1818 * by querying the enrolment plugins
1820 function check_enrolment_plugins(&$user) {
1821 global $CFG;
1823 static $inprogress; // To prevent this function being called more than once in an invocation
1825 if (!empty($inprogress[$user->id])) {
1826 return;
1829 $inprogress[$user->id] = true; // Set the flag
1831 require_once($CFG->dirroot .'/enrol/enrol.class.php');
1833 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
1834 $plugins = array($CFG->enrol);
1837 foreach ($plugins as $plugin) {
1838 $enrol = enrolment_factory::factory($plugin);
1839 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1840 $enrol->setup_enrolments($user);
1841 } else { /// Run legacy enrolment methods
1842 if (method_exists($enrol, 'get_student_courses')) {
1843 $enrol->get_student_courses($user);
1845 if (method_exists($enrol, 'get_teacher_courses')) {
1846 $enrol->get_teacher_courses($user);
1849 /// deal with $user->students and $user->teachers stuff
1850 unset($user->student);
1851 unset($user->teacher);
1853 unset($enrol);
1856 unset($inprogress[$user->id]); // Unset the flag
1860 * Installs the roles system.
1861 * This function runs on a fresh install as well as on an upgrade from the old
1862 * hard-coded student/teacher/admin etc. roles to the new roles system.
1864 function moodle_install_roles() {
1866 global $CFG, $db;
1868 /// Create a system wide context for assignemnt.
1869 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
1872 /// Create default/legacy roles and capabilities.
1873 /// (1 legacy capability per legacy role at system level).
1875 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1876 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1877 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1878 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1879 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1880 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1881 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1882 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1883 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1884 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1885 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1886 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
1887 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1888 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
1890 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1892 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
1893 error('Could not assign moodle/site:doanything to the admin role');
1895 if (!update_capabilities()) {
1896 error('Had trouble upgrading the core capabilities for the Roles System');
1899 /// Look inside user_admin, user_creator, user_teachers, user_students and
1900 /// assign above new roles. If a user has both teacher and student role,
1901 /// only teacher role is assigned. The assignment should be system level.
1903 $dbtables = $db->MetaTables('TABLES');
1905 /// Set up the progress bar
1907 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1909 $totalcount = $progresscount = 0;
1910 foreach ($usertables as $usertable) {
1911 if (in_array($CFG->prefix.$usertable, $dbtables)) {
1912 $totalcount += count_records($usertable);
1916 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1918 /// Upgrade the admins.
1919 /// Sort using id ASC, first one is primary admin.
1921 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
1922 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
1923 while ($admin = rs_fetch_next_record($rs)) {
1924 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
1925 $progresscount++;
1926 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1928 rs_close($rs);
1930 } else {
1931 // This is a fresh install.
1935 /// Upgrade course creators.
1936 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
1937 if ($rs = get_recordset('user_coursecreators')) {
1938 while ($coursecreator = rs_fetch_next_record($rs)) {
1939 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
1940 $progresscount++;
1941 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1943 rs_close($rs);
1948 /// Upgrade editting teachers and non-editting teachers.
1949 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
1950 if ($rs = get_recordset('user_teachers')) {
1951 while ($teacher = rs_fetch_next_record($rs)) {
1953 // removed code here to ignore site level assignments
1954 // since the contexts are separated now
1956 // populate the user_lastaccess table
1957 $access = new object();
1958 $access->timeaccess = $teacher->timeaccess;
1959 $access->userid = $teacher->userid;
1960 $access->courseid = $teacher->course;
1961 insert_record('user_lastaccess', $access);
1963 // assign the default student role
1964 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
1965 // hidden teacher
1966 if ($teacher->authority == 0) {
1967 $hiddenteacher = 1;
1968 } else {
1969 $hiddenteacher = 0;
1972 if ($teacher->editall) { // editting teacher
1973 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id, $teacher->timestart, $teacher->timeend, $hiddenteacher, $teacher->enrol, $teacher->timemodified);
1974 } else {
1975 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id, $teacher->timestart, $teacher->timeend, $hiddenteacher, $teacher->enrol, $teacher->timemodified);
1977 $progresscount++;
1978 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1980 rs_close($rs);
1985 /// Upgrade students.
1986 if (in_array($CFG->prefix.'user_students', $dbtables)) {
1987 if ($rs = get_recordset('user_students')) {
1988 while ($student = rs_fetch_next_record($rs)) {
1990 // populate the user_lastaccess table
1991 $access = new object;
1992 $access->timeaccess = $student->timeaccess;
1993 $access->userid = $student->userid;
1994 $access->courseid = $student->course;
1995 insert_record('user_lastaccess', $access);
1997 // assign the default student role
1998 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
1999 role_assign($studentrole, $student->userid, 0, $coursecontext->id, $student->timestart, $student->timeend, 0, $student->enrol, $student->time);
2000 $progresscount++;
2001 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
2003 rs_close($rs);
2008 /// Upgrade guest (only 1 entry).
2009 if ($guestuser = get_record('user', 'username', 'guest')) {
2010 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
2012 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
2015 /// Insert the correct records for legacy roles
2016 allow_assign($adminrole, $adminrole);
2017 allow_assign($adminrole, $coursecreatorrole);
2018 allow_assign($adminrole, $noneditteacherrole);
2019 allow_assign($adminrole, $editteacherrole);
2020 allow_assign($adminrole, $studentrole);
2021 allow_assign($adminrole, $guestrole);
2023 allow_assign($coursecreatorrole, $noneditteacherrole);
2024 allow_assign($coursecreatorrole, $editteacherrole);
2025 allow_assign($coursecreatorrole, $studentrole);
2026 allow_assign($coursecreatorrole, $guestrole);
2028 allow_assign($editteacherrole, $noneditteacherrole);
2029 allow_assign($editteacherrole, $studentrole);
2030 allow_assign($editteacherrole, $guestrole);
2032 /// Set up default permissions for overrides
2033 allow_override($adminrole, $adminrole);
2034 allow_override($adminrole, $coursecreatorrole);
2035 allow_override($adminrole, $noneditteacherrole);
2036 allow_override($adminrole, $editteacherrole);
2037 allow_override($adminrole, $studentrole);
2038 allow_override($adminrole, $guestrole);
2039 allow_override($adminrole, $userrole);
2042 /// Delete the old user tables when we are done
2044 $tables = array('user_students', 'user_teachers', 'user_coursecreators', 'user_admins');
2045 foreach ($tables as $tablename) {
2046 $table = new XMLDBTable($tablename);
2047 if (table_exists($table)) {
2048 drop_table($table);
2054 * Returns array of all legacy roles.
2056 function get_legacy_roles() {
2057 return array(
2058 'admin' => 'moodle/legacy:admin',
2059 'coursecreator' => 'moodle/legacy:coursecreator',
2060 'editingteacher' => 'moodle/legacy:editingteacher',
2061 'teacher' => 'moodle/legacy:teacher',
2062 'student' => 'moodle/legacy:student',
2063 'guest' => 'moodle/legacy:guest',
2064 'user' => 'moodle/legacy:user'
2068 function get_legacy_type($roleid) {
2069 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2070 $legacyroles = get_legacy_roles();
2072 $result = '';
2073 foreach($legacyroles as $ltype=>$lcap) {
2074 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
2075 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
2076 //choose first selected legacy capability - reset the rest
2077 if (empty($result)) {
2078 $result = $ltype;
2079 } else {
2080 unassign_capability($lcap, $roleid);
2085 return $result;
2089 * Assign the defaults found in this capabality definition to roles that have
2090 * the corresponding legacy capabilities assigned to them.
2091 * @param $legacyperms - an array in the format (example):
2092 * 'guest' => CAP_PREVENT,
2093 * 'student' => CAP_ALLOW,
2094 * 'teacher' => CAP_ALLOW,
2095 * 'editingteacher' => CAP_ALLOW,
2096 * 'coursecreator' => CAP_ALLOW,
2097 * 'admin' => CAP_ALLOW
2098 * @return boolean - success or failure.
2100 function assign_legacy_capabilities($capability, $legacyperms) {
2102 $legacyroles = get_legacy_roles();
2104 foreach ($legacyperms as $type => $perm) {
2106 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
2108 if (!array_key_exists($type, $legacyroles)) {
2109 error('Incorrect legacy role definition for type: '.$type);
2112 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW)) {
2113 foreach ($roles as $role) {
2114 // Assign a site level capability.
2115 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
2116 return false;
2121 return true;
2126 * Checks to see if a capability is a legacy capability.
2127 * @param $capabilityname
2128 * @return boolean
2130 function islegacy($capabilityname) {
2131 if (strpos($capabilityname, 'moodle/legacy') === 0) {
2132 return true;
2133 } else {
2134 return false;
2140 /**********************************
2141 * Context Manipulation functions *
2142 **********************************/
2145 * Create a new context record for use by all roles-related stuff
2146 * assumes that the caller has done the homework.
2148 * @param $level
2149 * @param $instanceid
2151 * @return object newly created context
2153 function create_context($contextlevel, $instanceid) {
2155 global $CFG;
2157 if ($contextlevel == CONTEXT_SYSTEM) {
2158 return create_system_context();
2161 $context = new object();
2162 $context->contextlevel = $contextlevel;
2163 $context->instanceid = $instanceid;
2165 // Define $context->path based on the parent
2166 // context. In other words... Who is your daddy?
2167 $basepath = '/' . SYSCONTEXTID;
2168 $basedepth = 1;
2170 $result = true;
2172 switch ($contextlevel) {
2173 case CONTEXT_COURSECAT:
2174 $sql = "SELECT ctx.path, ctx.depth
2175 FROM {$CFG->prefix}context ctx
2176 JOIN {$CFG->prefix}course_categories cc
2177 ON (cc.parent=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
2178 WHERE cc.id={$instanceid}";
2179 if ($p = get_record_sql($sql)) {
2180 $basepath = $p->path;
2181 $basedepth = $p->depth;
2182 } else if ($category = get_record('course_categories', 'id', $instanceid)) {
2183 if (empty($category->parent)) {
2184 // ok - this is a top category
2185 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $category->parent)) {
2186 $basepath = $parent->path;
2187 $basedepth = $parent->depth;
2188 } else {
2189 // wrong parent category - no big deal, this can be fixed later
2190 $basepath = null;
2191 $basedepth = 0;
2193 } else {
2194 // incorrect category id
2195 $result = false;
2197 break;
2199 case CONTEXT_COURSE:
2200 $sql = "SELECT ctx.path, ctx.depth
2201 FROM {$CFG->prefix}context ctx
2202 JOIN {$CFG->prefix}course c
2203 ON (c.category=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
2204 WHERE c.id={$instanceid} AND c.id !=" . SITEID;
2205 if ($p = get_record_sql($sql)) {
2206 $basepath = $p->path;
2207 $basedepth = $p->depth;
2208 } else if ($course = get_record('course', 'id', $instanceid)) {
2209 if ($course->id == SITEID) {
2210 //ok - no parent category
2211 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
2212 $basepath = $parent->path;
2213 $basedepth = $parent->depth;
2214 } else {
2215 // wrong parent category of course - no big deal, this can be fixed later
2216 $basepath = null;
2217 $basedepth = 0;
2219 } else if ($instanceid == SITEID) {
2220 // no errors for missing site course during installation
2221 return false;
2222 } else {
2223 // incorrect course id
2224 $result = false;
2226 break;
2228 case CONTEXT_MODULE:
2229 $sql = "SELECT ctx.path, ctx.depth
2230 FROM {$CFG->prefix}context ctx
2231 JOIN {$CFG->prefix}course_modules cm
2232 ON (cm.course=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
2233 WHERE cm.id={$instanceid}";
2234 if ($p = get_record_sql($sql)) {
2235 $basepath = $p->path;
2236 $basedepth = $p->depth;
2237 } else if ($cm = get_record('course_modules', 'id', $instanceid)) {
2238 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
2239 $basepath = $parent->path;
2240 $basedepth = $parent->depth;
2241 } else {
2242 // course does not exist - modules can not exist without a course
2243 $result = false;
2245 } else {
2246 // cm does not exist
2247 $result = false;
2249 break;
2251 case CONTEXT_BLOCK:
2252 // Only non-pinned & course-page based
2253 $sql = "SELECT ctx.path, ctx.depth
2254 FROM {$CFG->prefix}context ctx
2255 JOIN {$CFG->prefix}block_instance bi
2256 ON (bi.pageid=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
2257 WHERE bi.id={$instanceid} AND bi.pagetype='course-view'";
2258 if ($p = get_record_sql($sql)) {
2259 $basepath = $p->path;
2260 $basedepth = $p->depth;
2261 } else if ($bi = get_record('block_instance', 'id', $instanceid)) {
2262 if ($bi->pagetype != 'course-view') {
2263 // ok - not a course block
2264 } else if ($parent = get_context_instance(CONTEXT_COURSE, $bi->pageid)) {
2265 $basepath = $parent->path;
2266 $basedepth = $parent->depth;
2267 } else {
2268 // parent course does not exist - course blocks can not exist without a course
2269 $result = false;
2271 } else {
2272 // block does not exist
2273 $result = false;
2275 break;
2276 case CONTEXT_USER:
2277 // default to basepath
2278 break;
2281 // if grandparents unknown, maybe rebuild_context_path() will solve it later
2282 if ($basedepth != 0) {
2283 $context->depth = $basedepth+1;
2286 if ($result and $id = insert_record('context', $context)) {
2287 // can't set the full path till we know the id!
2288 if ($basedepth != 0 and !empty($basepath)) {
2289 set_field('context', 'path', $basepath.'/'. $id, 'id', $id);
2291 return get_context_instance_by_id($id);
2293 } else {
2294 debugging('Error: could not insert new context level "'.
2295 s($contextlevel).'", instance "'.
2296 s($instanceid).'".');
2297 return false;
2302 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
2304 function get_system_context($cache=true) {
2305 static $cached = null;
2306 if ($cache and defined('SYSCONTEXTID')) {
2307 if (is_null($cached)) {
2308 $cached = new object();
2309 $cached->id = SYSCONTEXTID;
2310 $cached->contextlevel = CONTEXT_SYSTEM;
2311 $cached->instanceid = 0;
2312 $cached->path = '/'.SYSCONTEXTID;
2313 $cached->depth = 1;
2315 return $cached;
2318 if (!$context = get_record('context', 'contextlevel', CONTEXT_SYSTEM)) {
2319 $context = new object();
2320 $context->contextlevel = CONTEXT_SYSTEM;
2321 $context->instanceid = 0;
2322 $context->depth = 1;
2323 $context->path = NULL; //not known before insert
2325 if (!$context->id = insert_record('context', $context)) {
2326 // better something than nothing - let's hope it will work somehow
2327 if (!defined('SYSCONTEXTID')) {
2328 define('SYSCONTEXTID', 1);
2330 debugging('Can not create system context');
2331 $context->id = SYSCONTEXTID;
2332 $context->path = '/'.SYSCONTEXTID;
2333 return $context;
2337 if (!isset($context->depth) or $context->depth != 1 or $context->instanceid != 0 or $context->path != '/'.$context->id) {
2338 $context->instanceid = 0;
2339 $context->path = '/'.$context->id;
2340 $context->depth = 1;
2341 update_record('context', $context);
2344 if (!defined('SYSCONTEXTID')) {
2345 define('SYSCONTEXTID', $context->id);
2348 $cached = $context;
2349 return $cached;
2353 * Remove a context record and any dependent entries,
2354 * removes context from static context cache too
2355 * @param $level
2356 * @param $instanceid
2358 * @return bool properly deleted
2360 function delete_context($contextlevel, $instanceid) {
2361 global $context_cache, $context_cache_id;
2363 // do not use get_context_instance(), because the related object might not exist,
2364 // or the context does not exist yet and it would be created now
2365 if ($context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instanceid)) {
2366 $result = delete_records('role_assignments', 'contextid', $context->id) &&
2367 delete_records('role_capabilities', 'contextid', $context->id) &&
2368 delete_records('context', 'id', $context->id);
2370 // do not mark dirty contexts if parents unknown
2371 if (!is_null($context->path) and $context->depth > 0) {
2372 mark_context_dirty($context->path);
2375 // purge static context cache if entry present
2376 unset($context_cache[$contextlevel][$instanceid]);
2377 unset($context_cache_id[$context->id]);
2379 return $result;
2380 } else {
2382 return true;
2387 * Precreates all contexts including all parents
2388 * @param int $contextlevel, empty means all
2389 * @param bool $buildpaths update paths and depths
2390 * @param bool $feedback show sql feedback
2391 * @return void
2393 function create_contexts($contextlevel=null, $buildpaths=true, $feedback=false) {
2394 global $CFG;
2396 //make sure system context exists
2397 $syscontext = get_system_context(false);
2399 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSECAT
2400 or $contextlevel == CONTEXT_COURSE
2401 or $contextlevel == CONTEXT_MODULE
2402 or $contextlevel == CONTEXT_BLOCK) {
2403 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2404 SELECT ".CONTEXT_COURSECAT.", cc.id
2405 FROM {$CFG->prefix}course_categories cc
2406 WHERE NOT EXISTS (SELECT 'x'
2407 FROM {$CFG->prefix}context cx
2408 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
2409 execute_sql($sql, $feedback);
2413 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSE
2414 or $contextlevel == CONTEXT_MODULE
2415 or $contextlevel == CONTEXT_BLOCK) {
2416 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2417 SELECT ".CONTEXT_COURSE.", c.id
2418 FROM {$CFG->prefix}course c
2419 WHERE NOT EXISTS (SELECT 'x'
2420 FROM {$CFG->prefix}context cx
2421 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
2422 execute_sql($sql, $feedback);
2426 if (empty($contextlevel) or $contextlevel == CONTEXT_MODULE) {
2427 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2428 SELECT ".CONTEXT_MODULE.", cm.id
2429 FROM {$CFG->prefix}course_modules cm
2430 WHERE NOT EXISTS (SELECT 'x'
2431 FROM {$CFG->prefix}context cx
2432 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
2433 execute_sql($sql, $feedback);
2436 if (empty($contextlevel) or $contextlevel == CONTEXT_BLOCK) {
2437 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2438 SELECT ".CONTEXT_BLOCK.", bi.id
2439 FROM {$CFG->prefix}block_instance bi
2440 WHERE NOT EXISTS (SELECT 'x'
2441 FROM {$CFG->prefix}context cx
2442 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
2443 execute_sql($sql, $feedback);
2446 if (empty($contextlevel) or $contextlevel == CONTEXT_USER) {
2447 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2448 SELECT ".CONTEXT_USER.", u.id
2449 FROM {$CFG->prefix}user u
2450 WHERE u.deleted=0
2451 AND NOT EXISTS (SELECT 'x'
2452 FROM {$CFG->prefix}context cx
2453 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
2454 execute_sql($sql, $feedback);
2458 if ($buildpaths) {
2459 build_context_path(false, $feedback);
2464 * Remove stale context records
2466 * @return bool
2468 function cleanup_contexts() {
2469 global $CFG;
2471 $sql = " SELECT c.contextlevel,
2472 c.instanceid AS instanceid
2473 FROM {$CFG->prefix}context c
2474 LEFT OUTER JOIN {$CFG->prefix}course_categories t
2475 ON c.instanceid = t.id
2476 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSECAT . "
2477 UNION
2478 SELECT c.contextlevel,
2479 c.instanceid
2480 FROM {$CFG->prefix}context c
2481 LEFT OUTER JOIN {$CFG->prefix}course t
2482 ON c.instanceid = t.id
2483 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSE . "
2484 UNION
2485 SELECT c.contextlevel,
2486 c.instanceid
2487 FROM {$CFG->prefix}context c
2488 LEFT OUTER JOIN {$CFG->prefix}course_modules t
2489 ON c.instanceid = t.id
2490 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_MODULE . "
2491 UNION
2492 SELECT c.contextlevel,
2493 c.instanceid
2494 FROM {$CFG->prefix}context c
2495 LEFT OUTER JOIN {$CFG->prefix}user t
2496 ON c.instanceid = t.id
2497 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_USER . "
2498 UNION
2499 SELECT c.contextlevel,
2500 c.instanceid
2501 FROM {$CFG->prefix}context c
2502 LEFT OUTER JOIN {$CFG->prefix}block_instance t
2503 ON c.instanceid = t.id
2504 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_BLOCK . "
2505 UNION
2506 SELECT c.contextlevel,
2507 c.instanceid
2508 FROM {$CFG->prefix}context c
2509 LEFT OUTER JOIN {$CFG->prefix}groups t
2510 ON c.instanceid = t.id
2511 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_GROUP . "
2513 if ($rs = get_recordset_sql($sql)) {
2514 begin_sql();
2515 $tx = true;
2516 while ($tx && $ctx = rs_fetch_next_record($rs)) {
2517 $tx = $tx && delete_context($ctx->contextlevel, $ctx->instanceid);
2519 rs_close($rs);
2520 if ($tx) {
2521 commit_sql();
2522 return true;
2524 rollback_sql();
2525 return false;
2526 rs_close($rs);
2528 return true;
2532 * Get the context instance as an object. This function will create the
2533 * context instance if it does not exist yet.
2534 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2535 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
2536 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
2537 * @return object The context object.
2539 function get_context_instance($contextlevel, $instance=0) {
2541 global $context_cache, $context_cache_id, $CFG;
2542 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_GROUP, CONTEXT_MODULE, CONTEXT_BLOCK);
2544 if ($contextlevel === 'clearcache') {
2545 // TODO: Remove for v2.0
2546 // No longer needed, but we'll catch it to avoid erroring out on custom code.
2547 // This used to be a fix for MDL-9016
2548 // "Restoring into existing course, deleting first
2549 // deletes context and doesn't recreate it"
2550 return false;
2553 /// System context has special cache
2554 if ($contextlevel == CONTEXT_SYSTEM) {
2555 return get_system_context();
2558 /// check allowed context levels
2559 if (!in_array($contextlevel, $allowed_contexts)) {
2560 // fatal error, code must be fixed - probably typo or switched parameters
2561 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
2564 if (!is_array($instance)) {
2565 /// Check the cache
2566 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2567 return $context_cache[$contextlevel][$instance];
2570 /// Get it from the database, or create it
2571 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
2572 $context = create_context($contextlevel, $instance);
2575 /// Only add to cache if context isn't empty.
2576 if (!empty($context)) {
2577 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
2578 $context_cache_id[$context->id] = $context; // Cache it for later
2581 return $context;
2585 /// ok, somebody wants to load several contexts to save some db queries ;-)
2586 $instances = $instance;
2587 $result = array();
2589 foreach ($instances as $key=>$instance) {
2590 /// Check the cache first
2591 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2592 $result[$instance] = $context_cache[$contextlevel][$instance];
2593 unset($instances[$key]);
2594 continue;
2598 if ($instances) {
2599 if (count($instances) > 1) {
2600 $instanceids = implode(',', $instances);
2601 $instanceids = "instanceid IN ($instanceids)";
2602 } else {
2603 $instance = reset($instances);
2604 $instanceids = "instanceid = $instance";
2607 if (!$contexts = get_records_sql("SELECT instanceid, id, contextlevel, path, depth
2608 FROM {$CFG->prefix}context
2609 WHERE contextlevel=$contextlevel AND $instanceids")) {
2610 $contexts = array();
2613 foreach ($instances as $instance) {
2614 if (isset($contexts[$instance])) {
2615 $context = $contexts[$instance];
2616 } else {
2617 $context = create_context($contextlevel, $instance);
2620 if (!empty($context)) {
2621 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
2622 $context_cache_id[$context->id] = $context; // Cache it for later
2625 $result[$instance] = $context;
2629 return $result;
2634 * Get a context instance as an object, from a given context id.
2635 * @param mixed $id a context id or array of ids.
2636 * @return mixed object or array of the context object.
2638 function get_context_instance_by_id($id) {
2640 global $context_cache, $context_cache_id;
2642 if ($id == SYSCONTEXTID) {
2643 return get_system_context();
2646 if (isset($context_cache_id[$id])) { // Already cached
2647 return $context_cache_id[$id];
2650 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
2651 $context_cache[$context->contextlevel][$context->instanceid] = $context;
2652 $context_cache_id[$context->id] = $context;
2653 return $context;
2656 return false;
2661 * Get the local override (if any) for a given capability in a role in a context
2662 * @param $roleid
2663 * @param $contextid
2664 * @param $capability
2666 function get_local_override($roleid, $contextid, $capability) {
2667 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
2672 /************************************
2673 * DB TABLE RELATED FUNCTIONS *
2674 ************************************/
2677 * function that creates a role
2678 * @param name - role name
2679 * @param shortname - role short name
2680 * @param description - role description
2681 * @param legacy - optional legacy capability
2682 * @return id or false
2684 function create_role($name, $shortname, $description, $legacy='') {
2686 // check for duplicate role name
2688 if ($role = get_record('role','name', $name)) {
2689 error('there is already a role with this name!');
2692 if ($role = get_record('role','shortname', $shortname)) {
2693 error('there is already a role with this shortname!');
2696 $role = new object();
2697 $role->name = $name;
2698 $role->shortname = $shortname;
2699 $role->description = $description;
2701 //find free sortorder number
2702 $role->sortorder = count_records('role');
2703 while (get_record('role','sortorder', $role->sortorder)) {
2704 $role->sortorder += 1;
2707 if (!$context = get_context_instance(CONTEXT_SYSTEM)) {
2708 return false;
2711 if ($id = insert_record('role', $role)) {
2712 if ($legacy) {
2713 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
2716 /// By default, users with role:manage at site level
2717 /// should be able to assign users to this new role, and override this new role's capabilities
2719 // find all admin roles
2720 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
2721 // foreach admin role
2722 foreach ($adminroles as $arole) {
2723 // write allow_assign and allow_overrid
2724 allow_assign($arole->id, $id);
2725 allow_override($arole->id, $id);
2729 return $id;
2730 } else {
2731 return false;
2737 * function that deletes a role and cleanups up after it
2738 * @param roleid - id of role to delete
2739 * @return success
2741 function delete_role($roleid) {
2742 global $CFG;
2743 $success = true;
2745 // mdl 10149, check if this is the last active admin role
2746 // if we make the admin role not deletable then this part can go
2748 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
2750 if ($role = get_record('role', 'id', $roleid)) {
2751 if (record_exists('role_capabilities', 'contextid', $systemcontext->id, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
2752 // deleting an admin role
2753 $status = false;
2754 if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext)) {
2755 foreach ($adminroles as $adminrole) {
2756 if ($adminrole->id != $roleid) {
2757 // some other admin role
2758 if (record_exists('role_assignments', 'roleid', $adminrole->id, 'contextid', $systemcontext->id)) {
2759 // found another admin role with at least 1 user assigned
2760 $status = true;
2761 break;
2766 if ($status !== true) {
2767 error ('You can not delete this role because there is no other admin roles with users assigned');
2772 // first unssign all users
2773 if (!role_unassign($roleid)) {
2774 debugging("Error while unassigning all users from role with ID $roleid!");
2775 $success = false;
2778 // cleanup all references to this role, ignore errors
2779 if ($success) {
2781 // MDL-10679 find all contexts where this role has an override
2782 $contexts = get_records_sql("SELECT contextid, contextid
2783 FROM {$CFG->prefix}role_capabilities
2784 WHERE roleid = $roleid");
2786 delete_records('role_capabilities', 'roleid', $roleid);
2788 delete_records('role_allow_assign', 'roleid', $roleid);
2789 delete_records('role_allow_assign', 'allowassign', $roleid);
2790 delete_records('role_allow_override', 'roleid', $roleid);
2791 delete_records('role_allow_override', 'allowoverride', $roleid);
2792 delete_records('role_names', 'roleid', $roleid);
2795 // finally delete the role itself
2796 // get this before the name is gone for logging
2797 $rolename = get_field('role', 'name', 'id', $roleid);
2799 if ($success and !delete_records('role', 'id', $roleid)) {
2800 debugging("Could not delete role record with ID $roleid!");
2801 $success = false;
2804 if ($success) {
2805 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '', $USER->id);
2808 return $success;
2812 * Function to write context specific overrides, or default capabilities.
2813 * @param module - string name
2814 * @param capability - string name
2815 * @param contextid - context id
2816 * @param roleid - role id
2817 * @param permission - int 1,-1 or -1000
2818 * should not be writing if permission is 0
2820 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2822 global $USER;
2824 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
2825 unassign_capability($capability, $roleid, $contextid);
2826 return true;
2829 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
2831 if ($existing and !$overwrite) { // We want to keep whatever is there already
2832 return true;
2835 $cap = new object;
2836 $cap->contextid = $contextid;
2837 $cap->roleid = $roleid;
2838 $cap->capability = $capability;
2839 $cap->permission = $permission;
2840 $cap->timemodified = time();
2841 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
2843 if ($existing) {
2844 $cap->id = $existing->id;
2845 return update_record('role_capabilities', $cap);
2846 } else {
2847 $c = get_record('context', 'id', $contextid);
2848 return insert_record('role_capabilities', $cap);
2853 * Unassign a capability from a role.
2854 * @param $roleid - the role id
2855 * @param $capability - the name of the capability
2856 * @return boolean - success or failure
2858 function unassign_capability($capability, $roleid, $contextid=NULL) {
2860 if (isset($contextid)) {
2861 // delete from context rel, if this is the last override in this context
2862 $status = delete_records('role_capabilities', 'capability', $capability,
2863 'roleid', $roleid, 'contextid', $contextid);
2864 } else {
2865 $status = delete_records('role_capabilities', 'capability', $capability,
2866 'roleid', $roleid);
2868 return $status;
2873 * Get the roles that have a given capability assigned to it. This function
2874 * does not resolve the actual permission of the capability. It just checks
2875 * for assignment only.
2876 * @param $capability - capability name (string)
2877 * @param $permission - optional, the permission defined for this capability
2878 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2879 * @return array or role objects
2881 function get_roles_with_capability($capability, $permission=NULL, $context='') {
2883 global $CFG;
2885 if ($context) {
2886 if ($contexts = get_parent_contexts($context)) {
2887 $listofcontexts = '('.implode(',', $contexts).')';
2888 } else {
2889 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2890 $listofcontexts = '('.$sitecontext->id.')'; // must be site
2892 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
2893 } else {
2894 $contextstr = '';
2897 $selectroles = "SELECT r.*
2898 FROM {$CFG->prefix}role r,
2899 {$CFG->prefix}role_capabilities rc
2900 WHERE rc.capability = '$capability'
2901 AND rc.roleid = r.id $contextstr";
2903 if (isset($permission)) {
2904 $selectroles .= " AND rc.permission = '$permission'";
2906 return get_records_sql($selectroles);
2911 * This function makes a role-assignment (a role for a user or group in a particular context)
2912 * @param $roleid - the role of the id
2913 * @param $userid - userid
2914 * @param $groupid - group id
2915 * @param $contextid - id of the context
2916 * @param $timestart - time this assignment becomes effective
2917 * @param $timeend - time this assignemnt ceases to be effective
2918 * @uses $USER
2919 * @return id - new id of the assigment
2921 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
2922 global $USER, $CFG;
2924 /// Do some data validation
2926 if (empty($roleid)) {
2927 debugging('Role ID not provided');
2928 return false;
2931 if (empty($userid) && empty($groupid)) {
2932 debugging('Either userid or groupid must be provided');
2933 return false;
2936 if ($userid && !record_exists('user', 'id', $userid)) {
2937 debugging('User ID '.intval($userid).' does not exist!');
2938 return false;
2941 if ($groupid && !groups_group_exists($groupid)) {
2942 debugging('Group ID '.intval($groupid).' does not exist!');
2943 return false;
2946 if (!$context = get_context_instance_by_id($contextid)) {
2947 debugging('Context ID '.intval($contextid).' does not exist!');
2948 return false;
2951 if (($timestart and $timeend) and ($timestart > $timeend)) {
2952 debugging('The end time can not be earlier than the start time');
2953 return false;
2956 if (!$timemodified) {
2957 $timemodified = time();
2960 /// Check for existing entry
2961 if ($userid) {
2962 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
2963 } else {
2964 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
2968 $newra = new object;
2970 if (empty($ra)) { // Create a new entry
2971 $newra->roleid = $roleid;
2972 $newra->contextid = $context->id;
2973 $newra->userid = $userid;
2974 $newra->hidden = $hidden;
2975 $newra->enrol = $enrol;
2976 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2977 /// by repeating queries with the same exact parameters in a 100 secs time window
2978 $newra->timestart = round($timestart, -2);
2979 $newra->timeend = $timeend;
2980 $newra->timemodified = $timemodified;
2981 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
2983 $success = insert_record('role_assignments', $newra);
2985 } else { // We already have one, just update it
2987 $newra->id = $ra->id;
2988 $newra->hidden = $hidden;
2989 $newra->enrol = $enrol;
2990 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2991 /// by repeating queries with the same exact parameters in a 100 secs time window
2992 $newra->timestart = round($timestart, -2);
2993 $newra->timeend = $timeend;
2994 $newra->timemodified = $timemodified;
2995 $newra->modifierid = empty($USER->id) ? 0 : $USER->id;
2997 $success = update_record('role_assignments', $newra);
3000 if ($success) { /// Role was assigned, so do some other things
3002 /// mark context as dirty - modules might use has_capability() in xxx_role_assing()
3003 /// again expensive, but needed
3004 mark_context_dirty($context->path);
3006 if (!empty($USER->id) && $USER->id == $userid) {
3007 /// If the user is the current user, then do full reload of capabilities too.
3008 load_all_capabilities();
3011 /// Ask all the modules if anything needs to be done for this user
3012 if ($mods = get_list_of_plugins('mod')) {
3013 foreach ($mods as $mod) {
3014 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
3015 $functionname = $mod.'_role_assign';
3016 if (function_exists($functionname)) {
3017 $functionname($userid, $context, $roleid);
3023 /// now handle metacourse role assignments if in course context
3024 if ($success and $context->contextlevel == CONTEXT_COURSE) {
3025 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
3026 foreach ($parents as $parent) {
3027 sync_metacourse($parent->parent_course);
3032 return $success;
3037 * Deletes one or more role assignments. You must specify at least one parameter.
3038 * @param $roleid
3039 * @param $userid
3040 * @param $groupid
3041 * @param $contextid
3042 * @param $enrol unassign only if enrolment type matches, NULL means anything
3043 * @return boolean - success or failure
3045 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
3047 global $USER, $CFG;
3049 $success = true;
3051 $args = array('roleid', 'userid', 'groupid', 'contextid');
3052 $select = array();
3053 foreach ($args as $arg) {
3054 if ($$arg) {
3055 $select[] = $arg.' = '.$$arg;
3058 if (!empty($enrol)) {
3059 $select[] = "enrol='$enrol'";
3062 if ($select) {
3063 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
3064 $mods = get_list_of_plugins('mod');
3065 foreach($ras as $ra) {
3066 /// infinite loop protection when deleting recursively
3067 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
3068 continue;
3070 $success = delete_records('role_assignments', 'id', $ra->id) and $success;
3072 if (!$context = get_context_instance_by_id($ra->contextid)) {
3073 // strange error, not much to do
3074 continue;
3077 /* mark contexts as dirty here, because we need the refreshed
3078 * caps bellow to delete group membership and user_lastaccess!
3079 * and yes, this is very expensive for bulk operations :-(
3081 mark_context_dirty($context->path);
3083 /// If the user is the current user, then do full reload of capabilities too.
3084 if (!empty($USER->id) && $USER->id == $ra->userid) {
3085 load_all_capabilities();
3088 /// Ask all the modules if anything needs to be done for this user
3089 foreach ($mods as $mod) {
3090 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
3091 $functionname = $mod.'_role_unassign';
3092 if (function_exists($functionname)) {
3093 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
3097 /// now handle metacourse role unassigment and removing from goups if in course context
3098 if ($context->contextlevel == CONTEXT_COURSE) {
3100 // cleanup leftover course groups/subscriptions etc when user has
3101 // no capability to view course
3102 // this may be slow, but this is the proper way of doing it
3103 if (!has_capability('moodle/course:view', $context, $ra->userid)) {
3104 // remove from groups
3105 if ($groups = groups_get_all_groups($context->instanceid)) {
3106 foreach ($groups as $group) {
3107 delete_records('groups_members', 'groupid', $group->id, 'userid', $ra->userid);
3111 // delete lastaccess records
3112 delete_records('user_lastaccess', 'userid', $ra->userid, 'courseid', $context->instanceid);
3115 //unassign roles in metacourses if needed
3116 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
3117 foreach ($parents as $parent) {
3118 sync_metacourse($parent->parent_course);
3126 return $success;
3130 * A convenience function to take care of the common case where you
3131 * just want to enrol someone using the default role into a course
3133 * @param object $course
3134 * @param object $user
3135 * @param string $enrol - the plugin used to do this enrolment
3137 function enrol_into_course($course, $user, $enrol) {
3139 $timestart = time();
3140 // remove time part from the timestamp and keep only the date part
3141 $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
3142 if ($course->enrolperiod) {
3143 $timeend = $timestart + $course->enrolperiod;
3144 } else {
3145 $timeend = 0;
3148 if ($role = get_default_course_role($course)) {
3150 $context = get_context_instance(CONTEXT_COURSE, $course->id);
3152 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
3153 return false;
3156 // force accessdata refresh for users visiting this context...
3157 mark_context_dirty($context->path);
3159 email_welcome_message_to_user($course, $user);
3161 add_to_log($course->id, 'course', 'enrol', 'view.php?id='.$course->id, $user->id);
3163 return true;
3166 return false;
3170 * Loads the capability definitions for the component (from file). If no
3171 * capabilities are defined for the component, we simply return an empty array.
3172 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3173 * @return array of capabilities
3175 function load_capability_def($component) {
3176 global $CFG;
3178 if ($component == 'moodle') {
3179 $defpath = $CFG->libdir.'/db/access.php';
3180 $varprefix = 'moodle';
3181 } else {
3182 $compparts = explode('/', $component);
3184 if ($compparts[0] == 'block') {
3185 // Blocks are an exception. Blocks directory is 'blocks', and not
3186 // 'block'. So we need to jump through hoops.
3187 $defpath = $CFG->dirroot.'/'.$compparts[0].
3188 's/'.$compparts[1].'/db/access.php';
3189 $varprefix = $compparts[0].'_'.$compparts[1];
3191 } else if ($compparts[0] == 'format') {
3192 // Similar to the above, course formats are 'format' while they
3193 // are stored in 'course/format'.
3194 $defpath = $CFG->dirroot.'/course/'.$component.'/db/access.php';
3195 $varprefix = $compparts[0].'_'.$compparts[1];
3197 } else if ($compparts[0] == 'gradeimport') {
3198 $defpath = $CFG->dirroot.'/grade/import/'.$compparts[1].'/db/access.php';
3199 $varprefix = $compparts[0].'_'.$compparts[1];
3201 } else if ($compparts[0] == 'gradeexport') {
3202 $defpath = $CFG->dirroot.'/grade/export/'.$compparts[1].'/db/access.php';
3203 $varprefix = $compparts[0].'_'.$compparts[1];
3205 } else if ($compparts[0] == 'gradereport') {
3206 $defpath = $CFG->dirroot.'/grade/report/'.$compparts[1].'/db/access.php';
3207 $varprefix = $compparts[0].'_'.$compparts[1];
3209 } else {
3210 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
3211 $varprefix = str_replace('/', '_', $component);
3214 $capabilities = array();
3216 if (file_exists($defpath)) {
3217 require($defpath);
3218 $capabilities = ${$varprefix.'_capabilities'};
3220 return $capabilities;
3225 * Gets the capabilities that have been cached in the database for this
3226 * component.
3227 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3228 * @return array of capabilities
3230 function get_cached_capabilities($component='moodle') {
3231 if ($component == 'moodle') {
3232 $storedcaps = get_records_select('capabilities',
3233 "name LIKE 'moodle/%:%'");
3234 } else if ($component == 'local') {
3235 $storedcaps = get_records_select('capabilities',
3236 "name LIKE 'moodle/local:%'");
3237 } else {
3238 $storedcaps = get_records_select('capabilities',
3239 "name LIKE '$component:%'");
3241 return $storedcaps;
3245 * Returns default capabilities for given legacy role type.
3247 * @param string legacy role name
3248 * @return array
3250 function get_default_capabilities($legacyrole) {
3251 if (!$allcaps = get_records('capabilities')) {
3252 error('Error: no capabilitites defined!');
3254 $alldefs = array();
3255 $defaults = array();
3256 $components = array();
3257 foreach ($allcaps as $cap) {
3258 if (!in_array($cap->component, $components)) {
3259 $components[] = $cap->component;
3260 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
3263 foreach($alldefs as $name=>$def) {
3264 if (isset($def['legacy'][$legacyrole])) {
3265 $defaults[$name] = $def['legacy'][$legacyrole];
3269 //some exceptions
3270 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW;
3271 if ($legacyrole == 'admin') {
3272 $defaults['moodle/site:doanything'] = CAP_ALLOW;
3274 return $defaults;
3278 * Reset role capabilitites to default according to selected legacy capability.
3279 * If several legacy caps selected, use the first from get_default_capabilities.
3280 * If no legacy selected, removes all capabilities.
3282 * @param int @roleid
3284 function reset_role_capabilities($roleid) {
3285 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
3286 $legacyroles = get_legacy_roles();
3288 $defaultcaps = array();
3289 foreach($legacyroles as $ltype=>$lcap) {
3290 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
3291 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
3292 //choose first selected legacy capability
3293 $defaultcaps = get_default_capabilities($ltype);
3294 break;
3298 delete_records('role_capabilities', 'roleid', $roleid);
3299 if (!empty($defaultcaps)) {
3300 foreach($defaultcaps as $cap=>$permission) {
3301 assign_capability($cap, $permission, $roleid, $sitecontext->id);
3307 * Updates the capabilities table with the component capability definitions.
3308 * If no parameters are given, the function updates the core moodle
3309 * capabilities.
3311 * Note that the absence of the db/access.php capabilities definition file
3312 * will cause any stored capabilities for the component to be removed from
3313 * the database.
3315 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3316 * @return boolean
3318 function update_capabilities($component='moodle') {
3320 $storedcaps = array();
3322 $filecaps = load_capability_def($component);
3323 $cachedcaps = get_cached_capabilities($component);
3324 if ($cachedcaps) {
3325 foreach ($cachedcaps as $cachedcap) {
3326 array_push($storedcaps, $cachedcap->name);
3327 // update risk bitmasks and context levels in existing capabilities if needed
3328 if (array_key_exists($cachedcap->name, $filecaps)) {
3329 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
3330 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
3332 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
3333 $updatecap = new object();
3334 $updatecap->id = $cachedcap->id;
3335 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
3336 if (!update_record('capabilities', $updatecap)) {
3337 return false;
3341 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
3342 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
3344 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
3345 $updatecap = new object();
3346 $updatecap->id = $cachedcap->id;
3347 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
3348 if (!update_record('capabilities', $updatecap)) {
3349 return false;
3356 // Are there new capabilities in the file definition?
3357 $newcaps = array();
3359 foreach ($filecaps as $filecap => $def) {
3360 if (!$storedcaps ||
3361 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
3362 if (!array_key_exists('riskbitmask', $def)) {
3363 $def['riskbitmask'] = 0; // no risk if not specified
3365 $newcaps[$filecap] = $def;
3368 // Add new capabilities to the stored definition.
3369 foreach ($newcaps as $capname => $capdef) {
3370 $capability = new object;
3371 $capability->name = $capname;
3372 $capability->captype = $capdef['captype'];
3373 $capability->contextlevel = $capdef['contextlevel'];
3374 $capability->component = $component;
3375 $capability->riskbitmask = $capdef['riskbitmask'];
3377 if (!insert_record('capabilities', $capability, false, 'id')) {
3378 return false;
3382 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
3383 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
3384 foreach ($rolecapabilities as $rolecapability){
3385 //assign_capability will update rather than insert if capability exists
3386 if (!assign_capability($capname, $rolecapability->permission,
3387 $rolecapability->roleid, $rolecapability->contextid, true)){
3388 notify('Could not clone capabilities for '.$capname);
3392 // Do we need to assign the new capabilities to roles that have the
3393 // legacy capabilities moodle/legacy:* as well?
3394 // we ignore legacy key if we have cloned permissions
3395 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
3396 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
3397 notify('Could not assign legacy capabilities for '.$capname);
3400 // Are there any capabilities that have been removed from the file
3401 // definition that we need to delete from the stored capabilities and
3402 // role assignments?
3403 capabilities_cleanup($component, $filecaps);
3405 return true;
3410 * Deletes cached capabilities that are no longer needed by the component.
3411 * Also unassigns these capabilities from any roles that have them.
3412 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3413 * @param $newcapdef - array of the new capability definitions that will be
3414 * compared with the cached capabilities
3415 * @return int - number of deprecated capabilities that have been removed
3417 function capabilities_cleanup($component, $newcapdef=NULL) {
3419 $removedcount = 0;
3421 if ($cachedcaps = get_cached_capabilities($component)) {
3422 foreach ($cachedcaps as $cachedcap) {
3423 if (empty($newcapdef) ||
3424 array_key_exists($cachedcap->name, $newcapdef) === false) {
3426 // Remove from capabilities cache.
3427 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
3428 error('Could not delete deprecated capability '.$cachedcap->name);
3429 } else {
3430 $removedcount++;
3432 // Delete from roles.
3433 if($roles = get_roles_with_capability($cachedcap->name)) {
3434 foreach($roles as $role) {
3435 if (!unassign_capability($cachedcap->name, $role->id)) {
3436 error('Could not unassign deprecated capability '.
3437 $cachedcap->name.' from role '.$role->name);
3441 } // End if.
3444 return $removedcount;
3449 /****************
3450 * UI FUNCTIONS *
3451 ****************/
3455 * prints human readable context identifier.
3457 function print_context_name($context, $withprefix = true, $short = false) {
3459 $name = '';
3460 switch ($context->contextlevel) {
3462 case CONTEXT_SYSTEM: // by now it's a definite an inherit
3463 $name = get_string('coresystem');
3464 break;
3466 case CONTEXT_USER:
3467 if ($user = get_record('user', 'id', $context->instanceid)) {
3468 if ($withprefix){
3469 $name = get_string('user').': ';
3471 $name .= fullname($user);
3473 break;
3475 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
3476 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
3477 if ($withprefix){
3478 $name = get_string('category').': ';
3480 $name .=format_string($category->name);
3482 break;
3484 case CONTEXT_COURSE: // 1 to 1 to course cat
3485 if ($course = get_record('course', 'id', $context->instanceid)) {
3486 if ($withprefix){
3487 if ($context->instanceid == SITEID) {
3488 $name = get_string('site').': ';
3489 } else {
3490 $name = get_string('course').': ';
3493 if ($short){
3494 $name .=format_string($course->shortname);
3495 } else {
3496 $name .=format_string($course->fullname);
3500 break;
3502 case CONTEXT_GROUP: // 1 to 1 to course
3503 if ($name = groups_get_group_name($context->instanceid)) {
3504 if ($withprefix){
3505 $name = get_string('group').': '. $name;
3508 break;
3510 case CONTEXT_MODULE: // 1 to 1 to course
3511 if ($cm = get_record('course_modules','id',$context->instanceid)) {
3512 if ($module = get_record('modules','id',$cm->module)) {
3513 if ($mod = get_record($module->name, 'id', $cm->instance)) {
3514 if ($withprefix){
3515 $name = get_string('activitymodule').': ';
3517 $name .= $mod->name;
3521 break;
3523 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
3524 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
3525 if ($block = get_record('block','id',$blockinstance->blockid)) {
3526 global $CFG;
3527 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
3528 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
3529 $blockname = "block_$block->name";
3530 if ($blockobject = new $blockname()) {
3531 if ($withprefix){
3532 $name = get_string('block').': ';
3534 $name .= $blockobject->title;
3538 break;
3540 default:
3541 error ('This is an unknown context (' . $context->contextlevel . ') in print_context_name!');
3542 return false;
3545 return $name;
3550 * Extracts the relevant capabilities given a contextid.
3551 * All case based, example an instance of forum context.
3552 * Will fetch all forum related capabilities, while course contexts
3553 * Will fetch all capabilities
3554 * @param object context
3555 * @return array();
3557 * capabilities
3558 * `name` varchar(150) NOT NULL,
3559 * `captype` varchar(50) NOT NULL,
3560 * `contextlevel` int(10) NOT NULL,
3561 * `component` varchar(100) NOT NULL,
3563 function fetch_context_capabilities($context) {
3565 global $CFG;
3567 $sort = 'ORDER BY contextlevel,component,id'; // To group them sensibly for display
3569 switch ($context->contextlevel) {
3571 case CONTEXT_SYSTEM: // all
3572 $SQL = "select * from {$CFG->prefix}capabilities";
3573 break;
3575 case CONTEXT_USER:
3576 $SQL = "SELECT *
3577 FROM {$CFG->prefix}capabilities
3578 WHERE contextlevel = ".CONTEXT_USER;
3579 break;
3581 case CONTEXT_COURSECAT: // all
3582 $SQL = "select * from {$CFG->prefix}capabilities";
3583 break;
3585 case CONTEXT_COURSE: // all
3586 $SQL = "select * from {$CFG->prefix}capabilities";
3587 break;
3589 case CONTEXT_GROUP: // group caps
3590 break;
3592 case CONTEXT_MODULE: // mod caps
3593 $cm = get_record('course_modules', 'id', $context->instanceid);
3594 $module = get_record('modules', 'id', $cm->module);
3596 $SQL = "select * from {$CFG->prefix}capabilities where contextlevel = ".CONTEXT_MODULE."
3597 and component = 'mod/$module->name'";
3598 break;
3600 case CONTEXT_BLOCK: // block caps
3601 $cb = get_record('block_instance', 'id', $context->instanceid);
3602 $block = get_record('block', 'id', $cb->blockid);
3604 $SQL = "select * from {$CFG->prefix}capabilities where (contextlevel = ".CONTEXT_BLOCK." AND component = 'moodle')
3605 OR (component = 'block/$block->name')";
3606 break;
3608 default:
3609 return false;
3612 if (!$records = get_records_sql($SQL.' '.$sort)) {
3613 $records = array();
3616 /// the rest of code is a bit hacky, think twice before modifying it :-(
3618 // special sorting of core system capabiltites and enrollments
3619 if (in_array($context->contextlevel, array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE))) {
3620 $first = array();
3621 foreach ($records as $key=>$record) {
3622 if (preg_match('|^moodle/|', $record->name) and $record->contextlevel == CONTEXT_SYSTEM) {
3623 $first[$key] = $record;
3624 unset($records[$key]);
3625 } else if (count($first)){
3626 break;
3629 if (count($first)) {
3630 $records = $first + $records; // merge the two arrays keeping the keys
3632 } else {
3633 $contextindependentcaps = fetch_context_independent_capabilities();
3634 $records = array_merge($contextindependentcaps, $records);
3637 return $records;
3643 * Gets the context-independent capabilities that should be overrridable in
3644 * any context.
3645 * @return array of capability records from the capabilities table.
3647 function fetch_context_independent_capabilities() {
3649 //only CONTEXT_SYSTEM capabilities here or it will break the hack in fetch_context_capabilities()
3650 $contextindependentcaps = array(
3651 'moodle/site:accessallgroups'
3654 $records = array();
3656 foreach ($contextindependentcaps as $capname) {
3657 $record = get_record('capabilities', 'name', $capname);
3658 array_push($records, $record);
3660 return $records;
3665 * This function pulls out all the resolved capabilities (overrides and
3666 * defaults) of a role used in capability overrides in contexts at a given
3667 * context.
3668 * @param obj $context
3669 * @param int $roleid
3670 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
3671 * @return array
3673 function role_context_capabilities($roleid, $context, $cap='') {
3674 global $CFG;
3676 $contexts = get_parent_contexts($context);
3677 $contexts[] = $context->id;
3678 $contexts = '('.implode(',', $contexts).')';
3680 if ($cap) {
3681 $search = " AND rc.capability = '$cap' ";
3682 } else {
3683 $search = '';
3686 $SQL = "SELECT rc.*
3687 FROM {$CFG->prefix}role_capabilities rc,
3688 {$CFG->prefix}context c
3689 WHERE rc.contextid in $contexts
3690 AND rc.roleid = $roleid
3691 AND rc.contextid = c.id $search
3692 ORDER BY c.contextlevel DESC,
3693 rc.capability DESC";
3695 $capabilities = array();
3697 if ($records = get_records_sql($SQL)) {
3698 // We are traversing via reverse order.
3699 foreach ($records as $record) {
3700 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3701 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
3702 $capabilities[$record->capability] = $record->permission;
3706 return $capabilities;
3710 * Recursive function which, given a context, find all parent context ids,
3711 * and return the array in reverse order, i.e. parent first, then grand
3712 * parent, etc.
3714 * @param object $context
3715 * @return array()
3717 function get_parent_contexts($context) {
3719 if ($context->path == '') {
3720 return array();
3723 $parentcontexts = substr($context->path, 1); // kill leading slash
3724 $parentcontexts = explode('/', $parentcontexts);
3725 array_pop($parentcontexts); // and remove its own id
3727 return array_reverse($parentcontexts);
3732 * Recursive function which, given a context, find all its children context ids.
3734 * When called for a course context, it will return the modules and blocks
3735 * displayed in the course page.
3737 * For course category contexts it will return categories and courses. It will
3738 * NOT recurse into courses - if you want to do that, call it on the returned
3739 * courses.
3741 * If called on a course context it _will_ populate the cache with the appropriate
3742 * contexts ;-)
3744 * @param object $context.
3745 * @return array of child records
3747 function get_child_contexts($context) {
3749 global $CFG, $context_cache;
3751 // We *MUST* populate the context_cache as the callers
3752 // will probably ask for the full record anyway soon after
3753 // soon after calling us ;-)
3755 switch ($context->contextlevel) {
3757 case CONTEXT_BLOCK:
3758 // No children.
3759 return array();
3760 break;
3762 case CONTEXT_MODULE:
3763 // No children.
3764 return array();
3765 break;
3767 case CONTEXT_GROUP:
3768 // No children.
3769 return array();
3770 break;
3772 case CONTEXT_COURSE:
3773 // Find
3774 // - module instances - easy
3775 // - groups
3776 // - blocks assigned to the course-view page explicitly - easy
3777 // - blocks pinned (note! we get all of them here, regardless of vis)
3778 $sql = " SELECT ctx.*
3779 FROM {$CFG->prefix}context ctx
3780 WHERE ctx.path LIKE '{$context->path}/%'
3781 AND ctx.contextlevel IN (".CONTEXT_MODULE.",".CONTEXT_BLOCK.")
3782 UNION
3783 SELECT ctx.*
3784 FROM {$CFG->prefix}context ctx
3785 JOIN {$CFG->prefix}groups g
3786 ON (ctx.instanceid=g.id AND ctx.contextlevel=".CONTEXT_GROUP.")
3787 WHERE g.courseid={$context->instanceid}
3788 UNION
3789 SELECT ctx.*
3790 FROM {$CFG->prefix}context ctx
3791 JOIN {$CFG->prefix}block_pinned b
3792 ON (ctx.instanceid=b.blockid AND ctx.contextlevel=".CONTEXT_BLOCK.")
3793 WHERE b.pagetype='course-view'
3795 $rs = get_recordset_sql($sql);
3796 $records = array();
3797 while ($rec = rs_fetch_next_record($rs)) {
3798 $records[$rec->id] = $rec;
3799 $context_cache[$rec->contextlevel][$rec->instanceid] = $rec;
3801 rs_close($rs);
3802 return $records;
3803 break;
3805 case CONTEXT_COURSECAT:
3806 // Find
3807 // - categories
3808 // - courses
3809 $sql = " SELECT ctx.*
3810 FROM {$CFG->prefix}context ctx
3811 WHERE ctx.path LIKE '{$context->path}/%'
3812 AND ctx.contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.")
3814 $rs = get_recordset_sql($sql);
3815 $records = array();
3816 while ($rec = rs_fetch_next_record($rs)) {
3817 $records[$rec->id] = $rec;
3818 $context_cache[$rec->contextlevel][$rec->instanceid] = $rec;
3820 rs_close($rs);
3821 return $records;
3822 break;
3824 case CONTEXT_USER:
3825 // No children.
3826 return array();
3827 break;
3829 case CONTEXT_SYSTEM:
3830 // Just get all the contexts except for CONTEXT_SYSTEM level
3831 // and hope we don't OOM in the process - don't cache
3832 $sql = 'SELECT c.*'.
3833 'FROM '.$CFG->prefix.'context c '.
3834 'WHERE contextlevel != '.CONTEXT_SYSTEM;
3836 return get_records_sql($sql);
3837 break;
3839 default:
3840 error('This is an unknown context (' . $context->contextlevel . ') in get_child_contexts!');
3841 return false;
3847 * Gets a string for sql calls, searching for stuff in this context or above
3848 * @param object $context
3849 * @return string
3851 function get_related_contexts_string($context) {
3852 if ($parents = get_parent_contexts($context)) {
3853 return (' IN ('.$context->id.','.implode(',', $parents).')');
3854 } else {
3855 return (' ='.$context->id);
3860 * Returns the human-readable, translated version of the capability.
3861 * Basically a big switch statement.
3862 * @param $capabilityname - e.g. mod/choice:readresponses
3864 function get_capability_string($capabilityname) {
3866 // Typical capabilityname is mod/choice:readresponses
3868 $names = split('/', $capabilityname);
3869 $stringname = $names[1]; // choice:readresponses
3870 $components = split(':', $stringname);
3871 $componentname = $components[0]; // choice
3873 switch ($names[0]) {
3874 case 'mod':
3875 $string = get_string($stringname, $componentname);
3876 break;
3878 case 'block':
3879 $string = get_string($stringname, 'block_'.$componentname);
3880 break;
3882 case 'moodle':
3883 if ($componentname == 'local') {
3884 $string = get_string($stringname, 'local');
3885 } else {
3886 $string = get_string($stringname, 'role');
3888 break;
3890 case 'enrol':
3891 $string = get_string($stringname, 'enrol_'.$componentname);
3892 break;
3894 case 'format':
3895 $string = get_string($stringname, 'format_'.$componentname);
3896 break;
3898 case 'gradeexport':
3899 $string = get_string($stringname, 'gradeexport_'.$componentname);
3900 break;
3902 case 'gradeimport':
3903 $string = get_string($stringname, 'gradeimport_'.$componentname);
3904 break;
3906 case 'gradereport':
3907 $string = get_string($stringname, 'gradereport_'.$componentname);
3908 break;
3910 default:
3911 $string = get_string($stringname);
3912 break;
3915 return $string;
3920 * This gets the mod/block/course/core etc strings.
3921 * @param $component
3922 * @param $contextlevel
3924 function get_component_string($component, $contextlevel) {
3926 switch ($contextlevel) {
3928 case CONTEXT_SYSTEM:
3929 if (preg_match('|^enrol/|', $component)) {
3930 $langname = str_replace('/', '_', $component);
3931 $string = get_string('enrolname', $langname);
3932 } else if (preg_match('|^block/|', $component)) {
3933 $langname = str_replace('/', '_', $component);
3934 $string = get_string('blockname', $langname);
3935 } else if (preg_match('|^local|', $component)) {
3936 $langname = str_replace('/', '_', $component);
3937 $string = get_string('local');
3938 } else {
3939 $string = get_string('coresystem');
3941 break;
3943 case CONTEXT_USER:
3944 $string = get_string('users');
3945 break;
3947 case CONTEXT_COURSECAT:
3948 $string = get_string('categories');
3949 break;
3951 case CONTEXT_COURSE:
3952 if (preg_match('|^gradeimport/|', $component)
3953 || preg_match('|^gradeexport/|', $component)
3954 || preg_match('|^gradereport/|', $component)) {
3955 $string = get_string('gradebook', 'admin');
3956 } else {
3957 $string = get_string('course');
3959 break;
3961 case CONTEXT_GROUP:
3962 $string = get_string('group');
3963 break;
3965 case CONTEXT_MODULE:
3966 $string = get_string('modulename', basename($component));
3967 break;
3969 case CONTEXT_BLOCK:
3970 if( $component == 'moodle' ){
3971 $string = get_string('block');
3972 }else{
3973 $string = get_string('blockname', 'block_'.basename($component));
3975 break;
3977 default:
3978 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
3979 return false;
3982 return $string;
3986 * Gets the list of roles assigned to this context and up (parents)
3987 * @param object $context
3988 * @param view - set to true when roles are pulled for display only
3989 * this is so that we can filter roles with no visible
3990 * assignment, for example, you might want to "hide" all
3991 * course creators when browsing the course participants
3992 * list.
3993 * @return array
3995 function get_roles_used_in_context($context, $view = false) {
3997 global $CFG;
3999 // filter for roles with all hidden assignments
4000 // no need to return when only pulling roles for reviewing
4001 // e.g. participants page.
4002 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
4003 $contextlist = get_related_contexts_string($context);
4005 $sql = "SELECT DISTINCT r.id,
4006 r.name,
4007 r.shortname,
4008 r.sortorder
4009 FROM {$CFG->prefix}role_assignments ra,
4010 {$CFG->prefix}role r
4011 WHERE r.id = ra.roleid
4012 AND ra.contextid $contextlist
4013 $hiddensql
4014 ORDER BY r.sortorder ASC";
4016 return get_records_sql($sql);
4020 * This function is used to print roles column in user profile page.
4021 * @param int userid
4022 * @param object context
4023 * @return string
4025 function get_user_roles_in_context($userid, $context, $view=true){
4026 global $CFG, $USER;
4028 $rolestring = '';
4029 $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';
4030 $rolenames = array();
4031 if ($roles = get_records_sql($SQL)) {
4032 foreach ($roles as $userrole) {
4033 // MDL-12544, if we are in view mode and current user has no capability to view hidden assignment, skip it
4034 if ($userrole->hidden && $view && !has_capability('moodle/role:viewhiddenassigns', $context)) {
4035 continue;
4037 $rolenames[$userrole->roleid] = $userrole->name;
4040 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
4042 foreach ($rolenames as $roleid => $rolename) {
4043 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
4045 $rolestring = implode(',', $rolenames);
4047 return $rolestring;
4052 * Checks if a user can override capabilities of a particular role in this context
4053 * @param object $context
4054 * @param int targetroleid - the id of the role you want to override
4055 * @return boolean
4057 function user_can_override($context, $targetroleid) {
4058 // first check if user has override capability
4059 // if not return false;
4060 if (!has_capability('moodle/role:override', $context)) {
4061 return false;
4063 // pull out all active roles of this user from this context(or above)
4064 if ($userroles = get_user_roles($context)) {
4065 foreach ($userroles as $userrole) {
4066 // if any in the role_allow_override table, then it's ok
4067 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
4068 return true;
4073 return false;
4078 * Checks if a user can assign users to a particular role in this context
4079 * @param object $context
4080 * @param int targetroleid - the id of the role you want to assign users to
4081 * @return boolean
4083 function user_can_assign($context, $targetroleid) {
4085 // first check if user has override capability
4086 // if not return false;
4087 if (!has_capability('moodle/role:assign', $context)) {
4088 return false;
4090 // pull out all active roles of this user from this context(or above)
4091 if ($userroles = get_user_roles($context)) {
4092 foreach ($userroles as $userrole) {
4093 // if any in the role_allow_override table, then it's ok
4094 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
4095 return true;
4100 return false;
4103 /** Returns all site roles in correct sort order.
4106 function get_all_roles() {
4107 return get_records('role', '', '', 'sortorder ASC');
4111 * gets all the user roles assigned in this context, or higher contexts
4112 * this is mainly used when checking if a user can assign a role, or overriding a role
4113 * i.e. we need to know what this user holds, in order to verify against allow_assign and
4114 * allow_override tables
4115 * @param object $context
4116 * @param int $userid
4117 * @param view - set to true when roles are pulled for display only
4118 * this is so that we can filter roles with no visible
4119 * assignment, for example, you might want to "hide" all
4120 * course creators when browsing the course participants
4121 * list.
4122 * @return array
4124 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
4126 global $USER, $CFG, $db;
4128 if (empty($userid)) {
4129 if (empty($USER->id)) {
4130 return array();
4132 $userid = $USER->id;
4134 // set up hidden sql
4135 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
4137 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
4138 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id.')';
4139 } else {
4140 $contexts = ' ra.contextid = \''.$context->id.'\'';
4143 if (!$return = get_records_sql('SELECT ra.*, r.name, r.shortname
4144 FROM '.$CFG->prefix.'role_assignments ra,
4145 '.$CFG->prefix.'role r,
4146 '.$CFG->prefix.'context c
4147 WHERE ra.userid = '.$userid.'
4148 AND ra.roleid = r.id
4149 AND ra.contextid = c.id
4150 AND '.$contexts . $hiddensql .'
4151 ORDER BY '.$order)) {
4152 $return = array();
4155 return $return;
4159 * Creates a record in the allow_override table
4160 * @param int sroleid - source roleid
4161 * @param int troleid - target roleid
4162 * @return int - id or false
4164 function allow_override($sroleid, $troleid) {
4165 $record = new object();
4166 $record->roleid = $sroleid;
4167 $record->allowoverride = $troleid;
4168 return insert_record('role_allow_override', $record);
4172 * Creates a record in the allow_assign table
4173 * @param int sroleid - source roleid
4174 * @param int troleid - target roleid
4175 * @return int - id or false
4177 function allow_assign($sroleid, $troleid) {
4178 $record = new object;
4179 $record->roleid = $sroleid;
4180 $record->allowassign = $troleid;
4181 return insert_record('role_allow_assign', $record);
4185 * Gets a list of roles that this user can assign in this context
4186 * @param object $context
4187 * @param string $field
4188 * @return array
4190 function get_assignable_roles ($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS) {
4192 global $CFG;
4194 // this users RAs
4195 $ras = get_user_roles($context);
4196 $roleids = array();
4197 foreach ($ras as $ra) {
4198 $roleids[] = $ra->roleid;
4200 unset($ra);
4202 if (count($roleids)===0) {
4203 return array();
4206 $roleids = implode(',',$roleids);
4208 // The subselect scopes the DISTINCT down to
4209 // the role ids - a DISTINCT over the whole of
4210 // the role table is much more expensive on some DBs
4211 $sql = "SELECT r.id, r.$field
4212 FROM {$CFG->prefix}role r
4213 JOIN ( SELECT DISTINCT allowassign as allowedrole
4214 FROM {$CFG->prefix}role_allow_assign raa
4215 WHERE raa.roleid IN ($roleids) ) ar
4216 ON r.id=ar.allowedrole
4217 ORDER BY sortorder ASC";
4219 $rs = get_recordset_sql($sql);
4220 $roles = array();
4221 while ($r = rs_fetch_next_record($rs)) {
4222 $roles[$r->id] = $r->{$field};
4224 rs_close($rs);
4226 return role_fix_names($roles, $context, $rolenamedisplay);
4230 * Gets a list of roles that this user can assign in this context, for the switchrole menu
4232 * This is a quick-fix for MDL-13459 until MDL-8312 is sorted out...
4233 * @param object $context
4234 * @param string $field
4235 * @return array
4237 function get_assignable_roles_for_switchrole ($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS) {
4239 global $CFG;
4241 // this users RAs
4242 $ras = get_user_roles($context);
4243 $roleids = array();
4244 foreach ($ras as $ra) {
4245 $roleids[] = $ra->roleid;
4247 unset($ra);
4249 if (count($roleids)===0) {
4250 return array();
4253 $roleids = implode(',',$roleids);
4255 // The subselect scopes the DISTINCT down to
4256 // the role ids - a DISTINCT over the whole of
4257 // the role table is much more expensive on some DBs
4258 $sql = "SELECT r.id, r.$field
4259 FROM {$CFG->prefix}role r
4260 JOIN ( SELECT DISTINCT allowassign as allowedrole
4261 FROM {$CFG->prefix}role_allow_assign raa
4262 WHERE raa.roleid IN ($roleids) ) ar
4263 ON r.id=ar.allowedrole
4264 JOIN {$CFG->prefix}role_capabilities rc
4265 ON (r.id = rc.roleid AND rc.capability = 'moodle/course:view'
4266 AND rc.capability != 'moodle/site:doanything')
4267 ORDER BY sortorder ASC";
4269 $rs = get_recordset_sql($sql);
4270 $roles = array();
4271 while ($r = rs_fetch_next_record($rs)) {
4272 $roles[$r->id] = $r->{$field};
4274 rs_close($rs);
4276 return role_fix_names($roles, $context, $rolenamedisplay);
4280 * Gets a list of roles that this user can override in this context
4281 * @param object $context
4282 * @return array
4284 function get_overridable_roles($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS) {
4286 $options = array();
4288 if ($roles = get_all_roles()) {
4289 foreach ($roles as $role) {
4290 if (user_can_override($context, $role->id)) {
4291 $options[$role->id] = $role->$field;
4296 return role_fix_names($options, $context, $rolenamedisplay);
4300 * Returns a role object that is the default role for new enrolments
4301 * in a given course
4303 * @param object $course
4304 * @return object $role
4306 function get_default_course_role($course) {
4307 global $CFG;
4309 /// First let's take the default role the course may have
4310 if (!empty($course->defaultrole)) {
4311 if ($role = get_record('role', 'id', $course->defaultrole)) {
4312 return $role;
4316 /// Otherwise the site setting should tell us
4317 if ($CFG->defaultcourseroleid) {
4318 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid)) {
4319 return $role;
4323 /// It's unlikely we'll get here, but just in case, try and find a student role
4324 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
4325 return array_shift($studentroles); /// Take the first one
4328 return NULL;
4333 * Who has this capability in this context?
4335 * This can be a very expensive call - use sparingly and keep
4336 * the results if you are going to need them again soon.
4338 * Note if $fields is empty this function attempts to get u.*
4339 * which can get rather large - and has a serious perf impact
4340 * on some DBs.
4342 * @param $context - object
4343 * @param $capability - string capability
4344 * @param $fields - fields to be pulled
4345 * @param $sort - the sort order
4346 * @param $limitfrom - number of records to skip (offset)
4347 * @param $limitnum - number of records to fetch
4348 * @param $groups - single group or array of groups - only return
4349 * users who are in one of these group(s).
4350 * @param $exceptions - list of users to exclude
4351 * @param view - set to true when roles are pulled for display only
4352 * this is so that we can filter roles with no visible
4353 * assignment, for example, you might want to "hide" all
4354 * course creators when browsing the course participants
4355 * list.
4356 * @param boolean $useviewallgroups if $groups is set the return users who
4357 * have capability both $capability and moodle/site:accessallgroups
4358 * in this context, as well as users who have $capability and who are
4359 * in $groups.
4361 function get_users_by_capability($context, $capability, $fields='', $sort='',
4362 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true,
4363 $view=false, $useviewallgroups=false) {
4364 global $CFG;
4366 $ctxids = substr($context->path, 1); // kill leading slash
4367 $ctxids = str_replace('/', ',', $ctxids);
4369 // Context is the frontpage
4370 $isfrontpage = false;
4371 $iscoursepage = false; // coursepage other than fp
4372 if ($context->contextlevel == CONTEXT_COURSE) {
4373 if ($context->instanceid == SITEID) {
4374 $isfrontpage = true;
4375 } else {
4376 $iscoursepage = true;
4380 // What roles/rolecaps are interesting?
4381 $caps = "'$capability'";
4382 if ($doanything===true) {
4383 $caps.=",'moodle/site:doanything'";
4384 $doanything_join='';
4385 $doanything_cond='';
4386 } else {
4387 // This is an outer join against
4388 // admin-ish roleids. Any row that succeeds
4389 // in JOINing here ends up removed from
4390 // the resultset. This means we remove
4391 // rolecaps from roles that also have
4392 // 'doanything' capabilities.
4393 $doanything_join="LEFT OUTER JOIN (
4394 SELECT DISTINCT rc.roleid
4395 FROM {$CFG->prefix}role_capabilities rc
4396 WHERE rc.capability='moodle/site:doanything'
4397 AND rc.permission=".CAP_ALLOW."
4398 AND rc.contextid IN ($ctxids)
4399 ) dar
4400 ON rc.roleid=dar.roleid";
4401 $doanything_cond="AND dar.roleid IS NULL";
4404 // fetch all capability records - we'll walk several
4405 // times over them, and should be a small set
4407 $negperm = false; // has any negative (<0) permission?
4408 $roleids = array();
4410 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability,
4411 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
4412 FROM {$CFG->prefix}role_capabilities rc
4413 JOIN {$CFG->prefix}context ctx on rc.contextid = ctx.id
4414 $doanything_join
4415 WHERE rc.capability IN ($caps) AND ctx.id IN ($ctxids)
4416 $doanything_cond
4417 ORDER BY rc.roleid ASC, ctx.depth ASC";
4418 if ($capdefs = get_records_sql($sql)) {
4419 foreach ($capdefs AS $rcid=>$rc) {
4420 $roleids[] = (int)$rc->roleid;
4421 if ($rc->permission < 0) {
4422 $negperm = true;
4427 $roleids = array_unique($roleids);
4429 if (count($roleids)===0) { // noone here!
4430 return false;
4433 // is the default role interesting? does it have
4434 // a relevant rolecap? (we use this a lot later)
4435 if (in_array((int)$CFG->defaultuserroleid, $roleids, true)) {
4436 $defaultroleinteresting = true;
4437 } else {
4438 $defaultroleinteresting = false;
4442 // Prepare query clauses
4444 $wherecond = array();
4445 /// Groups
4446 if ($groups) {
4447 if (is_array($groups)) {
4448 $grouptest = 'gm.groupid IN (' . implode(',', $groups) . ')';
4449 } else {
4450 $grouptest = 'gm.groupid = ' . $groups;
4452 $grouptest = 'ra.userid IN (SELECT userid FROM ' .
4453 $CFG->prefix . 'groups_members gm WHERE ' . $grouptest . ')';
4455 if ($useviewallgroups) {
4456 $viewallgroupsusers = get_users_by_capability($context,
4457 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
4458 $wherecond['groups'] = '('. $grouptest . ' OR ra.userid IN (' .
4459 implode(',', array_keys($viewallgroupsusers)) . '))';
4460 } else {
4461 $wherecond['groups'] = '(' . $grouptest .')';
4465 /// User exceptions
4466 if (!empty($exceptions)) {
4467 $wherecond['userexceptions'] = ' u.id NOT IN ('.$exceptions.')';
4470 /// Set up hidden role-assignments sql
4471 if ($view && !has_capability('moodle/role:viewhiddenassigns', $context)) {
4472 $condhiddenra = 'AND ra.hidden = 0 ';
4473 $sscondhiddenra = 'AND ssra.hidden = 0 ';
4474 } else {
4475 $condhiddenra = '';
4476 $sscondhiddenra = '';
4479 // Collect WHERE conditions
4480 $where = implode(' AND ', array_values($wherecond));
4481 if ($where != '') {
4482 $where = 'WHERE ' . $where;
4485 /// Set up default fields
4486 if (empty($fields)) {
4487 if ($iscoursepage) {
4488 $fields = 'u.*, ul.timeaccess as lastaccess';
4489 } else {
4490 $fields = 'u.*';
4494 /// Set up default sort
4495 if (empty($sort)) { // default to course lastaccess or just lastaccess
4496 if ($iscoursepage) {
4497 $sort = 'ul.timeaccess';
4498 } else {
4499 $sort = 'u.lastaccess';
4502 $sortby = $sort ? " ORDER BY $sort " : '';
4504 // User lastaccess JOIN
4505 if ((strpos($sort, 'ul.timeaccess') === FALSE) and (strpos($fields, 'ul.timeaccess') === FALSE)) { // user_lastaccess is not required MDL-13810
4506 $uljoin = '';
4507 } else {
4508 $uljoin = "LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul
4509 ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
4513 // Simple cases - No negative permissions means we can take shortcuts
4515 if (!$negperm) {
4517 // at the frontpage, and all site users have it - easy!
4518 if ($isfrontpage && !empty($CFG->defaultfrontpageroleid)
4519 && in_array((int)$CFG->defaultfrontpageroleid, $roleids, true)) {
4521 return get_records_sql("SELECT $fields
4522 FROM {$CFG->prefix}user u
4523 ORDER BY $sort",
4524 $limitfrom, $limitnum);
4527 // all site users have it, anyway
4528 // TODO: NOT ALWAYS! Check this case because this gets run for cases like this:
4529 // 1) Default role has the permission for a module thing like mod/choice:choose
4530 // 2) We are checking for an activity module context in a course
4531 // 3) Thus all users are returned even though course:view is also required
4532 if ($defaultroleinteresting) {
4533 $sql = "SELECT $fields
4534 FROM {$CFG->prefix}user u
4535 $uljoin
4536 $where
4537 ORDER BY $sort";
4538 return get_records_sql($sql, $limitfrom, $limitnum);
4541 /// Simple SQL assuming no negative rolecaps.
4542 /// We use a subselect to grab the role assignments
4543 /// ensuring only one row per user -- even if they
4544 /// have many "relevant" role assignments.
4545 $select = " SELECT $fields";
4546 $from = " FROM {$CFG->prefix}user u
4547 JOIN (SELECT DISTINCT ssra.userid
4548 FROM {$CFG->prefix}role_assignments ssra
4549 WHERE ssra.contextid IN ($ctxids)
4550 AND ssra.roleid IN (".implode(',',$roleids) .")
4551 $sscondhiddenra
4552 ) ra ON ra.userid = u.id
4553 $uljoin ";
4554 $where = " WHERE u.deleted = 0 ";
4555 if (count(array_keys($wherecond))) {
4556 $where .= ' AND ' . implode(' AND ', array_values($wherecond));
4558 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
4562 // If there are any negative rolecaps, we need to
4563 // work through a subselect that will bring several rows
4564 // per user (one per RA).
4565 // Since we cannot do the job in pure SQL (not without SQL stored
4566 // procedures anyway), we end up tied to processing the data in PHP
4567 // all the way down to pagination.
4569 // In some cases, this will mean bringing across a ton of data --
4570 // when paginating, we have to walk the permisisons of all the rows
4571 // in the _previous_ pages to get the pagination correct in the case
4572 // of users that end up not having the permission - this removed.
4575 // Prepare the role permissions datastructure for fast lookups
4576 $roleperms = array(); // each role cap and depth
4577 foreach ($capdefs AS $rcid=>$rc) {
4579 $rid = (int)$rc->roleid;
4580 $perm = (int)$rc->permission;
4581 $rcdepth = (int)$rc->ctxdepth;
4582 if (!isset($roleperms[$rc->capability][$rid])) {
4583 $roleperms[$rc->capability][$rid] = (object)array('perm' => $perm,
4584 'rcdepth' => $rcdepth);
4585 } else {
4586 if ($roleperms[$rc->capability][$rid]->perm == CAP_PROHIBIT) {
4587 continue;
4589 // override - as we are going
4590 // from general to local perms
4591 // (as per the ORDER BY...depth ASC above)
4592 // and local perms win...
4593 $roleperms[$rc->capability][$rid] = (object)array('perm' => $perm,
4594 'rcdepth' => $rcdepth);
4599 if ($context->contextlevel == CONTEXT_SYSTEM
4600 || $isfrontpage
4601 || $defaultroleinteresting) {
4603 // Handle system / sitecourse / defaultrole-with-perhaps-neg-overrides
4604 // with a SELECT FROM user LEFT OUTER JOIN against ra -
4605 // This is expensive on the SQL and PHP sides -
4606 // moves a ton of data across the wire.
4607 $ss = "SELECT u.id as userid, ra.roleid,
4608 ctx.depth
4609 FROM {$CFG->prefix}user u
4610 LEFT OUTER JOIN {$CFG->prefix}role_assignments ra
4611 ON (ra.userid = u.id
4612 AND ra.contextid IN ($ctxids)
4613 AND ra.roleid IN (".implode(',',$roleids) .")
4614 $condhiddenra)
4615 LEFT OUTER JOIN {$CFG->prefix}context ctx
4616 ON ra.contextid=ctx.id
4617 WHERE u.deleted=0";
4618 } else {
4619 // "Normal complex case" - the rolecaps we are after will
4620 // be defined in a role assignment somewhere.
4621 $ss = "SELECT ra.userid as userid, ra.roleid,
4622 ctx.depth
4623 FROM {$CFG->prefix}role_assignments ra
4624 JOIN {$CFG->prefix}context ctx
4625 ON ra.contextid=ctx.id
4626 WHERE ra.contextid IN ($ctxids)
4627 $condhiddenra
4628 AND ra.roleid IN (".implode(',',$roleids) .")";
4631 $select = "SELECT $fields ,ra.roleid, ra.depth ";
4632 $from = "FROM ($ss) ra
4633 JOIN {$CFG->prefix}user u
4634 ON ra.userid=u.id
4635 $uljoin ";
4636 $where = "WHERE u.deleted = 0 ";
4637 if (count(array_keys($wherecond))) {
4638 $where .= ' AND ' . implode(' AND ', array_values($wherecond));
4641 // Each user's entries MUST come clustered together
4642 // and RAs ordered in depth DESC - the role/cap resolution
4643 // code depends on this.
4644 $sort .= ' , ra.userid ASC, ra.depth DESC';
4645 $sortby .= ' , ra.userid ASC, ra.depth DESC ';
4647 $rs = get_recordset_sql($select.$from.$where.$sortby);
4650 // Process the user accounts+RAs, folding repeats together...
4652 // The processing for this recordset is tricky - to fold
4653 // the role/perms of users with multiple role-assignments
4654 // correctly while still processing one-row-at-a-time
4655 // we need to add a few additional 'private' fields to
4656 // the results array - so we can treat the rows as a
4657 // state machine to track the cap/perms and at what RA-depth
4658 // and RC-depth they were defined.
4660 // So what we do here is:
4661 // - loop over rows, checking pagination limits
4662 // - when we find a new user, if we are in the page add it to the
4663 // $results, and start building $ras array with its role-assignments
4664 // - when we are dealing with the next user, or are at the end of the userlist
4665 // (last rec or last in page), trigger the check-permission idiom
4666 // - the check permission idiom will
4667 // - add the default enrolment if needed
4668 // - call has_capability_from_rarc(), which based on RAs and RCs will return a bool
4669 // (should be fairly tight code ;-) )
4670 // - if the user has permission, all is good, just $c++ (counter)
4671 // - ...else, decrease the counter - so pagination is kept straight,
4672 // and (if we are in the page) remove from the results
4674 $results = array();
4676 // pagination controls
4677 $c = 0;
4678 $limitfrom = (int)$limitfrom;
4679 $limitnum = (int)$limitnum;
4682 // Track our last user id so we know when we are dealing
4683 // with a new user...
4685 $lastuserid = 0;
4687 // In this loop, we
4688 // $ras: role assignments, multidimensional array
4689 // treat as a stack - going from local to general
4690 // $ras = (( roleid=> x, $depth=>y) , ( roleid=> x, $depth=>y))
4692 while ($user = rs_fetch_next_record($rs)) {
4694 //error_log(" Record: " . print_r($user,1));
4697 // Pagination controls
4698 // Note that we might end up removing a user
4699 // that ends up _not_ having the rights,
4700 // therefore rolling back $c
4702 if ($lastuserid != $user->id) {
4704 // Did the last user end up with a positive permission?
4705 if ($lastuserid !=0) {
4706 if ($defaultroleinteresting) {
4707 // add the role at the end of $ras
4708 $ras[] = array( 'roleid' => $CFG->defaultuserroleid,
4709 'depth' => 1 );
4711 if (has_capability_from_rarc($ras, $roleperms, $capability, $doanything)) {
4712 $c++;
4713 } else {
4714 // remove the user from the result set,
4715 // only if we are 'in the page'
4716 if ($limitfrom === 0 || $c >= $limitfrom) {
4717 unset($results[$lastuserid]);
4722 // Did we hit pagination limit?
4723 if ($limitnum !==0 && $c >= ($limitfrom+$limitnum)) { // we are done!
4724 break;
4727 // New user setup, and $ras reset
4728 $lastuserid = $user->id;
4729 $ras = array();
4730 if (!empty($user->roleid)) {
4731 $ras[] = array( 'roleid' => (int)$user->roleid,
4732 'depth' => (int)$user->depth );
4735 // if we are 'in the page', also add the rec
4736 // to the results...
4737 if ($limitfrom === 0 || $c >= $limitfrom) {
4738 $results[$user->id] = $user; // trivial
4740 } else {
4741 // Additional RA for $lastuserid
4742 $ras[] = array( 'roleid'=>(int)$user->roleid,
4743 'depth'=>(int)$user->depth );
4746 } // end while(fetch)
4748 // Prune last entry if necessary
4749 if ($lastuserid !=0) {
4750 if ($defaultroleinteresting) {
4751 // add the role at the end of $ras
4752 $ras[] = array( 'roleid' => $CFG->defaultuserroleid,
4753 'depth' => 1 );
4755 if (!has_capability_from_rarc($ras, $roleperms, $capability, $doanything)) {
4756 // remove the user from the result set,
4757 // only if we are 'in the page'
4758 if ($limitfrom === 0 || $c >= $limitfrom) {
4759 if (isset($results[$lastuserid])) {
4760 unset($results[$lastuserid]);
4766 return $results;
4770 * Fast (fast!) utility function to resolve if a capability is granted,
4771 * based on Role Assignments and Role Capabilities.
4773 * Used (at least) by get_users_by_capability().
4775 * If PHP had fast built-in memoize functions, we could
4776 * add a $contextid parameter and memoize the return values.
4778 * @param array $ras - role assignments
4779 * @param array $roleperms - role permissions
4780 * @param string $capability - name of the capability
4781 * @param bool $doanything
4782 * @return boolean
4785 function has_capability_from_rarc($ras, $roleperms, $capability, $doanything) {
4786 // Mini-state machine, using $hascap
4787 // $hascap[ 'moodle/foo:bar' ]->perm = CAP_SOMETHING (numeric constant)
4788 // $hascap[ 'moodle/foo:bar' ]->radepth = depth of the role assignment that set it
4789 // $hascap[ 'moodle/foo:bar' ]->rcdepth = depth of the rolecap that set it
4790 // -- when resolving conflicts, we need to look into radepth first, if unresolved
4792 $caps = array($capability);
4793 if ($doanything) {
4794 $caps[] = 'moodle/site:candoanything';
4797 $hascap = array();
4800 // Compute which permission/roleassignment/rolecap
4801 // wins for each capability we are walking
4803 foreach ($ras as $ra) {
4804 foreach ($caps as $cap) {
4805 if (!isset($roleperms[$cap][$ra['roleid']])) {
4806 // nothing set for this cap - skip
4807 continue;
4809 // We explicitly clone here as we
4810 // add more properties to it
4811 // that must stay separate from the
4812 // original roleperm data structure
4813 $rp = clone($roleperms[$cap][$ra['roleid']]);
4814 $rp->radepth = $ra['depth'];
4816 // Trivial case, we are the first to set
4817 if (!isset($hascap[$cap])) {
4818 $hascap[$cap] = $rp;
4822 // Resolve who prevails, in order of precendence
4823 // - Prohibits always wins
4824 // - Locality of RA
4825 // - Locality of RC
4827 //// Prohibits...
4828 if ($rp->perm === CAP_PROHIBIT) {
4829 $hascap[$cap] = $rp;
4830 continue;
4832 if ($hascap[$cap]->perm === CAP_PROHIBIT) {
4833 continue;
4836 // Locality of RA - the look is ordered by depth DESC
4837 // so from local to general -
4838 // Higher RA loses to local RA... unless perm===0
4839 /// Thanks to the order of the records, $rp->radepth <= $hascap[$cap]->radepth
4840 if ($rp->radepth > $hascap[$cap]->radepth) {
4841 error_log('Should not happen @ ' . __FUNCTION__.':'.__LINE__);
4843 if ($rp->radepth < $hascap[$cap]->radepth) {
4844 if ($hascap[$cap]->perm!==0) {
4845 // Wider RA loses to local RAs...
4846 continue;
4847 } else {
4848 // "Higher RA resolves conflict" case,
4849 // local RAs had cancelled eachother
4850 $hascap[$cap] = $rp;
4851 continue;
4854 // Same ralevel - locality of RC wins
4855 if ($rp->rcdepth > $hascap[$cap]->rcdepth) {
4856 $hascap[$cap] = $rp;
4857 continue;
4859 if ($rp->rcdepth > $hascap[$cap]->rcdepth) {
4860 continue;
4862 // We match depth - add them
4863 $hascap[$cap]->perm += $rp->perm;
4866 if ($hascap[$capability]->perm > 0
4867 || ($doanything && isset($hascap['moodle/site:candoanything'])
4868 && $hascap['moodle/site:candoanything']->perm > 0)) {
4869 return true;
4871 return false;
4875 * Will re-sort a $users results array (from get_users_by_capability(), usually)
4876 * based on a sorting policy. This is to support the odd practice of
4877 * sorting teachers by 'authority', where authority was "lowest id of the role
4878 * assignment".
4880 * Will execute 1 database query. Only suitable for small numbers of users, as it
4881 * uses an u.id IN() clause.
4883 * Notes about the sorting criteria.
4885 * As a default, we cannot rely on role.sortorder because then
4886 * admins/coursecreators will always win. That is why the sane
4887 * rule "is locality matters most", with sortorder as 2nd
4888 * consideration.
4890 * If you want role.sortorder, use the 'sortorder' policy, and
4891 * name explicitly what roles you want to cover. It's probably
4892 * a good idea to see what roles have the capabilities you want
4893 * (array_diff() them against roiles that have 'can-do-anything'
4894 * to weed out admin-ish roles. Or fetch a list of roles from
4895 * variables like $CFG->coursemanagers .
4897 * @param array users Users' array, keyed on userid
4898 * @param object context
4899 * @param array roles - ids of the roles to include, optional
4900 * @param string policy - defaults to locality, more about
4901 * @return array - sorted copy of the array
4903 function sort_by_roleassignment_authority($users, $context, $roles=array(), $sortpolicy='locality') {
4904 global $CFG;
4906 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
4907 $contextwhere = ' ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
4908 if (empty($roles)) {
4909 $roleswhere = '';
4910 } else {
4911 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
4914 $sql = "SELECT ra.userid
4915 FROM {$CFG->prefix}role_assignments ra
4916 JOIN {$CFG->prefix}role r
4917 ON ra.roleid=r.id
4918 JOIN {$CFG->prefix}context ctx
4919 ON ra.contextid=ctx.id
4920 WHERE
4921 $userswhere
4922 AND $contextwhere
4923 $roleswhere
4926 // Default 'locality' policy -- read PHPDoc notes
4927 // about sort policies...
4928 $orderby = 'ORDER BY
4929 ctx.depth DESC, /* locality wins */
4930 r.sortorder ASC, /* rolesorting 2nd criteria */
4931 ra.id /* role assignment order tie-breaker */';
4932 if ($sortpolicy === 'sortorder') {
4933 $orderby = 'ORDER BY
4934 r.sortorder ASC, /* rolesorting 2nd criteria */
4935 ra.id /* role assignment order tie-breaker */';
4938 $sortedids = get_fieldset_sql($sql . $orderby);
4939 $sortedusers = array();
4940 $seen = array();
4942 foreach ($sortedids as $id) {
4943 // Avoid duplicates
4944 if (isset($seen[$id])) {
4945 continue;
4947 $seen[$id] = true;
4949 // assign
4950 $sortedusers[$id] = $users[$id];
4952 return $sortedusers;
4956 * gets all the users assigned this role in this context or higher
4957 * @param int roleid (can also be an array of ints!)
4958 * @param int contextid
4959 * @param bool parent if true, get list of users assigned in higher context too
4960 * @param string fields - fields from user (u.) , role assignment (ra) or role (r.)
4961 * @param string sort - sort from user (u.) , role assignment (ra) or role (r.)
4962 * @param bool gethidden - whether to fetch hidden enrolments too
4963 * @return array()
4965 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $gethidden=true, $group='', $limitfrom='', $limitnum='') {
4966 global $CFG;
4968 if (empty($fields)) {
4969 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
4970 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
4971 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4972 'u.emailstop, u.lang, u.timezone, r.name as rolename';
4975 // whether this assignment is hidden
4976 $hiddensql = $gethidden ? '': ' AND ra.hidden = 0 ';
4978 $parentcontexts = '';
4979 if ($parent) {
4980 $parentcontexts = substr($context->path, 1); // kill leading slash
4981 $parentcontexts = str_replace('/', ',', $parentcontexts);
4982 if ($parentcontexts !== '') {
4983 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4987 if (is_array($roleid)) {
4988 $roleselect = ' AND ra.roleid IN (' . implode(',',$roleid) .')';
4989 } elseif (!empty($roleid)) { // should not test for int, because it can come in as a string
4990 $roleselect = "AND ra.roleid = $roleid";
4991 } else {
4992 $roleselect = '';
4995 if ($group) {
4996 $groupjoin = "JOIN {$CFG->prefix}groups_members gm
4997 ON gm.userid = u.id";
4998 $groupselect = " AND gm.groupid = $group ";
4999 } else {
5000 $groupjoin = '';
5001 $groupselect = '';
5004 $SQL = "SELECT $fields, ra.roleid
5005 FROM {$CFG->prefix}role_assignments ra
5006 JOIN {$CFG->prefix}user u
5007 ON u.id = ra.userid
5008 JOIN {$CFG->prefix}role r
5009 ON ra.roleid = r.id
5010 $groupjoin
5011 WHERE (ra.contextid = $context->id $parentcontexts)
5012 $roleselect
5013 $groupselect
5014 $hiddensql
5015 ORDER BY $sort
5016 "; // join now so that we can just use fullname() later
5018 return get_records_sql($SQL, $limitfrom, $limitnum);
5022 * Counts all the users assigned this role in this context or higher
5023 * @param int roleid
5024 * @param int contextid
5025 * @param bool parent if true, get list of users assigned in higher context too
5026 * @return array()
5028 function count_role_users($roleid, $context, $parent=false) {
5029 global $CFG;
5031 if ($parent) {
5032 if ($contexts = get_parent_contexts($context)) {
5033 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
5034 } else {
5035 $parentcontexts = '';
5037 } else {
5038 $parentcontexts = '';
5041 $SQL = "SELECT count(u.id)
5042 FROM {$CFG->prefix}role_assignments r
5043 JOIN {$CFG->prefix}user u
5044 ON u.id = r.userid
5045 WHERE (r.contextid = $context->id $parentcontexts)
5046 AND r.roleid = $roleid
5047 AND u.deleted = 0";
5049 return count_records_sql($SQL);
5053 * This function gets the list of courses that this user has a particular capability in.
5054 * It is still not very efficient.
5055 * @param string $capability Capability in question
5056 * @param int $userid User ID or null for current user
5057 * @param bool $doanything True if 'doanything' is permitted (default)
5058 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
5059 * otherwise use a comma-separated list of the fields you require, not including id
5060 * @param string $orderby If set, use a comma-separated list of fields from course
5061 * table with sql modifiers (DESC) if needed
5062 * @return array Array of courses, may have zero entries. Or false if query failed.
5064 function get_user_capability_course($capability, $userid=NULL,$doanything=true,$fieldsexceptid='',$orderby='') {
5065 // Convert fields list and ordering
5066 $fieldlist='';
5067 if($fieldsexceptid) {
5068 $fields=explode(',',$fieldsexceptid);
5069 foreach($fields as $field) {
5070 $fieldlist.=',c.'.$field;
5073 if($orderby) {
5074 $fields=explode(',',$orderby);
5075 $orderby='';
5076 foreach($fields as $field) {
5077 if($orderby) {
5078 $orderby.=',';
5080 $orderby.='c.'.$field;
5082 $orderby='ORDER BY '.$orderby;
5085 // Obtain a list of everything relevant about all courses including context.
5086 // Note the result can be used directly as a context (we are going to), the course
5087 // fields are just appended.
5088 global $CFG;
5089 $rs=get_recordset_sql("
5090 SELECT
5091 x.*,c.id AS courseid$fieldlist
5092 FROM
5093 {$CFG->prefix}course c
5094 INNER JOIN {$CFG->prefix}context x ON c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE."
5095 $orderby
5097 if(!$rs) {
5098 return false;
5101 // Check capability for each course in turn
5102 $courses=array();
5103 while($coursecontext=rs_fetch_next_record($rs)) {
5104 if(has_capability($capability,$coursecontext,$userid,$doanything)) {
5105 // We've got the capability. Make the record look like a course record
5106 // and store it
5107 $coursecontext->id=$coursecontext->courseid;
5108 unset($coursecontext->courseid);
5109 unset($coursecontext->contextlevel);
5110 unset($coursecontext->instanceid);
5111 $courses[]=$coursecontext;
5114 return $courses;
5117 /** This function finds the roles assigned directly to this context only
5118 * i.e. no parents role
5119 * @param object $context
5120 * @return array
5122 function get_roles_on_exact_context($context) {
5124 global $CFG;
5126 return get_records_sql("SELECT r.*
5127 FROM {$CFG->prefix}role_assignments ra,
5128 {$CFG->prefix}role r
5129 WHERE ra.roleid = r.id
5130 AND ra.contextid = $context->id");
5135 * Switches the current user to another role for the current session and only
5136 * in the given context.
5138 * The caller *must* check
5139 * - that this op is allowed
5140 * - that the requested role can be assigned in this ctx
5141 * (hint, use get_assignable_roles())
5142 * - that the requested role is NOT $CFG->defaultuserroleid
5144 * To "unswitch" pass 0 as the roleid.
5146 * This function *will* modify $USER->access - beware
5148 * @param integer $roleid
5149 * @param object $context
5150 * @return bool
5152 function role_switch($roleid, $context) {
5153 global $USER, $CFG;
5156 // Plan of action
5158 // - Add the ghost RA to $USER->access
5159 // as $USER->access['rsw'][$path] = $roleid
5161 // - Make sure $USER->access['rdef'] has the roledefs
5162 // it needs to honour the switcheroo
5164 // Roledefs will get loaded "deep" here - down to the last child
5165 // context. Note that
5167 // - When visiting subcontexts, our selective accessdata loading
5168 // will still work fine - though those ra/rdefs will be ignored
5169 // appropriately while the switch is in place
5171 // - If a switcheroo happens at a category with tons of courses
5172 // (that have many overrides for switched-to role), the session
5173 // will get... quite large. Sometimes you just can't win.
5175 // To un-switch just unset($USER->access['rsw'][$path])
5178 // Add the switch RA
5179 if (!isset($USER->access['rsw'])) {
5180 $USER->access['rsw'] = array();
5183 if ($roleid == 0) {
5184 unset($USER->access['rsw'][$context->path]);
5185 if (empty($USER->access['rsw'])) {
5186 unset($USER->access['rsw']);
5188 return true;
5191 $USER->access['rsw'][$context->path]=$roleid;
5193 // Load roledefs
5194 $USER->access = get_role_access_bycontext($roleid, $context,
5195 $USER->access);
5197 /* DO WE NEED THIS AT ALL???
5198 // Add some permissions we are really going
5199 // to always need, even if the role doesn't have them!
5201 $USER->capabilities[$context->id]['moodle/course:view'] = CAP_ALLOW;
5204 return true;
5208 // get any role that has an override on exact context
5209 function get_roles_with_override_on_context($context) {
5211 global $CFG;
5213 return get_records_sql("SELECT r.*
5214 FROM {$CFG->prefix}role_capabilities rc,
5215 {$CFG->prefix}role r
5216 WHERE rc.roleid = r.id
5217 AND rc.contextid = $context->id");
5220 // get all capabilities for this role on this context (overrids)
5221 function get_capabilities_from_role_on_context($role, $context) {
5223 global $CFG;
5225 return get_records_sql("SELECT *
5226 FROM {$CFG->prefix}role_capabilities
5227 WHERE contextid = $context->id
5228 AND roleid = $role->id");
5231 // find out which roles has assignment on this context
5232 function get_roles_with_assignment_on_context($context) {
5234 global $CFG;
5236 return get_records_sql("SELECT r.*
5237 FROM {$CFG->prefix}role_assignments ra,
5238 {$CFG->prefix}role r
5239 WHERE ra.roleid = r.id
5240 AND ra.contextid = $context->id");
5246 * Find all user assignemnt of users for this role, on this context
5248 function get_users_from_role_on_context($role, $context) {
5250 global $CFG;
5252 return get_records_sql("SELECT *
5253 FROM {$CFG->prefix}role_assignments
5254 WHERE contextid = $context->id
5255 AND roleid = $role->id");
5259 * Simple function returning a boolean true if roles exist, otherwise false
5261 function user_has_role_assignment($userid, $roleid, $contextid=0) {
5263 if ($contextid) {
5264 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
5265 } else {
5266 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
5271 * Get role name or alias if exists and format the text.
5272 * @param object $role role object
5273 * @param object $coursecontext
5274 * @return $string name of role in course context
5276 function role_get_name($role, $coursecontext) {
5277 if ($r = get_record('role_names','roleid', $role->id,'contextid', $coursecontext->id)) {
5278 return strip_tags(format_string($r->name));
5279 } else {
5280 return strip_tags(format_string($role->name));
5285 * Prepare list of roles for display, apply aliases and format text
5286 * @param array $roleoptions array roleid=>rolename
5287 * @param object $context
5288 * @return array of role names
5290 function role_fix_names($roleoptions, $context, $rolenamedisplay=ROLENAME_ALIAS) {
5291 if ($rolenamedisplay != ROLENAME_ORIGINAL && !empty($context->id)) {
5292 if ($context->contextlevel == CONTEXT_MODULE || $context->contextlevel == CONTEXT_BLOCK) { // find the parent course context
5293 if ($parentcontextid = array_shift(get_parent_contexts($context))) {
5294 $context = get_context_instance_by_id($parentcontextid);
5297 if ($aliasnames = get_records('role_names', 'contextid', $context->id)) {
5298 if ($rolenamedisplay == ROLENAME_ALIAS) {
5299 foreach ($aliasnames as $alias) {
5300 if (isset($roleoptions[$alias->roleid])) {
5301 $roleoptions[$alias->roleid] = format_string($alias->name);
5304 } else if ($rolenamedisplay == ROLENAME_BOTH) {
5305 foreach ($aliasnames as $alias) {
5306 if (isset($roleoptions[$alias->roleid])) {
5307 $roleoptions[$alias->roleid] = format_string($alias->name).' ('.format_string($roleoptions[$alias->roleid]).')';
5313 foreach ($roleoptions as $rid => $name) {
5314 $roleoptions[$rid] = strip_tags($name);
5316 return $roleoptions;
5320 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
5321 * when we read in a new capability
5322 * most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
5323 * but when we are in grade, all reports/import/export capabilites should be together
5324 * @param string a - component string a
5325 * @param string b - component string b
5326 * @return bool - whether 2 component are in different "sections"
5328 function component_level_changed($cap, $comp, $contextlevel) {
5330 if ($cap->component == 'enrol/authorize' && $comp =='enrol/authorize') {
5331 return false;
5334 if (strstr($cap->component, '/') && strstr($comp, '/')) {
5335 $compsa = explode('/', $cap->component);
5336 $compsb = explode('/', $comp);
5340 // we are in gradebook, still
5341 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
5342 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
5343 return false;
5347 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
5351 * Populate context.path and context.depth where missing.
5352 * @param bool $force force a complete rebuild of the path and depth fields.
5353 * @param bool $feedback display feedback (during upgrade usually)
5354 * @return void
5356 function build_context_path($force=false, $feedback=false) {
5357 global $CFG;
5358 require_once($CFG->libdir.'/ddllib.php');
5360 // System context
5361 $sitectx = get_system_context(!$force);
5362 $base = '/'.$sitectx->id;
5364 // Sitecourse
5365 $sitecoursectx = get_record('context',
5366 'contextlevel', CONTEXT_COURSE,
5367 'instanceid', SITEID);
5368 if ($force || $sitecoursectx->path !== "$base/{$sitecoursectx->id}") {
5369 set_field('context', 'path', "$base/{$sitecoursectx->id}",
5370 'id', $sitecoursectx->id);
5371 set_field('context', 'depth', 2,
5372 'id', $sitecoursectx->id);
5373 $sitecoursectx = get_record('context',
5374 'contextlevel', CONTEXT_COURSE,
5375 'instanceid', SITEID);
5378 $ctxemptyclause = " AND (ctx.path IS NULL
5379 OR ctx.depth=0) ";
5380 $emptyclause = " AND ({$CFG->prefix}context.path IS NULL
5381 OR {$CFG->prefix}context.depth=0) ";
5382 if ($force) {
5383 $ctxemptyclause = $emptyclause = '';
5386 /* MDL-11347:
5387 * - mysql does not allow to use FROM in UPDATE statements
5388 * - using two tables after UPDATE works in mysql, but might give unexpected
5389 * results in pg 8 (depends on configuration)
5390 * - using table alias in UPDATE does not work in pg < 8.2
5392 if ($CFG->dbfamily == 'mysql') {
5393 $updatesql = "UPDATE {$CFG->prefix}context ct, {$CFG->prefix}context_temp temp
5394 SET ct.path = temp.path,
5395 ct.depth = temp.depth
5396 WHERE ct.id = temp.id";
5397 } else if ($CFG->dbfamily == 'oracle') {
5398 $updatesql = "UPDATE {$CFG->prefix}context ct
5399 SET (ct.path, ct.depth) =
5400 (SELECT temp.path, temp.depth
5401 FROM {$CFG->prefix}context_temp temp
5402 WHERE temp.id=ct.id)
5403 WHERE EXISTS (SELECT 'x'
5404 FROM {$CFG->prefix}context_temp temp
5405 WHERE temp.id = ct.id)";
5406 } else {
5407 $updatesql = "UPDATE {$CFG->prefix}context
5408 SET path = temp.path,
5409 depth = temp.depth
5410 FROM {$CFG->prefix}context_temp temp
5411 WHERE temp.id={$CFG->prefix}context.id";
5414 $udelsql = "TRUNCATE TABLE {$CFG->prefix}context_temp";
5416 // Top level categories
5417 $sql = "UPDATE {$CFG->prefix}context
5418 SET depth=2, path=" . sql_concat("'$base/'", 'id') . "
5419 WHERE contextlevel=".CONTEXT_COURSECAT."
5420 AND EXISTS (SELECT 'x'
5421 FROM {$CFG->prefix}course_categories cc
5422 WHERE cc.id = {$CFG->prefix}context.instanceid
5423 AND cc.depth=1)
5424 $emptyclause";
5426 execute_sql($sql, $feedback);
5428 execute_sql($udelsql, $feedback);
5430 // Deeper categories - one query per depthlevel
5431 $maxdepth = get_field_sql("SELECT MAX(depth)
5432 FROM {$CFG->prefix}course_categories");
5433 for ($n=2;$n<=$maxdepth;$n++) {
5434 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5435 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", $n+1
5436 FROM {$CFG->prefix}context ctx
5437 JOIN {$CFG->prefix}course_categories c ON ctx.instanceid=c.id
5438 JOIN {$CFG->prefix}context pctx ON c.parent=pctx.instanceid
5439 WHERE ctx.contextlevel=".CONTEXT_COURSECAT."
5440 AND pctx.contextlevel=".CONTEXT_COURSECAT."
5441 AND c.depth=$n
5442 AND NOT EXISTS (SELECT 'x'
5443 FROM {$CFG->prefix}context_temp temp
5444 WHERE temp.id = ctx.id)
5445 $ctxemptyclause";
5446 execute_sql($sql, $feedback);
5448 // this is needed after every loop
5449 // MDL-11532
5450 execute_sql($updatesql, $feedback);
5451 execute_sql($udelsql, $feedback);
5454 // Courses -- except sitecourse
5455 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5456 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5457 FROM {$CFG->prefix}context ctx
5458 JOIN {$CFG->prefix}course c ON ctx.instanceid=c.id
5459 JOIN {$CFG->prefix}context pctx ON c.category=pctx.instanceid
5460 WHERE ctx.contextlevel=".CONTEXT_COURSE."
5461 AND c.id!=".SITEID."
5462 AND pctx.contextlevel=".CONTEXT_COURSECAT."
5463 AND NOT EXISTS (SELECT 'x'
5464 FROM {$CFG->prefix}context_temp temp
5465 WHERE temp.id = ctx.id)
5466 $ctxemptyclause";
5467 execute_sql($sql, $feedback);
5469 execute_sql($updatesql, $feedback);
5470 execute_sql($udelsql, $feedback);
5472 // Module instances
5473 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5474 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5475 FROM {$CFG->prefix}context ctx
5476 JOIN {$CFG->prefix}course_modules cm ON ctx.instanceid=cm.id
5477 JOIN {$CFG->prefix}context pctx ON cm.course=pctx.instanceid
5478 WHERE ctx.contextlevel=".CONTEXT_MODULE."
5479 AND pctx.contextlevel=".CONTEXT_COURSE."
5480 AND NOT EXISTS (SELECT 'x'
5481 FROM {$CFG->prefix}context_temp temp
5482 WHERE temp.id = ctx.id)
5483 $ctxemptyclause";
5484 execute_sql($sql, $feedback);
5486 execute_sql($updatesql, $feedback);
5487 execute_sql($udelsql, $feedback);
5489 // Blocks - non-pinned course-view only
5490 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5491 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5492 FROM {$CFG->prefix}context ctx
5493 JOIN {$CFG->prefix}block_instance bi ON ctx.instanceid = bi.id
5494 JOIN {$CFG->prefix}context pctx ON bi.pageid=pctx.instanceid
5495 WHERE ctx.contextlevel=".CONTEXT_BLOCK."
5496 AND pctx.contextlevel=".CONTEXT_COURSE."
5497 AND bi.pagetype='course-view'
5498 AND NOT EXISTS (SELECT 'x'
5499 FROM {$CFG->prefix}context_temp temp
5500 WHERE temp.id = ctx.id)
5501 $ctxemptyclause";
5502 execute_sql($sql, $feedback);
5504 execute_sql($updatesql, $feedback);
5505 execute_sql($udelsql, $feedback);
5507 // Blocks - others
5508 $sql = "UPDATE {$CFG->prefix}context
5509 SET depth=2, path=".sql_concat("'$base/'", 'id')."
5510 WHERE contextlevel=".CONTEXT_BLOCK."
5511 AND EXISTS (SELECT 'x'
5512 FROM {$CFG->prefix}block_instance bi
5513 WHERE bi.id = {$CFG->prefix}context.instanceid
5514 AND bi.pagetype!='course-view')
5515 $emptyclause ";
5516 execute_sql($sql, $feedback);
5518 // User
5519 $sql = "UPDATE {$CFG->prefix}context
5520 SET depth=2, path=".sql_concat("'$base/'", 'id')."
5521 WHERE contextlevel=".CONTEXT_USER."
5522 AND EXISTS (SELECT 'x'
5523 FROM {$CFG->prefix}user u
5524 WHERE u.id = {$CFG->prefix}context.instanceid)
5525 $emptyclause ";
5526 execute_sql($sql, $feedback);
5528 // Personal TODO
5530 //TODO: fix group contexts
5532 // reset static course cache - it might have incorrect cached data
5533 global $context_cache, $context_cache_id;
5534 $context_cache = array();
5535 $context_cache_id = array();
5540 * Update the path field of the context and
5541 * all the dependent subcontexts that follow
5542 * the move.
5544 * The most important thing here is to be as
5545 * DB efficient as possible. This op can have a
5546 * massive impact in the DB.
5548 * @param obj current context obj
5549 * @param obj newparent new parent obj
5552 function context_moved($context, $newparent) {
5553 global $CFG;
5555 $frompath = $context->path;
5556 $newpath = $newparent->path . '/' . $context->id;
5558 $setdepth = '';
5559 if (($newparent->depth +1) != $context->depth) {
5560 $setdepth = ", depth= depth + ({$newparent->depth} - {$context->depth}) + 1";
5562 $sql = "UPDATE {$CFG->prefix}context
5563 SET path='$newpath'
5564 $setdepth
5565 WHERE path='$frompath'";
5566 execute_sql($sql,false);
5568 $len = strlen($frompath);
5569 $sql = "UPDATE {$CFG->prefix}context
5570 SET path = ".sql_concat("'$newpath'", 'SUBSTR(path, '.$len.' +1)')."
5571 $setdepth
5572 WHERE path LIKE '{$frompath}/%'";
5573 execute_sql($sql,false);
5575 mark_context_dirty($frompath);
5576 mark_context_dirty($newpath);
5581 * Turn the ctx* fields in an objectlike record
5582 * into a context subobject. This allows
5583 * us to SELECT from major tables JOINing with
5584 * context at no cost, saving a ton of context
5585 * lookups...
5587 function make_context_subobj($rec) {
5588 $ctx = new StdClass;
5589 $ctx->id = $rec->ctxid; unset($rec->ctxid);
5590 $ctx->path = $rec->ctxpath; unset($rec->ctxpath);
5591 $ctx->depth = $rec->ctxdepth; unset($rec->ctxdepth);
5592 $ctx->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
5593 $ctx->instanceid = $rec->id;
5595 $rec->context = $ctx;
5596 return $rec;
5600 * Fetch recent dirty contexts to know cheaply whether our $USER->access
5601 * is stale and needs to be reloaded.
5603 * Uses cache_flags
5604 * @param int $time
5605 * @return array of dirty contexts
5607 function get_dirty_contexts($time) {
5608 return get_cache_flags('accesslib/dirtycontexts', $time-2);
5612 * Mark a context as dirty (with timestamp)
5613 * so as to force reloading of the context.
5614 * @param string $path context path
5616 function mark_context_dirty($path) {
5617 global $CFG, $DIRTYCONTEXTS;
5618 // only if it is a non-empty string
5619 if (is_string($path) && $path !== '') {
5620 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
5621 if (isset($DIRTYCONTEXTS)) {
5622 $DIRTYCONTEXTS[$path] = 1;
5628 * Will walk the contextpath to answer whether
5629 * the contextpath is dirty
5631 * @param array $contexts array of strings
5632 * @param obj/array dirty contexts from get_dirty_contexts()
5633 * @return bool
5635 function is_contextpath_dirty($pathcontexts, $dirty) {
5636 $path = '';
5637 foreach ($pathcontexts as $ctx) {
5638 $path = $path.'/'.$ctx;
5639 if (isset($dirty[$path])) {
5640 return true;
5643 return false;
5648 * switch role order (used in admin/roles/manage.php)
5650 * @param int $first id of role to move down
5651 * @param int $second id of role to move up
5653 * @return bool success or failure
5655 function switch_roles($first, $second) {
5656 $status = true;
5657 //first find temorary sortorder number
5658 $tempsort = count_records('role') + 3;
5659 while (get_record('role','sortorder', $tempsort)) {
5660 $tempsort += 3;
5663 $r1 = new object();
5664 $r1->id = $first->id;
5665 $r1->sortorder = $tempsort;
5666 $r2 = new object();
5667 $r2->id = $second->id;
5668 $r2->sortorder = $first->sortorder;
5670 if (!update_record('role', $r1)) {
5671 debugging("Can not update role with ID $r1->id!");
5672 $status = false;
5675 if (!update_record('role', $r2)) {
5676 debugging("Can not update role with ID $r2->id!");
5677 $status = false;
5680 $r1->sortorder = $second->sortorder;
5681 if (!update_record('role', $r1)) {
5682 debugging("Can not update role with ID $r1->id!");
5683 $status = false;
5686 return $status;
5690 * duplicates all the base definitions of a role
5692 * @param object $sourcerole role to copy from
5693 * @param int $targetrole id of role to copy to
5695 * @return void
5697 function role_cap_duplicate($sourcerole, $targetrole) {
5698 global $CFG;
5699 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
5700 $caps = get_records_sql("SELECT * FROM {$CFG->prefix}role_capabilities
5701 WHERE roleid = $sourcerole->id
5702 AND contextid = $systemcontext->id");
5703 // adding capabilities
5704 foreach ($caps as $cap) {
5705 unset($cap->id);
5706 $cap->roleid = $targetrole;
5707 insert_record('role_capabilities', $cap);