Merge commit 'catalyst/MOODLE_19_STABLE' into mdl19-linuxchix
[moodle-linuxchix.git] / lib / accesslib.php
blobec27bf6d2930e5e06320f2042145962fb7da5bd0
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
9 // //
10 // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * Public API vs internals
28 * -----------------------
30 * General users probably only care about
32 * Context handling
33 * - get_context_instance()
34 * - get_context_instance_by_id()
35 * - get_parent_contexts()
36 * - get_child_contexts()
38 * Whether the user can do something...
39 * - has_capability()
40 * - require_capability()
41 * - require_login() (from moodlelib)
43 * What courses has this user access to?
44 * - get_user_courses_bycap()
46 * What users can do X in this context?
47 * - get_users_by_capability()
49 * Enrol/unenrol
50 * - enrol_into_course()
51 * - role_assign()/role_unassign()
54 * Advanced use
55 * - load_all_capabilities()
56 * - reload_all_capabilities()
57 * - $ACCESS global
58 * - has_capability_in_accessdata()
59 * - is_siteadmin()
60 * - get_user_access_sitewide()
61 * - load_subcontext()
62 * - get_role_access_bycontext()
64 * Name conventions
65 * ----------------
67 * - "ctx" means context
69 * accessdata
70 * ----------
72 * Access control data is held in the "accessdata" array
73 * which - for the logged-in user, will be in $USER->access
75 * For other users can be generated and passed around (but see
76 * the $ACCESS global).
78 * $accessdata is a multidimensional array, holding
79 * role assignments (RAs), role-capabilities-perm sets
80 * (role defs) and a list of courses we have loaded
81 * data for.
83 * Things are keyed on "contextpaths" (the path field of
84 * the context table) for fast walking up/down the tree.
86 * $accessdata[ra][$contextpath]= array($roleid)
87 * [$contextpath]= array($roleid)
88 * [$contextpath]= array($roleid)
90 * Role definitions are stored like this
91 * (no cap merge is done - so it's compact)
93 * $accessdata[rdef][$contextpath:$roleid][mod/forum:viewpost] = 1
94 * [mod/forum:editallpost] = -1
95 * [mod/forum:startdiscussion] = -1000
97 * See how has_capability_in_accessdata() walks up/down the tree.
99 * Normally - specially for the logged-in user, we only load
100 * rdef and ra down to the course level, but not below. This
101 * keeps accessdata small and compact. Below-the-course ra/rdef
102 * are loaded as needed. We keep track of which courses we
103 * have loaded ra/rdef in
105 * $accessdata[loaded] = array($contextpath, $contextpath)
107 * Stale accessdata
108 * ----------------
110 * For the logged-in user, accessdata is long-lived.
112 * On each pageload we load $DIRTYPATHS which lists
113 * context paths affected by changes. Any check at-or-below
114 * a dirty context will trigger a transparent reload of accessdata.
116 * Changes at the sytem level will force the reload for everyone.
118 * Default role caps
119 * -----------------
120 * The default role assignment is not in the DB, so we
121 * add it manually to accessdata.
123 * This means that functions that work directly off the
124 * DB need to ensure that the default role caps
125 * are dealt with appropriately.
129 require_once $CFG->dirroot.'/lib/blocklib.php';
131 // permission definitions
132 define('CAP_INHERIT', 0);
133 define('CAP_ALLOW', 1);
134 define('CAP_PREVENT', -1);
135 define('CAP_PROHIBIT', -1000);
137 // context definitions
138 define('CONTEXT_SYSTEM', 10);
139 define('CONTEXT_USER', 30);
140 define('CONTEXT_COURSECAT', 40);
141 define('CONTEXT_COURSE', 50);
142 define('CONTEXT_GROUP', 60);
143 define('CONTEXT_MODULE', 70);
144 define('CONTEXT_BLOCK', 80);
146 // capability risks - see http://docs.moodle.org/en/Development:Hardening_new_Roles_system
147 define('RISK_MANAGETRUST', 0x0001);
148 define('RISK_CONFIG', 0x0002);
149 define('RISK_XSS', 0x0004);
150 define('RISK_PERSONAL', 0x0008);
151 define('RISK_SPAM', 0x0010);
152 define('RISK_DATALOSS', 0x0020);
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;
1048 * It will return a nested array showing role assignments
1049 * all relevant role capabilities for the user at
1050 * site/metacourse/course_category/course levels
1052 * We do _not_ delve deeper than courses because the number of
1053 * overrides at the module/block levels is HUGE.
1055 * [ra] => [/path/] = array(roleid, roleid)
1056 * [rdef] => [/path/:roleid][capability]=permission
1057 * [loaded] => array('/path', '/path')
1059 * @param $userid integer - the id of the user
1062 function get_user_access_sitewide($userid) {
1064 global $CFG;
1066 // this flag has not been set!
1067 // (not clean install, or upgraded successfully to 1.7 and up)
1068 if (empty($CFG->rolesactive)) {
1069 return false;
1072 /* Get in 3 cheap DB queries...
1073 * - role assignments - with role_caps
1074 * - relevant role caps
1075 * - above this user's RAs
1076 * - below this user's RAs - limited to course level
1079 $accessdata = array(); // named list
1080 $accessdata['ra'] = array();
1081 $accessdata['rdef'] = array();
1082 $accessdata['loaded'] = array();
1084 $sitectx = get_system_context();
1085 $base = '/'.$sitectx->id;
1088 // Role assignments - and any rolecaps directly linked
1089 // because it's cheap to read rolecaps here over many
1090 // RAs
1092 $sql = "SELECT ctx.path, ra.roleid, rc.capability, rc.permission
1093 FROM {$CFG->prefix}role_assignments ra
1094 JOIN {$CFG->prefix}context ctx
1095 ON ra.contextid=ctx.id
1096 LEFT OUTER JOIN {$CFG->prefix}role_capabilities rc
1097 ON (rc.roleid=ra.roleid AND rc.contextid=ra.contextid)
1098 WHERE ra.userid = $userid AND ctx.contextlevel <= ".CONTEXT_COURSE."
1099 ORDER BY ctx.depth, ctx.path, ra.roleid";
1100 $rs = get_recordset_sql($sql);
1102 // raparents collects paths & roles we need to walk up
1103 // the parenthood to build the rdef
1105 // the array will bulk up a bit with dups
1106 // which we'll later clear up
1108 $raparents = array();
1109 $lastseen = '';
1110 if ($rs) {
1111 while ($ra = rs_fetch_next_record($rs)) {
1112 // RAs leafs are arrays to support multi
1113 // role assignments...
1114 if (!isset($accessdata['ra'][$ra->path])) {
1115 $accessdata['ra'][$ra->path] = array();
1117 // only add if is not a repeat caused
1118 // by capability join...
1119 // (this check is cheaper than in_array())
1120 if ($lastseen !== $ra->path.':'.$ra->roleid) {
1121 $lastseen = $ra->path.':'.$ra->roleid;
1122 array_push($accessdata['ra'][$ra->path], $ra->roleid);
1123 $parentids = explode('/', $ra->path);
1124 array_shift($parentids); // drop empty leading "context"
1125 array_pop($parentids); // drop _this_ context
1127 if (isset($raparents[$ra->roleid])) {
1128 $raparents[$ra->roleid] = array_merge($raparents[$ra->roleid],
1129 $parentids);
1130 } else {
1131 $raparents[$ra->roleid] = $parentids;
1134 // Always add the roleded
1135 if (!empty($ra->capability)) {
1136 $k = "{$ra->path}:{$ra->roleid}";
1137 $accessdata['rdef'][$k][$ra->capability] = $ra->permission;
1140 unset($ra);
1141 rs_close($rs);
1144 // Walk up the tree to grab all the roledefs
1145 // of interest to our user...
1146 // NOTE: we use a series of IN clauses here - which
1147 // might explode on huge sites with very convoluted nesting of
1148 // categories... - extremely unlikely that the number of categories
1149 // and roletypes is so large that we hit the limits of IN()
1150 $clauses = array();
1151 foreach ($raparents as $roleid=>$contexts) {
1152 $contexts = implode(',', array_unique($contexts));
1153 if ($contexts ==! '') {
1154 $clauses[] = "(roleid=$roleid AND contextid IN ($contexts))";
1157 $clauses = implode(" OR ", $clauses);
1158 if ($clauses !== '') {
1159 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1160 FROM {$CFG->prefix}role_capabilities rc
1161 JOIN {$CFG->prefix}context ctx
1162 ON rc.contextid=ctx.id
1163 WHERE $clauses
1164 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1166 $rs = get_recordset_sql($sql);
1167 unset($clauses);
1169 if ($rs) {
1170 while ($rd = rs_fetch_next_record($rs)) {
1171 $k = "{$rd->path}:{$rd->roleid}";
1172 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1174 unset($rd);
1175 rs_close($rs);
1180 // Overrides for the role assignments IN SUBCONTEXTS
1181 // (though we still do _not_ go below the course level.
1183 // NOTE that the JOIN w sctx is with 3-way triangulation to
1184 // catch overrides to the applicable role in any subcontext, based
1185 // on the path field of the parent.
1187 $sql = "SELECT sctx.path, ra.roleid,
1188 ctx.path AS parentpath,
1189 rco.capability, rco.permission
1190 FROM {$CFG->prefix}role_assignments ra
1191 JOIN {$CFG->prefix}context ctx
1192 ON ra.contextid=ctx.id
1193 JOIN {$CFG->prefix}context sctx
1194 ON (sctx.path LIKE " . sql_concat('ctx.path',"'/%'"). " )
1195 JOIN {$CFG->prefix}role_capabilities rco
1196 ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
1197 WHERE ra.userid = $userid
1198 AND sctx.contextlevel <= ".CONTEXT_COURSE."
1199 ORDER BY sctx.depth, sctx.path, ra.roleid";
1201 $rs = get_recordset_sql($sql);
1202 if ($rs) {
1203 while ($rd = rs_fetch_next_record($rs)) {
1204 $k = "{$rd->path}:{$rd->roleid}";
1205 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1207 unset($rd);
1208 rs_close($rs);
1210 return $accessdata;
1214 * It add to the access ctrl array the data
1215 * needed by a user for a given context
1217 * @param $userid integer - the id of the user
1218 * @param $context context obj - needs path!
1219 * @param $accessdata array accessdata array
1221 function load_subcontext($userid, $context, &$accessdata) {
1223 global $CFG;
1227 /* Get the additional RAs and relevant rolecaps
1228 * - role assignments - with role_caps
1229 * - relevant role caps
1230 * - above this user's RAs
1231 * - below this user's RAs - limited to course level
1234 $base = "/" . SYSCONTEXTID;
1237 // Replace $context with the target context we will
1238 // load. Normally, this will be a course context, but
1239 // may be a different top-level context.
1241 // We have 3 cases
1243 // - Course
1244 // - BLOCK/PERSON/USER/COURSE(sitecourse) hanging from SYSTEM
1245 // - BLOCK/MODULE/GROUP hanging from a course
1247 // For course contexts, we _already_ have the RAs
1248 // but the cost of re-fetching is minimal so we don't care.
1250 if ($context->contextlevel !== CONTEXT_COURSE
1251 && $context->path !== "$base/{$context->id}") {
1252 // Case BLOCK/MODULE/GROUP hanging from a course
1253 // Assumption: the course _must_ be our parent
1254 // If we ever see stuff nested further this needs to
1255 // change to do 1 query over the exploded path to
1256 // find out which one is the course
1257 $courses = explode('/',get_course_from_path($context->path));
1258 $targetid = array_pop($courses);
1259 $context = get_context_instance_by_id($targetid);
1264 // Role assignments in the context and below
1266 $sql = "SELECT ctx.path, ra.roleid
1267 FROM {$CFG->prefix}role_assignments ra
1268 JOIN {$CFG->prefix}context ctx
1269 ON ra.contextid=ctx.id
1270 WHERE ra.userid = $userid
1271 AND (ctx.path = '{$context->path}' OR ctx.path LIKE '{$context->path}/%')
1272 ORDER BY ctx.depth, ctx.path, ra.roleid";
1273 $rs = get_recordset_sql($sql);
1276 // Read in the RAs, preventing duplicates
1278 $localroles = array();
1279 $lastseen = '';
1280 while ($ra = rs_fetch_next_record($rs)) {
1281 if (!isset($accessdata['ra'][$ra->path])) {
1282 $accessdata['ra'][$ra->path] = array();
1284 // only add if is not a repeat caused
1285 // by capability join...
1286 // (this check is cheaper than in_array())
1287 if ($lastseen !== $ra->path.':'.$ra->roleid) {
1288 $lastseen = $ra->path.':'.$ra->roleid;
1289 array_push($accessdata['ra'][$ra->path], $ra->roleid);
1290 array_push($localroles, $ra->roleid);
1293 rs_close($rs);
1296 // Walk up and down the tree to grab all the roledefs
1297 // of interest to our user...
1299 // NOTES
1300 // - we use IN() but the number of roles is very limited.
1302 $courseroles = aggregate_roles_from_accessdata($context, $accessdata);
1304 // Do we have any interesting "local" roles?
1305 $localroles = array_diff($localroles,$courseroles); // only "new" local roles
1306 $wherelocalroles='';
1307 if (count($localroles)) {
1308 // Role defs for local roles in 'higher' contexts...
1309 $contexts = substr($context->path, 1); // kill leading slash
1310 $contexts = str_replace('/', ',', $contexts);
1311 $localroleids = implode(',',$localroles);
1312 $wherelocalroles="OR (rc.roleid IN ({$localroleids})
1313 AND ctx.id IN ($contexts))" ;
1316 // We will want overrides for all of them
1317 $whereroles = '';
1318 if ($roleids = implode(',',array_merge($courseroles,$localroles))) {
1319 $whereroles = "rc.roleid IN ($roleids) AND";
1321 $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1322 FROM {$CFG->prefix}role_capabilities rc
1323 JOIN {$CFG->prefix}context ctx
1324 ON rc.contextid=ctx.id
1325 WHERE ($whereroles
1326 (ctx.id={$context->id} OR ctx.path LIKE '{$context->path}/%'))
1327 $wherelocalroles
1328 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1330 $newrdefs = array();
1331 if ($rs = get_recordset_sql($sql)) {
1332 while ($rd = rs_fetch_next_record($rs)) {
1333 $k = "{$rd->path}:{$rd->roleid}";
1334 if (!array_key_exists($k, $newrdefs)) {
1335 $newrdefs[$k] = array();
1337 $newrdefs[$k][$rd->capability] = $rd->permission;
1339 rs_close($rs);
1340 } else {
1341 debugging('Bad SQL encountered!');
1344 compact_rdefs($newrdefs);
1345 foreach ($newrdefs as $key=>$value) {
1346 $accessdata['rdef'][$key] =& $newrdefs[$key];
1349 // error_log("loaded {$context->path}");
1350 $accessdata['loaded'][] = $context->path;
1354 * It add to the access ctrl array the data
1355 * needed by a role for a given context.
1357 * The data is added in the rdef key.
1359 * This role-centric function is useful for role_switching
1360 * and to get an overview of what a role gets under a
1361 * given context and below...
1363 * @param $roleid integer - the id of the user
1364 * @param $context context obj - needs path!
1365 * @param $accessdata accessdata array
1368 function get_role_access_bycontext($roleid, $context, $accessdata=NULL) {
1370 global $CFG;
1372 /* Get the relevant rolecaps into rdef
1373 * - relevant role caps
1374 * - at ctx and above
1375 * - below this ctx
1378 if (is_null($accessdata)) {
1379 $accessdata = array(); // named list
1380 $accessdata['ra'] = array();
1381 $accessdata['rdef'] = array();
1382 $accessdata['loaded'] = array();
1385 $contexts = substr($context->path, 1); // kill leading slash
1386 $contexts = str_replace('/', ',', $contexts);
1389 // Walk up and down the tree to grab all the roledefs
1390 // of interest to our role...
1392 // NOTE: we use an IN clauses here - which
1393 // might explode on huge sites with very convoluted nesting of
1394 // categories... - extremely unlikely that the number of nested
1395 // categories is so large that we hit the limits of IN()
1397 $sql = "SELECT ctx.path, rc.capability, rc.permission
1398 FROM {$CFG->prefix}role_capabilities rc
1399 JOIN {$CFG->prefix}context ctx
1400 ON rc.contextid=ctx.id
1401 WHERE rc.roleid=$roleid AND
1402 ( ctx.id IN ($contexts) OR
1403 ctx.path LIKE '{$context->path}/%' )
1404 ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1406 $rs = get_recordset_sql($sql);
1407 while ($rd = rs_fetch_next_record($rs)) {
1408 $k = "{$rd->path}:{$roleid}";
1409 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1411 rs_close($rs);
1413 return $accessdata;
1417 * Load accessdata for a user
1418 * into the $ACCESS global
1420 * Used by has_capability() - but feel free
1421 * to call it if you are about to run a BIG
1422 * cron run across a bazillion users.
1425 function load_user_accessdata($userid) {
1426 global $ACCESS,$CFG;
1428 $base = '/'.SYSCONTEXTID;
1430 $accessdata = get_user_access_sitewide($userid);
1431 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1433 // provide "default role" & set 'dr'
1435 if (!empty($CFG->defaultuserroleid)) {
1436 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1437 if (!isset($accessdata['ra'][$base])) {
1438 $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
1439 } else {
1440 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
1442 $accessdata['dr'] = $CFG->defaultuserroleid;
1446 // provide "default frontpage role"
1448 if (!empty($CFG->defaultfrontpageroleid)) {
1449 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1450 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1451 if (!isset($accessdata['ra'][$base])) {
1452 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
1453 } else {
1454 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
1457 // for dirty timestamps in cron
1458 $accessdata['time'] = time();
1460 $ACCESS[$userid] = $accessdata;
1461 compact_rdefs($ACCESS[$userid]['rdef']);
1463 return true;
1467 * Use shared copy of role definistions stored in $RDEFS;
1468 * @param array $rdefs array of role definitions in contexts
1470 function compact_rdefs(&$rdefs) {
1471 global $RDEFS;
1474 * This is a basic sharing only, we could also
1475 * use md5 sums of values. The main purpose is to
1476 * reduce mem in cron jobs - many users in $ACCESS array.
1479 foreach ($rdefs as $key => $value) {
1480 if (!array_key_exists($key, $RDEFS)) {
1481 $RDEFS[$key] = $rdefs[$key];
1483 $rdefs[$key] =& $RDEFS[$key];
1488 * A convenience function to completely load all the capabilities
1489 * for the current user. This is what gets called from complete_user_login()
1490 * for example. Call it only _after_ you've setup $USER and called
1491 * check_enrolment_plugins();
1494 function load_all_capabilities() {
1495 global $USER, $CFG, $DIRTYCONTEXTS;
1497 $base = '/'.SYSCONTEXTID;
1499 if (isguestuser()) {
1500 $guest = get_guest_role();
1502 // Load the rdefs
1503 $USER->access = get_role_access($guest->id);
1504 // Put the ghost enrolment in place...
1505 $USER->access['ra'][$base] = array($guest->id);
1508 } else if (isloggedin()) {
1510 $accessdata = get_user_access_sitewide($USER->id);
1513 // provide "default role" & set 'dr'
1515 if (!empty($CFG->defaultuserroleid)) {
1516 $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1517 if (!isset($accessdata['ra'][$base])) {
1518 $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
1519 } else {
1520 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
1522 $accessdata['dr'] = $CFG->defaultuserroleid;
1525 $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1528 // provide "default frontpage role"
1530 if (!empty($CFG->defaultfrontpageroleid)) {
1531 $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1532 $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1533 if (!isset($accessdata['ra'][$base])) {
1534 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
1535 } else {
1536 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
1539 $USER->access = $accessdata;
1541 } else if (!empty($CFG->notloggedinroleid)) {
1542 $USER->access = get_role_access($CFG->notloggedinroleid);
1543 $USER->access['ra'][$base] = array($CFG->notloggedinroleid);
1546 // Timestamp to read dirty context timestamps later
1547 $USER->access['time'] = time();
1548 $DIRTYCONTEXTS = array();
1550 // Clear to force a refresh
1551 unset($USER->mycourses);
1555 * A convenience function to completely reload all the capabilities
1556 * for the current user when roles have been updated in a relevant
1557 * context -- but PRESERVING switchroles and loginas.
1559 * That is - completely transparent to the user.
1561 * Note: rewrites $USER->access completely.
1564 function reload_all_capabilities() {
1565 global $USER,$CFG;
1567 // error_log("reloading");
1568 // copy switchroles
1569 $sw = array();
1570 if (isset($USER->access['rsw'])) {
1571 $sw = $USER->access['rsw'];
1572 // error_log(print_r($sw,1));
1575 unset($USER->access);
1576 unset($USER->mycourses);
1578 load_all_capabilities();
1580 foreach ($sw as $path => $roleid) {
1581 $context = get_record('context', 'path', $path);
1582 role_switch($roleid, $context);
1588 * Adds a temp role to an accessdata array.
1590 * Useful for the "temporary guest" access
1591 * we grant to logged-in users.
1593 * Note - assumes a course context!
1596 function load_temp_role($context, $roleid, $accessdata) {
1598 global $CFG;
1601 // Load rdefs for the role in -
1602 // - this context
1603 // - all the parents
1604 // - and below - IOWs overrides...
1607 // turn the path into a list of context ids
1608 $contexts = substr($context->path, 1); // kill leading slash
1609 $contexts = str_replace('/', ',', $contexts);
1611 $sql = "SELECT ctx.path,
1612 rc.capability, rc.permission
1613 FROM {$CFG->prefix}context ctx
1614 JOIN {$CFG->prefix}role_capabilities rc
1615 ON rc.contextid=ctx.id
1616 WHERE (ctx.id IN ($contexts)
1617 OR ctx.path LIKE '{$context->path}/%')
1618 AND rc.roleid = {$roleid}
1619 ORDER BY ctx.depth, ctx.path";
1620 $rs = get_recordset_sql($sql);
1621 while ($rd = rs_fetch_next_record($rs)) {
1622 $k = "{$rd->path}:{$roleid}";
1623 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1625 rs_close($rs);
1628 // Say we loaded everything for the course context
1629 // - which we just did - if the user gets a proper
1630 // RA in this session, this data will need to be reloaded,
1631 // but that is handled by the complete accessdata reload
1633 array_push($accessdata['loaded'], $context->path);
1636 // Add the ghost RA
1638 if (isset($accessdata['ra'][$context->path])) {
1639 array_push($accessdata['ra'][$context->path], $roleid);
1640 } else {
1641 $accessdata['ra'][$context->path] = array($roleid);
1644 return $accessdata;
1649 * Check all the login enrolment information for the given user object
1650 * by querying the enrolment plugins
1652 function check_enrolment_plugins(&$user) {
1653 global $CFG;
1655 static $inprogress; // To prevent this function being called more than once in an invocation
1657 if (!empty($inprogress[$user->id])) {
1658 return;
1661 $inprogress[$user->id] = true; // Set the flag
1663 require_once($CFG->dirroot .'/enrol/enrol.class.php');
1665 if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) {
1666 $plugins = array($CFG->enrol);
1669 foreach ($plugins as $plugin) {
1670 $enrol = enrolment_factory::factory($plugin);
1671 if (method_exists($enrol, 'setup_enrolments')) { /// Plugin supports Roles (Moodle 1.7 and later)
1672 $enrol->setup_enrolments($user);
1673 } else { /// Run legacy enrolment methods
1674 if (method_exists($enrol, 'get_student_courses')) {
1675 $enrol->get_student_courses($user);
1677 if (method_exists($enrol, 'get_teacher_courses')) {
1678 $enrol->get_teacher_courses($user);
1681 /// deal with $user->students and $user->teachers stuff
1682 unset($user->student);
1683 unset($user->teacher);
1685 unset($enrol);
1688 unset($inprogress[$user->id]); // Unset the flag
1692 * Installs the roles system.
1693 * This function runs on a fresh install as well as on an upgrade from the old
1694 * hard-coded student/teacher/admin etc. roles to the new roles system.
1696 function moodle_install_roles() {
1698 global $CFG, $db;
1700 /// Create a system wide context for assignemnt.
1701 $systemcontext = $context = get_context_instance(CONTEXT_SYSTEM);
1704 /// Create default/legacy roles and capabilities.
1705 /// (1 legacy capability per legacy role at system level).
1707 $adminrole = create_role(addslashes(get_string('administrator')), 'admin',
1708 addslashes(get_string('administratordescription')), 'moodle/legacy:admin');
1709 $coursecreatorrole = create_role(addslashes(get_string('coursecreators')), 'coursecreator',
1710 addslashes(get_string('coursecreatorsdescription')), 'moodle/legacy:coursecreator');
1711 $editteacherrole = create_role(addslashes(get_string('defaultcourseteacher')), 'editingteacher',
1712 addslashes(get_string('defaultcourseteacherdescription')), 'moodle/legacy:editingteacher');
1713 $noneditteacherrole = create_role(addslashes(get_string('noneditingteacher')), 'teacher',
1714 addslashes(get_string('noneditingteacherdescription')), 'moodle/legacy:teacher');
1715 $studentrole = create_role(addslashes(get_string('defaultcoursestudent')), 'student',
1716 addslashes(get_string('defaultcoursestudentdescription')), 'moodle/legacy:student');
1717 $guestrole = create_role(addslashes(get_string('guest')), 'guest',
1718 addslashes(get_string('guestdescription')), 'moodle/legacy:guest');
1719 $userrole = create_role(addslashes(get_string('authenticateduser')), 'user',
1720 addslashes(get_string('authenticateduserdescription')), 'moodle/legacy:user');
1722 /// Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles
1724 if (!assign_capability('moodle/site:doanything', CAP_ALLOW, $adminrole, $systemcontext->id)) {
1725 error('Could not assign moodle/site:doanything to the admin role');
1727 if (!update_capabilities()) {
1728 error('Had trouble upgrading the core capabilities for the Roles System');
1731 /// Look inside user_admin, user_creator, user_teachers, user_students and
1732 /// assign above new roles. If a user has both teacher and student role,
1733 /// only teacher role is assigned. The assignment should be system level.
1735 $dbtables = $db->MetaTables('TABLES');
1737 /// Set up the progress bar
1739 $usertables = array('user_admins', 'user_coursecreators', 'user_teachers', 'user_students');
1741 $totalcount = $progresscount = 0;
1742 foreach ($usertables as $usertable) {
1743 if (in_array($CFG->prefix.$usertable, $dbtables)) {
1744 $totalcount += count_records($usertable);
1748 print_progress(0, $totalcount, 5, 1, 'Processing role assignments');
1750 /// Upgrade the admins.
1751 /// Sort using id ASC, first one is primary admin.
1753 if (in_array($CFG->prefix.'user_admins', $dbtables)) {
1754 if ($rs = get_recordset_sql('SELECT * from '.$CFG->prefix.'user_admins ORDER BY ID ASC')) {
1755 while ($admin = rs_fetch_next_record($rs)) {
1756 role_assign($adminrole, $admin->userid, 0, $systemcontext->id);
1757 $progresscount++;
1758 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1760 rs_close($rs);
1762 } else {
1763 // This is a fresh install.
1767 /// Upgrade course creators.
1768 if (in_array($CFG->prefix.'user_coursecreators', $dbtables)) {
1769 if ($rs = get_recordset('user_coursecreators')) {
1770 while ($coursecreator = rs_fetch_next_record($rs)) {
1771 role_assign($coursecreatorrole, $coursecreator->userid, 0, $systemcontext->id);
1772 $progresscount++;
1773 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1775 rs_close($rs);
1780 /// Upgrade editting teachers and non-editting teachers.
1781 if (in_array($CFG->prefix.'user_teachers', $dbtables)) {
1782 if ($rs = get_recordset('user_teachers')) {
1783 while ($teacher = rs_fetch_next_record($rs)) {
1785 // removed code here to ignore site level assignments
1786 // since the contexts are separated now
1788 // populate the user_lastaccess table
1789 $access = new object();
1790 $access->timeaccess = $teacher->timeaccess;
1791 $access->userid = $teacher->userid;
1792 $access->courseid = $teacher->course;
1793 insert_record('user_lastaccess', $access);
1795 // assign the default student role
1796 $coursecontext = get_context_instance(CONTEXT_COURSE, $teacher->course); // needs cache
1797 // hidden teacher
1798 if ($teacher->authority == 0) {
1799 $hiddenteacher = 1;
1800 } else {
1801 $hiddenteacher = 0;
1804 if ($teacher->editall) { // editting teacher
1805 role_assign($editteacherrole, $teacher->userid, 0, $coursecontext->id, $teacher->timestart, $teacher->timeend, $hiddenteacher, $teacher->enrol, $teacher->timemodified);
1806 } else {
1807 role_assign($noneditteacherrole, $teacher->userid, 0, $coursecontext->id, $teacher->timestart, $teacher->timeend, $hiddenteacher, $teacher->enrol, $teacher->timemodified);
1809 $progresscount++;
1810 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1812 rs_close($rs);
1817 /// Upgrade students.
1818 if (in_array($CFG->prefix.'user_students', $dbtables)) {
1819 if ($rs = get_recordset('user_students')) {
1820 while ($student = rs_fetch_next_record($rs)) {
1822 // populate the user_lastaccess table
1823 $access = new object;
1824 $access->timeaccess = $student->timeaccess;
1825 $access->userid = $student->userid;
1826 $access->courseid = $student->course;
1827 insert_record('user_lastaccess', $access);
1829 // assign the default student role
1830 $coursecontext = get_context_instance(CONTEXT_COURSE, $student->course);
1831 role_assign($studentrole, $student->userid, 0, $coursecontext->id, $student->timestart, $student->timeend, 0, $student->enrol, $student->time);
1832 $progresscount++;
1833 print_progress($progresscount, $totalcount, 5, 1, 'Processing role assignments');
1835 rs_close($rs);
1840 /// Upgrade guest (only 1 entry).
1841 if ($guestuser = get_record('user', 'username', 'guest')) {
1842 role_assign($guestrole, $guestuser->id, 0, $systemcontext->id);
1844 print_progress($totalcount, $totalcount, 5, 1, 'Processing role assignments');
1847 /// Insert the correct records for legacy roles
1848 allow_assign($adminrole, $adminrole);
1849 allow_assign($adminrole, $coursecreatorrole);
1850 allow_assign($adminrole, $noneditteacherrole);
1851 allow_assign($adminrole, $editteacherrole);
1852 allow_assign($adminrole, $studentrole);
1853 allow_assign($adminrole, $guestrole);
1855 allow_assign($coursecreatorrole, $noneditteacherrole);
1856 allow_assign($coursecreatorrole, $editteacherrole);
1857 allow_assign($coursecreatorrole, $studentrole);
1858 allow_assign($coursecreatorrole, $guestrole);
1860 allow_assign($editteacherrole, $noneditteacherrole);
1861 allow_assign($editteacherrole, $studentrole);
1862 allow_assign($editteacherrole, $guestrole);
1864 /// Set up default allow override matrix
1865 allow_override($adminrole, $adminrole);
1866 allow_override($adminrole, $coursecreatorrole);
1867 allow_override($adminrole, $noneditteacherrole);
1868 allow_override($adminrole, $editteacherrole);
1869 allow_override($adminrole, $studentrole);
1870 allow_override($adminrole, $guestrole);
1871 allow_override($adminrole, $userrole);
1873 //See MDL-15841
1874 //allow_override($editteacherrole, $noneditteacherrole);
1875 //allow_override($editteacherrole, $studentrole);
1876 //allow_override($editteacherrole, $guestrole);
1879 /// Delete the old user tables when we are done
1881 $tables = array('user_students', 'user_teachers', 'user_coursecreators', 'user_admins');
1882 foreach ($tables as $tablename) {
1883 $table = new XMLDBTable($tablename);
1884 if (table_exists($table)) {
1885 drop_table($table);
1891 * Returns array of all legacy roles.
1893 function get_legacy_roles() {
1894 return array(
1895 'admin' => 'moodle/legacy:admin',
1896 'coursecreator' => 'moodle/legacy:coursecreator',
1897 'editingteacher' => 'moodle/legacy:editingteacher',
1898 'teacher' => 'moodle/legacy:teacher',
1899 'student' => 'moodle/legacy:student',
1900 'guest' => 'moodle/legacy:guest',
1901 'user' => 'moodle/legacy:user'
1905 function get_legacy_type($roleid) {
1906 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1907 $legacyroles = get_legacy_roles();
1909 $result = '';
1910 foreach($legacyroles as $ltype=>$lcap) {
1911 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
1912 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
1913 //choose first selected legacy capability - reset the rest
1914 if (empty($result)) {
1915 $result = $ltype;
1916 } else {
1917 unassign_capability($lcap, $roleid);
1922 return $result;
1926 * Assign the defaults found in this capabality definition to roles that have
1927 * the corresponding legacy capabilities assigned to them.
1928 * @param $legacyperms - an array in the format (example):
1929 * 'guest' => CAP_PREVENT,
1930 * 'student' => CAP_ALLOW,
1931 * 'teacher' => CAP_ALLOW,
1932 * 'editingteacher' => CAP_ALLOW,
1933 * 'coursecreator' => CAP_ALLOW,
1934 * 'admin' => CAP_ALLOW
1935 * @return boolean - success or failure.
1937 function assign_legacy_capabilities($capability, $legacyperms) {
1939 $legacyroles = get_legacy_roles();
1941 foreach ($legacyperms as $type => $perm) {
1943 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1945 if (!array_key_exists($type, $legacyroles)) {
1946 error('Incorrect legacy role definition for type: '.$type);
1949 if ($roles = get_roles_with_capability($legacyroles[$type], CAP_ALLOW)) {
1950 foreach ($roles as $role) {
1951 // Assign a site level capability.
1952 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1953 return false;
1958 return true;
1963 * Checks to see if a capability is a legacy capability.
1964 * @param $capabilityname
1965 * @return boolean
1967 function islegacy($capabilityname) {
1968 if (strpos($capabilityname, 'moodle/legacy') === 0) {
1969 return true;
1970 } else {
1971 return false;
1977 /**********************************
1978 * Context Manipulation functions *
1979 **********************************/
1982 * Create a new context record for use by all roles-related stuff
1983 * assumes that the caller has done the homework.
1985 * @param $level
1986 * @param $instanceid
1988 * @return object newly created context
1990 function create_context($contextlevel, $instanceid) {
1992 global $CFG;
1994 if ($contextlevel == CONTEXT_SYSTEM) {
1995 return create_system_context();
1998 $context = new object();
1999 $context->contextlevel = $contextlevel;
2000 $context->instanceid = $instanceid;
2002 // Define $context->path based on the parent
2003 // context. In other words... Who is your daddy?
2004 $basepath = '/' . SYSCONTEXTID;
2005 $basedepth = 1;
2007 $result = true;
2009 switch ($contextlevel) {
2010 case CONTEXT_COURSECAT:
2011 $sql = "SELECT ctx.path, ctx.depth
2012 FROM {$CFG->prefix}context ctx
2013 JOIN {$CFG->prefix}course_categories cc
2014 ON (cc.parent=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
2015 WHERE cc.id={$instanceid}";
2016 if ($p = get_record_sql($sql)) {
2017 $basepath = $p->path;
2018 $basedepth = $p->depth;
2019 } else if ($category = get_record('course_categories', 'id', $instanceid)) {
2020 if (empty($category->parent)) {
2021 // ok - this is a top category
2022 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $category->parent)) {
2023 $basepath = $parent->path;
2024 $basedepth = $parent->depth;
2025 } else {
2026 // wrong parent category - no big deal, this can be fixed later
2027 $basepath = null;
2028 $basedepth = 0;
2030 } else {
2031 // incorrect category id
2032 $result = false;
2034 break;
2036 case CONTEXT_COURSE:
2037 $sql = "SELECT ctx.path, ctx.depth
2038 FROM {$CFG->prefix}context ctx
2039 JOIN {$CFG->prefix}course c
2040 ON (c.category=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
2041 WHERE c.id={$instanceid} AND c.id !=" . SITEID;
2042 if ($p = get_record_sql($sql)) {
2043 $basepath = $p->path;
2044 $basedepth = $p->depth;
2045 } else if ($course = get_record('course', 'id', $instanceid)) {
2046 if ($course->id == SITEID) {
2047 //ok - no parent category
2048 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
2049 $basepath = $parent->path;
2050 $basedepth = $parent->depth;
2051 } else {
2052 // wrong parent category of course - no big deal, this can be fixed later
2053 $basepath = null;
2054 $basedepth = 0;
2056 } else if ($instanceid == SITEID) {
2057 // no errors for missing site course during installation
2058 return false;
2059 } else {
2060 // incorrect course id
2061 $result = false;
2063 break;
2065 case CONTEXT_MODULE:
2066 $sql = "SELECT ctx.path, ctx.depth
2067 FROM {$CFG->prefix}context ctx
2068 JOIN {$CFG->prefix}course_modules cm
2069 ON (cm.course=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
2070 WHERE cm.id={$instanceid}";
2071 if ($p = get_record_sql($sql)) {
2072 $basepath = $p->path;
2073 $basedepth = $p->depth;
2074 } else if ($cm = get_record('course_modules', 'id', $instanceid)) {
2075 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course)) {
2076 $basepath = $parent->path;
2077 $basedepth = $parent->depth;
2078 } else {
2079 // course does not exist - modules can not exist without a course
2080 $result = false;
2082 } else {
2083 // cm does not exist
2084 $result = false;
2086 break;
2088 case CONTEXT_BLOCK:
2089 // Only non-pinned & course-page based
2090 $sql = "SELECT ctx.path, ctx.depth
2091 FROM {$CFG->prefix}context ctx
2092 JOIN {$CFG->prefix}block_instance bi
2093 ON (bi.pageid=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
2094 WHERE bi.id={$instanceid} AND bi.pagetype='course-view'";
2095 if ($p = get_record_sql($sql)) {
2096 $basepath = $p->path;
2097 $basedepth = $p->depth;
2098 } else if ($bi = get_record('block_instance', 'id', $instanceid)) {
2099 if ($bi->pagetype != 'course-view') {
2100 // ok - not a course block
2101 } else if ($parent = get_context_instance(CONTEXT_COURSE, $bi->pageid)) {
2102 $basepath = $parent->path;
2103 $basedepth = $parent->depth;
2104 } else {
2105 // parent course does not exist - course blocks can not exist without a course
2106 $result = false;
2108 } else {
2109 // block does not exist
2110 $result = false;
2112 break;
2113 case CONTEXT_USER:
2114 // default to basepath
2115 break;
2118 // if grandparents unknown, maybe rebuild_context_path() will solve it later
2119 if ($basedepth != 0) {
2120 $context->depth = $basedepth+1;
2123 if ($result and $id = insert_record('context', $context)) {
2124 // can't set the full path till we know the id!
2125 if ($basedepth != 0 and !empty($basepath)) {
2126 set_field('context', 'path', $basepath.'/'. $id, 'id', $id);
2128 return get_context_instance_by_id($id);
2130 } else {
2131 debugging('Error: could not insert new context level "'.
2132 s($contextlevel).'", instance "'.
2133 s($instanceid).'".');
2134 return false;
2139 * This hacky function is needed because we can not change system context instanceid using normal upgrade routine.
2141 function get_system_context($cache=true) {
2142 static $cached = null;
2143 if ($cache and defined('SYSCONTEXTID')) {
2144 if (is_null($cached)) {
2145 $cached = new object();
2146 $cached->id = SYSCONTEXTID;
2147 $cached->contextlevel = CONTEXT_SYSTEM;
2148 $cached->instanceid = 0;
2149 $cached->path = '/'.SYSCONTEXTID;
2150 $cached->depth = 1;
2152 return $cached;
2155 if (!$context = get_record('context', 'contextlevel', CONTEXT_SYSTEM)) {
2156 $context = new object();
2157 $context->contextlevel = CONTEXT_SYSTEM;
2158 $context->instanceid = 0;
2159 $context->depth = 1;
2160 $context->path = NULL; //not known before insert
2162 if (!$context->id = insert_record('context', $context)) {
2163 // better something than nothing - let's hope it will work somehow
2164 if (!defined('SYSCONTEXTID')) {
2165 define('SYSCONTEXTID', 1);
2167 debugging('Can not create system context');
2168 $context->id = SYSCONTEXTID;
2169 $context->path = '/'.SYSCONTEXTID;
2170 return $context;
2174 if (!isset($context->depth) or $context->depth != 1 or $context->instanceid != 0 or $context->path != '/'.$context->id) {
2175 $context->instanceid = 0;
2176 $context->path = '/'.$context->id;
2177 $context->depth = 1;
2178 update_record('context', $context);
2181 if (!defined('SYSCONTEXTID')) {
2182 define('SYSCONTEXTID', $context->id);
2185 $cached = $context;
2186 return $cached;
2190 * Remove a context record and any dependent entries,
2191 * removes context from static context cache too
2192 * @param $level
2193 * @param $instanceid
2195 * @return bool properly deleted
2197 function delete_context($contextlevel, $instanceid) {
2198 global $context_cache, $context_cache_id;
2200 // do not use get_context_instance(), because the related object might not exist,
2201 // or the context does not exist yet and it would be created now
2202 if ($context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instanceid)) {
2203 $result = delete_records('role_assignments', 'contextid', $context->id) &&
2204 delete_records('role_capabilities', 'contextid', $context->id) &&
2205 delete_records('context', 'id', $context->id);
2207 // do not mark dirty contexts if parents unknown
2208 if (!is_null($context->path) and $context->depth > 0) {
2209 mark_context_dirty($context->path);
2212 // purge static context cache if entry present
2213 unset($context_cache[$contextlevel][$instanceid]);
2214 unset($context_cache_id[$context->id]);
2216 return $result;
2217 } else {
2219 return true;
2224 * Precreates all contexts including all parents
2225 * @param int $contextlevel, empty means all
2226 * @param bool $buildpaths update paths and depths
2227 * @param bool $feedback show sql feedback
2228 * @return void
2230 function create_contexts($contextlevel=null, $buildpaths=true, $feedback=false) {
2231 global $CFG;
2233 //make sure system context exists
2234 $syscontext = get_system_context(false);
2236 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSECAT
2237 or $contextlevel == CONTEXT_COURSE
2238 or $contextlevel == CONTEXT_MODULE
2239 or $contextlevel == CONTEXT_BLOCK) {
2240 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2241 SELECT ".CONTEXT_COURSECAT.", cc.id
2242 FROM {$CFG->prefix}course_categories cc
2243 WHERE NOT EXISTS (SELECT 'x'
2244 FROM {$CFG->prefix}context cx
2245 WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
2246 execute_sql($sql, $feedback);
2250 if (empty($contextlevel) or $contextlevel == CONTEXT_COURSE
2251 or $contextlevel == CONTEXT_MODULE
2252 or $contextlevel == CONTEXT_BLOCK) {
2253 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2254 SELECT ".CONTEXT_COURSE.", c.id
2255 FROM {$CFG->prefix}course c
2256 WHERE NOT EXISTS (SELECT 'x'
2257 FROM {$CFG->prefix}context cx
2258 WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
2259 execute_sql($sql, $feedback);
2263 if (empty($contextlevel) or $contextlevel == CONTEXT_MODULE) {
2264 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2265 SELECT ".CONTEXT_MODULE.", cm.id
2266 FROM {$CFG->prefix}course_modules cm
2267 WHERE NOT EXISTS (SELECT 'x'
2268 FROM {$CFG->prefix}context cx
2269 WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
2270 execute_sql($sql, $feedback);
2273 if (empty($contextlevel) or $contextlevel == CONTEXT_BLOCK) {
2274 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2275 SELECT ".CONTEXT_BLOCK.", bi.id
2276 FROM {$CFG->prefix}block_instance bi
2277 WHERE NOT EXISTS (SELECT 'x'
2278 FROM {$CFG->prefix}context cx
2279 WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
2280 execute_sql($sql, $feedback);
2283 if (empty($contextlevel) or $contextlevel == CONTEXT_USER) {
2284 $sql = "INSERT INTO {$CFG->prefix}context (contextlevel, instanceid)
2285 SELECT ".CONTEXT_USER.", u.id
2286 FROM {$CFG->prefix}user u
2287 WHERE u.deleted=0
2288 AND NOT EXISTS (SELECT 'x'
2289 FROM {$CFG->prefix}context cx
2290 WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
2291 execute_sql($sql, $feedback);
2295 if ($buildpaths) {
2296 build_context_path(false, $feedback);
2301 * Remove stale context records
2303 * @return bool
2305 function cleanup_contexts() {
2306 global $CFG;
2308 $sql = " SELECT c.contextlevel,
2309 c.instanceid AS instanceid
2310 FROM {$CFG->prefix}context c
2311 LEFT OUTER JOIN {$CFG->prefix}course_categories t
2312 ON c.instanceid = t.id
2313 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSECAT . "
2314 UNION
2315 SELECT c.contextlevel,
2316 c.instanceid
2317 FROM {$CFG->prefix}context c
2318 LEFT OUTER JOIN {$CFG->prefix}course t
2319 ON c.instanceid = t.id
2320 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_COURSE . "
2321 UNION
2322 SELECT c.contextlevel,
2323 c.instanceid
2324 FROM {$CFG->prefix}context c
2325 LEFT OUTER JOIN {$CFG->prefix}course_modules t
2326 ON c.instanceid = t.id
2327 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_MODULE . "
2328 UNION
2329 SELECT c.contextlevel,
2330 c.instanceid
2331 FROM {$CFG->prefix}context c
2332 LEFT OUTER JOIN {$CFG->prefix}user t
2333 ON c.instanceid = t.id
2334 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_USER . "
2335 UNION
2336 SELECT c.contextlevel,
2337 c.instanceid
2338 FROM {$CFG->prefix}context c
2339 LEFT OUTER JOIN {$CFG->prefix}block_instance t
2340 ON c.instanceid = t.id
2341 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_BLOCK . "
2342 UNION
2343 SELECT c.contextlevel,
2344 c.instanceid
2345 FROM {$CFG->prefix}context c
2346 LEFT OUTER JOIN {$CFG->prefix}groups t
2347 ON c.instanceid = t.id
2348 WHERE t.id IS NULL AND c.contextlevel = " . CONTEXT_GROUP . "
2350 if ($rs = get_recordset_sql($sql)) {
2351 begin_sql();
2352 $tx = true;
2353 while ($tx && $ctx = rs_fetch_next_record($rs)) {
2354 $tx = $tx && delete_context($ctx->contextlevel, $ctx->instanceid);
2356 rs_close($rs);
2357 if ($tx) {
2358 commit_sql();
2359 return true;
2361 rollback_sql();
2362 return false;
2363 rs_close($rs);
2365 return true;
2369 * Get the context instance as an object. This function will create the
2370 * context instance if it does not exist yet.
2371 * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2372 * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
2373 * for $level = CONTEXT_MODULE, this would be $cm->id. And so on.
2374 * @return object The context object.
2376 function get_context_instance($contextlevel, $instance=0) {
2378 global $context_cache, $context_cache_id, $CFG;
2379 static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_GROUP, CONTEXT_MODULE, CONTEXT_BLOCK);
2381 if ($contextlevel === 'clearcache') {
2382 // TODO: Remove for v2.0
2383 // No longer needed, but we'll catch it to avoid erroring out on custom code.
2384 // This used to be a fix for MDL-9016
2385 // "Restoring into existing course, deleting first
2386 // deletes context and doesn't recreate it"
2387 return false;
2390 /// System context has special cache
2391 if ($contextlevel == CONTEXT_SYSTEM) {
2392 return get_system_context();
2395 /// check allowed context levels
2396 if (!in_array($contextlevel, $allowed_contexts)) {
2397 // fatal error, code must be fixed - probably typo or switched parameters
2398 error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
2401 if (!is_array($instance)) {
2402 /// Check the cache
2403 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2404 return $context_cache[$contextlevel][$instance];
2407 /// Get it from the database, or create it
2408 if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
2409 $context = create_context($contextlevel, $instance);
2412 /// Only add to cache if context isn't empty.
2413 if (!empty($context)) {
2414 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
2415 $context_cache_id[$context->id] = $context; // Cache it for later
2418 return $context;
2422 /// ok, somebody wants to load several contexts to save some db queries ;-)
2423 $instances = $instance;
2424 $result = array();
2426 foreach ($instances as $key=>$instance) {
2427 /// Check the cache first
2428 if (isset($context_cache[$contextlevel][$instance])) { // Already cached
2429 $result[$instance] = $context_cache[$contextlevel][$instance];
2430 unset($instances[$key]);
2431 continue;
2435 if ($instances) {
2436 if (count($instances) > 1) {
2437 $instanceids = implode(',', $instances);
2438 $instanceids = "instanceid IN ($instanceids)";
2439 } else {
2440 $instance = reset($instances);
2441 $instanceids = "instanceid = $instance";
2444 if (!$contexts = get_records_sql("SELECT instanceid, id, contextlevel, path, depth
2445 FROM {$CFG->prefix}context
2446 WHERE contextlevel=$contextlevel AND $instanceids")) {
2447 $contexts = array();
2450 foreach ($instances as $instance) {
2451 if (isset($contexts[$instance])) {
2452 $context = $contexts[$instance];
2453 } else {
2454 $context = create_context($contextlevel, $instance);
2457 if (!empty($context)) {
2458 $context_cache[$contextlevel][$instance] = $context; // Cache it for later
2459 $context_cache_id[$context->id] = $context; // Cache it for later
2462 $result[$instance] = $context;
2466 return $result;
2471 * Get a context instance as an object, from a given context id.
2472 * @param mixed $id a context id or array of ids.
2473 * @return mixed object or array of the context object.
2475 function get_context_instance_by_id($id) {
2477 global $context_cache, $context_cache_id;
2479 if ($id == SYSCONTEXTID) {
2480 return get_system_context();
2483 if (isset($context_cache_id[$id])) { // Already cached
2484 return $context_cache_id[$id];
2487 if ($context = get_record('context', 'id', $id)) { // Update the cache and return
2488 $context_cache[$context->contextlevel][$context->instanceid] = $context;
2489 $context_cache_id[$context->id] = $context;
2490 return $context;
2493 return false;
2498 * Get the local override (if any) for a given capability in a role in a context
2499 * @param $roleid
2500 * @param $contextid
2501 * @param $capability
2503 function get_local_override($roleid, $contextid, $capability) {
2504 return get_record('role_capabilities', 'roleid', $roleid, 'capability', $capability, 'contextid', $contextid);
2509 /************************************
2510 * DB TABLE RELATED FUNCTIONS *
2511 ************************************/
2514 * function that creates a role
2515 * @param name - role name
2516 * @param shortname - role short name
2517 * @param description - role description
2518 * @param legacy - optional legacy capability
2519 * @return id or false
2521 function create_role($name, $shortname, $description, $legacy='') {
2523 // check for duplicate role name
2525 if ($role = get_record('role','name', $name)) {
2526 error('there is already a role with this name!');
2529 if ($role = get_record('role','shortname', $shortname)) {
2530 error('there is already a role with this shortname!');
2533 $role = new object();
2534 $role->name = $name;
2535 $role->shortname = $shortname;
2536 $role->description = $description;
2538 //find free sortorder number
2539 $role->sortorder = count_records('role');
2540 while (get_record('role','sortorder', $role->sortorder)) {
2541 $role->sortorder += 1;
2544 if (!$context = get_context_instance(CONTEXT_SYSTEM)) {
2545 return false;
2548 if ($id = insert_record('role', $role)) {
2549 if ($legacy) {
2550 assign_capability($legacy, CAP_ALLOW, $id, $context->id);
2553 /// By default, users with role:manage at site level
2554 /// should be able to assign users to this new role, and override this new role's capabilities
2556 // find all admin roles
2557 if ($adminroles = get_roles_with_capability('moodle/role:manage', CAP_ALLOW, $context)) {
2558 // foreach admin role
2559 foreach ($adminroles as $arole) {
2560 // write allow_assign and allow_overrid
2561 allow_assign($arole->id, $id);
2562 allow_override($arole->id, $id);
2566 return $id;
2567 } else {
2568 return false;
2574 * function that deletes a role and cleanups up after it
2575 * @param roleid - id of role to delete
2576 * @return success
2578 function delete_role($roleid) {
2579 global $CFG;
2580 $success = true;
2582 // mdl 10149, check if this is the last active admin role
2583 // if we make the admin role not deletable then this part can go
2585 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
2587 if ($role = get_record('role', 'id', $roleid)) {
2588 if (record_exists('role_capabilities', 'contextid', $systemcontext->id, 'roleid', $roleid, 'capability', 'moodle/site:doanything')) {
2589 // deleting an admin role
2590 $status = false;
2591 if ($adminroles = get_roles_with_capability('moodle/site:doanything', CAP_ALLOW, $systemcontext)) {
2592 foreach ($adminroles as $adminrole) {
2593 if ($adminrole->id != $roleid) {
2594 // some other admin role
2595 if (record_exists('role_assignments', 'roleid', $adminrole->id, 'contextid', $systemcontext->id)) {
2596 // found another admin role with at least 1 user assigned
2597 $status = true;
2598 break;
2603 if ($status !== true) {
2604 error ('You can not delete this role because there is no other admin roles with users assigned');
2609 // first unssign all users
2610 if (!role_unassign($roleid)) {
2611 debugging("Error while unassigning all users from role with ID $roleid!");
2612 $success = false;
2615 // cleanup all references to this role, ignore errors
2616 if ($success) {
2618 // MDL-10679 find all contexts where this role has an override
2619 $contexts = get_records_sql("SELECT contextid, contextid
2620 FROM {$CFG->prefix}role_capabilities
2621 WHERE roleid = $roleid");
2623 delete_records('role_capabilities', 'roleid', $roleid);
2625 delete_records('role_allow_assign', 'roleid', $roleid);
2626 delete_records('role_allow_assign', 'allowassign', $roleid);
2627 delete_records('role_allow_override', 'roleid', $roleid);
2628 delete_records('role_allow_override', 'allowoverride', $roleid);
2629 delete_records('role_names', 'roleid', $roleid);
2632 // finally delete the role itself
2633 // get this before the name is gone for logging
2634 $rolename = get_field('role', 'name', 'id', $roleid);
2636 if ($success and !delete_records('role', 'id', $roleid)) {
2637 debugging("Could not delete role record with ID $roleid!");
2638 $success = false;
2641 if ($success) {
2642 add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '', $USER->id);
2645 return $success;
2649 * Function to write context specific overrides, or default capabilities.
2650 * @param module - string name
2651 * @param capability - string name
2652 * @param contextid - context id
2653 * @param roleid - role id
2654 * @param permission - int 1,-1 or -1000
2655 * should not be writing if permission is 0
2657 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2659 global $USER;
2661 if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
2662 unassign_capability($capability, $roleid, $contextid);
2663 return true;
2666 $existing = get_record('role_capabilities', 'contextid', $contextid, 'roleid', $roleid, 'capability', $capability);
2668 if ($existing and !$overwrite) { // We want to keep whatever is there already
2669 return true;
2672 $cap = new object;
2673 $cap->contextid = $contextid;
2674 $cap->roleid = $roleid;
2675 $cap->capability = $capability;
2676 $cap->permission = $permission;
2677 $cap->timemodified = time();
2678 $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
2680 if ($existing) {
2681 $cap->id = $existing->id;
2682 return update_record('role_capabilities', $cap);
2683 } else {
2684 $c = get_record('context', 'id', $contextid);
2685 return insert_record('role_capabilities', $cap);
2690 * Unassign a capability from a role.
2691 * @param $roleid - the role id
2692 * @param $capability - the name of the capability
2693 * @return boolean - success or failure
2695 function unassign_capability($capability, $roleid, $contextid=NULL) {
2697 if (isset($contextid)) {
2698 // delete from context rel, if this is the last override in this context
2699 $status = delete_records('role_capabilities', 'capability', $capability,
2700 'roleid', $roleid, 'contextid', $contextid);
2701 } else {
2702 $status = delete_records('role_capabilities', 'capability', $capability,
2703 'roleid', $roleid);
2705 return $status;
2710 * Get the roles that have a given capability assigned to it. This function
2711 * does not resolve the actual permission of the capability. It just checks
2712 * for assignment only.
2713 * @param $capability - capability name (string)
2714 * @param $permission - optional, the permission defined for this capability
2715 * either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT
2716 * @return array or role objects
2718 function get_roles_with_capability($capability, $permission=NULL, $context='') {
2720 global $CFG;
2722 if ($context) {
2723 if ($contexts = get_parent_contexts($context)) {
2724 $listofcontexts = '('.implode(',', $contexts).')';
2725 } else {
2726 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
2727 $listofcontexts = '('.$sitecontext->id.')'; // must be site
2729 $contextstr = "AND (rc.contextid = '$context->id' OR rc.contextid IN $listofcontexts)";
2730 } else {
2731 $contextstr = '';
2734 $selectroles = "SELECT r.*
2735 FROM {$CFG->prefix}role r,
2736 {$CFG->prefix}role_capabilities rc
2737 WHERE rc.capability = '$capability'
2738 AND rc.roleid = r.id $contextstr";
2740 if (isset($permission)) {
2741 $selectroles .= " AND rc.permission = '$permission'";
2743 return get_records_sql($selectroles);
2748 * This function makes a role-assignment (a role for a user or group in a particular context)
2749 * @param $roleid - the role of the id
2750 * @param $userid - userid
2751 * @param $groupid - group id
2752 * @param $contextid - id of the context
2753 * @param $timestart - time this assignment becomes effective
2754 * @param $timeend - time this assignemnt ceases to be effective
2755 * @uses $USER
2756 * @return id - new id of the assigment
2758 function role_assign($roleid, $userid, $groupid, $contextid, $timestart=0, $timeend=0, $hidden=0, $enrol='manual',$timemodified='') {
2759 global $USER, $CFG;
2761 /// Do some data validation
2763 if (empty($roleid)) {
2764 debugging('Role ID not provided');
2765 return false;
2768 if (empty($userid) && empty($groupid)) {
2769 debugging('Either userid or groupid must be provided');
2770 return false;
2773 if ($userid && !record_exists('user', 'id', $userid)) {
2774 debugging('User ID '.intval($userid).' does not exist!');
2775 return false;
2778 if ($groupid && !groups_group_exists($groupid)) {
2779 debugging('Group ID '.intval($groupid).' does not exist!');
2780 return false;
2783 if (!$context = get_context_instance_by_id($contextid)) {
2784 debugging('Context ID '.intval($contextid).' does not exist!');
2785 return false;
2788 if (($timestart and $timeend) and ($timestart > $timeend)) {
2789 debugging('The end time can not be earlier than the start time');
2790 return false;
2793 if (!$timemodified) {
2794 $timemodified = time();
2797 /// Check for existing entry
2798 if ($userid) {
2799 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'userid', $userid);
2800 } else {
2801 $ra = get_record('role_assignments', 'roleid', $roleid, 'contextid', $context->id, 'groupid', $groupid);
2804 if (empty($ra)) { // Create a new entry
2805 $ra = new object();
2806 $ra->roleid = $roleid;
2807 $ra->contextid = $context->id;
2808 $ra->userid = $userid;
2809 $ra->hidden = $hidden;
2810 $ra->enrol = $enrol;
2811 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2812 /// by repeating queries with the same exact parameters in a 100 secs time window
2813 $ra->timestart = round($timestart, -2);
2814 $ra->timeend = $timeend;
2815 $ra->timemodified = $timemodified;
2816 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
2818 if (!$ra->id = insert_record('role_assignments', $ra)) {
2819 return false;
2822 } else { // We already have one, just update it
2823 $ra->id = $ra->id;
2824 $ra->hidden = $hidden;
2825 $ra->enrol = $enrol;
2826 /// Always round timestart downto 100 secs to help DBs to use their own caching algorithms
2827 /// by repeating queries with the same exact parameters in a 100 secs time window
2828 $ra->timestart = round($timestart, -2);
2829 $ra->timeend = $timeend;
2830 $ra->timemodified = $timemodified;
2831 $ra->modifierid = empty($USER->id) ? 0 : $USER->id;
2833 if (!update_record('role_assignments', $ra)) {
2834 return false;
2838 /// mark context as dirty - modules might use has_capability() in xxx_role_assing()
2839 /// again expensive, but needed
2840 mark_context_dirty($context->path);
2842 if (!empty($USER->id) && $USER->id == $userid) {
2843 /// If the user is the current user, then do full reload of capabilities too.
2844 load_all_capabilities();
2847 /// Ask all the modules if anything needs to be done for this user
2848 if ($mods = get_list_of_plugins('mod')) {
2849 foreach ($mods as $mod) {
2850 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2851 $functionname = $mod.'_role_assign';
2852 if (function_exists($functionname)) {
2853 $functionname($userid, $context, $roleid);
2858 /// now handle metacourse role assignments if in course context
2859 if ($context->contextlevel == CONTEXT_COURSE) {
2860 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2861 foreach ($parents as $parent) {
2862 sync_metacourse($parent->parent_course);
2867 events_trigger('role_assigned', $ra);
2869 return true;
2874 * Deletes one or more role assignments. You must specify at least one parameter.
2875 * @param $roleid
2876 * @param $userid
2877 * @param $groupid
2878 * @param $contextid
2879 * @param $enrol unassign only if enrolment type matches, NULL means anything
2880 * @return boolean - success or failure
2882 function role_unassign($roleid=0, $userid=0, $groupid=0, $contextid=0, $enrol=NULL) {
2883 global $USER, $CFG;
2884 require_once($CFG->dirroot.'/group/lib.php');
2886 $success = true;
2888 $args = array('roleid', 'userid', 'groupid', 'contextid');
2889 $select = array();
2890 foreach ($args as $arg) {
2891 if ($$arg) {
2892 $select[] = $arg.' = '.$$arg;
2895 if (!empty($enrol)) {
2896 $select[] = "enrol='$enrol'";
2899 if ($select) {
2900 if ($ras = get_records_select('role_assignments', implode(' AND ', $select))) {
2901 $mods = get_list_of_plugins('mod');
2902 foreach($ras as $ra) {
2903 $fireevent = false;
2904 /// infinite loop protection when deleting recursively
2905 if (!$ra = get_record('role_assignments', 'id', $ra->id)) {
2906 continue;
2908 if (delete_records('role_assignments', 'id', $ra->id)) {
2909 $fireevent = true;
2910 } else {
2911 $success = false;
2914 if (!$context = get_context_instance_by_id($ra->contextid)) {
2915 // strange error, not much to do
2916 continue;
2919 /* mark contexts as dirty here, because we need the refreshed
2920 * caps bellow to delete group membership and user_lastaccess!
2921 * and yes, this is very expensive for bulk operations :-(
2923 mark_context_dirty($context->path);
2925 /// If the user is the current user, then do full reload of capabilities too.
2926 if (!empty($USER->id) && $USER->id == $ra->userid) {
2927 load_all_capabilities();
2930 /// Ask all the modules if anything needs to be done for this user
2931 foreach ($mods as $mod) {
2932 include_once($CFG->dirroot.'/mod/'.$mod.'/lib.php');
2933 $functionname = $mod.'_role_unassign';
2934 if (function_exists($functionname)) {
2935 $functionname($ra->userid, $context); // watch out, $context might be NULL if something goes wrong
2939 /// now handle metacourse role unassigment and removing from goups if in course context
2940 if ($context->contextlevel == CONTEXT_COURSE) {
2942 // cleanup leftover course groups/subscriptions etc when user has
2943 // no capability to view course
2944 // this may be slow, but this is the proper way of doing it
2945 if (!has_capability('moodle/course:view', $context, $ra->userid)) {
2946 // remove from groups
2947 groups_delete_group_members($context->instanceid, $ra->userid);
2949 // delete lastaccess records
2950 delete_records('user_lastaccess', 'userid', $ra->userid, 'courseid', $context->instanceid);
2953 //unassign roles in metacourses if needed
2954 if ($parents = get_records('course_meta', 'child_course', $context->instanceid)) {
2955 foreach ($parents as $parent) {
2956 sync_metacourse($parent->parent_course);
2961 if ($fireevent) {
2962 events_trigger('role_unassigned', $ra);
2968 return $success;
2972 * A convenience function to take care of the common case where you
2973 * just want to enrol someone using the default role into a course
2975 * @param object $course
2976 * @param object $user
2977 * @param string $enrol - the plugin used to do this enrolment
2979 function enrol_into_course($course, $user, $enrol) {
2981 $timestart = time();
2982 // remove time part from the timestamp and keep only the date part
2983 $timestart = make_timestamp(date('Y', $timestart), date('m', $timestart), date('d', $timestart), 0, 0, 0);
2984 if ($course->enrolperiod) {
2985 $timeend = $timestart + $course->enrolperiod;
2986 } else {
2987 $timeend = 0;
2990 if ($role = get_default_course_role($course)) {
2992 $context = get_context_instance(CONTEXT_COURSE, $course->id);
2994 if (!role_assign($role->id, $user->id, 0, $context->id, $timestart, $timeend, 0, $enrol)) {
2995 return false;
2998 // force accessdata refresh for users visiting this context...
2999 mark_context_dirty($context->path);
3001 email_welcome_message_to_user($course, $user);
3003 add_to_log($course->id, 'course', 'enrol',
3004 'view.php?id='.$course->id, $course->id);
3006 return true;
3009 return false;
3013 * Loads the capability definitions for the component (from file). If no
3014 * capabilities are defined for the component, we simply return an empty array.
3015 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3016 * @return array of capabilities
3018 function load_capability_def($component) {
3019 global $CFG;
3021 if ($component == 'moodle') {
3022 $defpath = $CFG->libdir.'/db/access.php';
3023 $varprefix = 'moodle';
3024 } else {
3025 $compparts = explode('/', $component);
3027 if ($compparts[0] == 'block') {
3028 // Blocks are an exception. Blocks directory is 'blocks', and not
3029 // 'block'. So we need to jump through hoops.
3030 $defpath = $CFG->dirroot.'/'.$compparts[0].
3031 's/'.$compparts[1].'/db/access.php';
3032 $varprefix = $compparts[0].'_'.$compparts[1];
3034 } else if ($compparts[0] == 'format') {
3035 // Similar to the above, course formats are 'format' while they
3036 // are stored in 'course/format'.
3037 $defpath = $CFG->dirroot.'/course/'.$component.'/db/access.php';
3038 $varprefix = $compparts[0].'_'.$compparts[1];
3040 } else if ($compparts[0] == 'gradeimport') {
3041 $defpath = $CFG->dirroot.'/grade/import/'.$compparts[1].'/db/access.php';
3042 $varprefix = $compparts[0].'_'.$compparts[1];
3044 } else if ($compparts[0] == 'gradeexport') {
3045 $defpath = $CFG->dirroot.'/grade/export/'.$compparts[1].'/db/access.php';
3046 $varprefix = $compparts[0].'_'.$compparts[1];
3048 } else if ($compparts[0] == 'gradereport') {
3049 $defpath = $CFG->dirroot.'/grade/report/'.$compparts[1].'/db/access.php';
3050 $varprefix = $compparts[0].'_'.$compparts[1];
3052 } else {
3053 $defpath = $CFG->dirroot.'/'.$component.'/db/access.php';
3054 $varprefix = str_replace('/', '_', $component);
3057 $capabilities = array();
3059 if (file_exists($defpath)) {
3060 require($defpath);
3061 $capabilities = ${$varprefix.'_capabilities'};
3063 return $capabilities;
3068 * Gets the capabilities that have been cached in the database for this
3069 * component.
3070 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3071 * @return array of capabilities
3073 function get_cached_capabilities($component='moodle') {
3074 if ($component == 'moodle') {
3075 $storedcaps = get_records_select('capabilities',
3076 "name LIKE 'moodle/%:%'");
3077 } else if ($component == 'local') {
3078 $storedcaps = get_records_select('capabilities',
3079 "name LIKE 'moodle/local:%'");
3080 } else {
3081 $storedcaps = get_records_select('capabilities',
3082 "name LIKE '$component:%'");
3084 return $storedcaps;
3088 * Returns default capabilities for given legacy role type.
3090 * @param string legacy role name
3091 * @return array
3093 function get_default_capabilities($legacyrole) {
3094 if (!$allcaps = get_records('capabilities')) {
3095 error('Error: no capabilitites defined!');
3097 $alldefs = array();
3098 $defaults = array();
3099 $components = array();
3100 foreach ($allcaps as $cap) {
3101 if (!in_array($cap->component, $components)) {
3102 $components[] = $cap->component;
3103 $alldefs = array_merge($alldefs, load_capability_def($cap->component));
3106 foreach($alldefs as $name=>$def) {
3107 if (isset($def['legacy'][$legacyrole])) {
3108 $defaults[$name] = $def['legacy'][$legacyrole];
3112 //some exceptions
3113 $defaults['moodle/legacy:'.$legacyrole] = CAP_ALLOW;
3114 if ($legacyrole == 'admin') {
3115 $defaults['moodle/site:doanything'] = CAP_ALLOW;
3117 return $defaults;
3121 * Reset role capabilitites to default according to selected legacy capability.
3122 * If several legacy caps selected, use the first from get_default_capabilities.
3123 * If no legacy selected, removes all capabilities.
3125 * @param int @roleid
3127 function reset_role_capabilities($roleid) {
3128 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
3129 $legacyroles = get_legacy_roles();
3131 $defaultcaps = array();
3132 foreach($legacyroles as $ltype=>$lcap) {
3133 $localoverride = get_local_override($roleid, $sitecontext->id, $lcap);
3134 if (!empty($localoverride->permission) and $localoverride->permission == CAP_ALLOW) {
3135 //choose first selected legacy capability
3136 $defaultcaps = get_default_capabilities($ltype);
3137 break;
3141 delete_records('role_capabilities', 'roleid', $roleid);
3142 if (!empty($defaultcaps)) {
3143 foreach($defaultcaps as $cap=>$permission) {
3144 assign_capability($cap, $permission, $roleid, $sitecontext->id);
3150 * Updates the capabilities table with the component capability definitions.
3151 * If no parameters are given, the function updates the core moodle
3152 * capabilities.
3154 * Note that the absence of the db/access.php capabilities definition file
3155 * will cause any stored capabilities for the component to be removed from
3156 * the database.
3158 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3159 * @return boolean
3161 function update_capabilities($component='moodle') {
3163 $storedcaps = array();
3165 $filecaps = load_capability_def($component);
3166 $cachedcaps = get_cached_capabilities($component);
3167 if ($cachedcaps) {
3168 foreach ($cachedcaps as $cachedcap) {
3169 array_push($storedcaps, $cachedcap->name);
3170 // update risk bitmasks and context levels in existing capabilities if needed
3171 if (array_key_exists($cachedcap->name, $filecaps)) {
3172 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
3173 $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
3175 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
3176 $updatecap = new object();
3177 $updatecap->id = $cachedcap->id;
3178 $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
3179 if (!update_record('capabilities', $updatecap)) {
3180 return false;
3184 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
3185 $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
3187 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
3188 $updatecap = new object();
3189 $updatecap->id = $cachedcap->id;
3190 $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
3191 if (!update_record('capabilities', $updatecap)) {
3192 return false;
3199 // Are there new capabilities in the file definition?
3200 $newcaps = array();
3202 foreach ($filecaps as $filecap => $def) {
3203 if (!$storedcaps ||
3204 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
3205 if (!array_key_exists('riskbitmask', $def)) {
3206 $def['riskbitmask'] = 0; // no risk if not specified
3208 $newcaps[$filecap] = $def;
3211 // Add new capabilities to the stored definition.
3212 foreach ($newcaps as $capname => $capdef) {
3213 $capability = new object;
3214 $capability->name = $capname;
3215 $capability->captype = $capdef['captype'];
3216 $capability->contextlevel = $capdef['contextlevel'];
3217 $capability->component = $component;
3218 $capability->riskbitmask = $capdef['riskbitmask'];
3220 if (!insert_record('capabilities', $capability, false, 'id')) {
3221 return false;
3225 if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
3226 if ($rolecapabilities = get_records('role_capabilities', 'capability', $capdef['clonepermissionsfrom'])){
3227 foreach ($rolecapabilities as $rolecapability){
3228 //assign_capability will update rather than insert if capability exists
3229 if (!assign_capability($capname, $rolecapability->permission,
3230 $rolecapability->roleid, $rolecapability->contextid, true)){
3231 notify('Could not clone capabilities for '.$capname);
3235 // Do we need to assign the new capabilities to roles that have the
3236 // legacy capabilities moodle/legacy:* as well?
3237 // we ignore legacy key if we have cloned permissions
3238 } else if (isset($capdef['legacy']) && is_array($capdef['legacy']) &&
3239 !assign_legacy_capabilities($capname, $capdef['legacy'])) {
3240 notify('Could not assign legacy capabilities for '.$capname);
3243 // Are there any capabilities that have been removed from the file
3244 // definition that we need to delete from the stored capabilities and
3245 // role assignments?
3246 capabilities_cleanup($component, $filecaps);
3248 return true;
3253 * Deletes cached capabilities that are no longer needed by the component.
3254 * Also unassigns these capabilities from any roles that have them.
3255 * @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
3256 * @param $newcapdef - array of the new capability definitions that will be
3257 * compared with the cached capabilities
3258 * @return int - number of deprecated capabilities that have been removed
3260 function capabilities_cleanup($component, $newcapdef=NULL) {
3262 $removedcount = 0;
3264 if ($cachedcaps = get_cached_capabilities($component)) {
3265 foreach ($cachedcaps as $cachedcap) {
3266 if (empty($newcapdef) ||
3267 array_key_exists($cachedcap->name, $newcapdef) === false) {
3269 // Remove from capabilities cache.
3270 if (!delete_records('capabilities', 'name', $cachedcap->name)) {
3271 error('Could not delete deprecated capability '.$cachedcap->name);
3272 } else {
3273 $removedcount++;
3275 // Delete from roles.
3276 if($roles = get_roles_with_capability($cachedcap->name)) {
3277 foreach($roles as $role) {
3278 if (!unassign_capability($cachedcap->name, $role->id)) {
3279 error('Could not unassign deprecated capability '.
3280 $cachedcap->name.' from role '.$role->name);
3284 } // End if.
3287 return $removedcount;
3292 /****************
3293 * UI FUNCTIONS *
3294 ****************/
3298 * prints human readable context identifier.
3300 function print_context_name($context, $withprefix = true, $short = false) {
3302 $name = '';
3303 switch ($context->contextlevel) {
3305 case CONTEXT_SYSTEM: // by now it's a definite an inherit
3306 $name = get_string('coresystem');
3307 break;
3309 case CONTEXT_USER:
3310 if ($user = get_record('user', 'id', $context->instanceid)) {
3311 if ($withprefix){
3312 $name = get_string('user').': ';
3314 $name .= fullname($user);
3316 break;
3318 case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
3319 if ($category = get_record('course_categories', 'id', $context->instanceid)) {
3320 if ($withprefix){
3321 $name = get_string('category').': ';
3323 $name .=format_string($category->name);
3325 break;
3327 case CONTEXT_COURSE: // 1 to 1 to course cat
3328 if ($course = get_record('course', 'id', $context->instanceid)) {
3329 if ($withprefix){
3330 if ($context->instanceid == SITEID) {
3331 $name = get_string('site').': ';
3332 } else {
3333 $name = get_string('course').': ';
3336 if ($short){
3337 $name .=format_string($course->shortname);
3338 } else {
3339 $name .=format_string($course->fullname);
3343 break;
3345 case CONTEXT_GROUP: // 1 to 1 to course
3346 if ($name = groups_get_group_name($context->instanceid)) {
3347 if ($withprefix){
3348 $name = get_string('group').': '. $name;
3351 break;
3353 case CONTEXT_MODULE: // 1 to 1 to course
3354 if ($cm = get_record('course_modules','id',$context->instanceid)) {
3355 if ($module = get_record('modules','id',$cm->module)) {
3356 if ($mod = get_record($module->name, 'id', $cm->instance)) {
3357 if ($withprefix){
3358 $name = get_string('activitymodule').': ';
3360 $name .= $mod->name;
3364 break;
3366 case CONTEXT_BLOCK: // not necessarily 1 to 1 to course
3367 if ($blockinstance = get_record('block_instance','id',$context->instanceid)) {
3368 if ($block = get_record('block','id',$blockinstance->blockid)) {
3369 global $CFG;
3370 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
3371 require_once("$CFG->dirroot/blocks/$block->name/block_$block->name.php");
3372 $blockname = "block_$block->name";
3373 if ($blockobject = new $blockname()) {
3374 if ($withprefix){
3375 $name = get_string('block').': ';
3377 $name .= $blockobject->title;
3381 break;
3383 default:
3384 error ('This is an unknown context (' . $context->contextlevel . ') in print_context_name!');
3385 return false;
3388 return $name;
3393 * Extracts the relevant capabilities given a contextid.
3394 * All case based, example an instance of forum context.
3395 * Will fetch all forum related capabilities, while course contexts
3396 * Will fetch all capabilities
3397 * @param object context
3398 * @return array();
3400 * capabilities
3401 * `name` varchar(150) NOT NULL,
3402 * `captype` varchar(50) NOT NULL,
3403 * `contextlevel` int(10) NOT NULL,
3404 * `component` varchar(100) NOT NULL,
3406 function fetch_context_capabilities($context) {
3408 global $CFG;
3410 $sort = 'ORDER BY contextlevel,component,name'; // To group them sensibly for display
3412 switch ($context->contextlevel) {
3414 case CONTEXT_SYSTEM: // all
3415 $SQL = "SELECT *
3416 FROM {$CFG->prefix}capabilities";
3417 break;
3419 case CONTEXT_USER:
3420 $extracaps = array('moodle/grade:viewall');
3421 foreach ($extracaps as $key=>$value) {
3422 $extracaps[$key]= "'$value'";
3424 $extra = implode(',', $extracaps);
3425 $SQL = "SELECT *
3426 FROM {$CFG->prefix}capabilities
3427 WHERE contextlevel = ".CONTEXT_USER."
3428 OR name IN ($extra)";
3429 break;
3431 case CONTEXT_COURSECAT: // course category context and bellow
3432 $SQL = "SELECT *
3433 FROM {$CFG->prefix}capabilities
3434 WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
3435 break;
3437 case CONTEXT_COURSE: // course context and bellow
3438 $SQL = "SELECT *
3439 FROM {$CFG->prefix}capabilities
3440 WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
3441 break;
3443 case CONTEXT_MODULE: // mod caps
3444 $cm = get_record('course_modules', 'id', $context->instanceid);
3445 $module = get_record('modules', 'id', $cm->module);
3447 $extra = "";
3448 $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
3449 if (file_exists($modfile)) {
3450 include_once($modfile);
3451 $modfunction = $module->name.'_get_extra_capabilities';
3452 if (function_exists($modfunction)) {
3453 if ($extracaps = $modfunction()) {
3454 foreach ($extracaps as $key=>$value) {
3455 $extracaps[$key]= "'$value'";
3457 $extra = implode(',', $extracaps);
3458 $extra = "OR name IN ($extra)";
3463 $SQL = "SELECT *
3464 FROM {$CFG->prefix}capabilities
3465 WHERE (contextlevel = ".CONTEXT_MODULE."
3466 AND component = 'mod/$module->name')
3467 $extra";
3468 break;
3470 case CONTEXT_BLOCK: // block caps
3471 $cb = get_record('block_instance', 'id', $context->instanceid);
3472 $block = get_record('block', 'id', $cb->blockid);
3474 $extra = "";
3475 if ($blockinstance = block_instance($block->name)) {
3476 if ($extracaps = $blockinstance->get_extra_capabilities()) {
3477 foreach ($extracaps as $key=>$value) {
3478 $extracaps[$key]= "'$value'";
3480 $extra = implode(',', $extracaps);
3481 $extra = "OR name IN ($extra)";
3485 $SQL = "SELECT *
3486 FROM {$CFG->prefix}capabilities
3487 WHERE (contextlevel = ".CONTEXT_BLOCK."
3488 AND component = 'block/$block->name')
3489 $extra";
3490 break;
3492 default:
3493 return false;
3496 if (!$records = get_records_sql($SQL.' '.$sort)) {
3497 $records = array();
3500 return $records;
3505 * This function pulls out all the resolved capabilities (overrides and
3506 * defaults) of a role used in capability overrides in contexts at a given
3507 * context.
3508 * @param obj $context
3509 * @param int $roleid
3510 * @param bool self - if set to true, resolve till this level, else stop at immediate parent level
3511 * @return array
3513 function role_context_capabilities($roleid, $context, $cap='') {
3514 global $CFG;
3516 $contexts = get_parent_contexts($context);
3517 $contexts[] = $context->id;
3518 $contexts = '('.implode(',', $contexts).')';
3520 if ($cap) {
3521 $search = " AND rc.capability = '$cap' ";
3522 } else {
3523 $search = '';
3526 $SQL = "SELECT rc.*
3527 FROM {$CFG->prefix}role_capabilities rc,
3528 {$CFG->prefix}context c
3529 WHERE rc.contextid in $contexts
3530 AND rc.roleid = $roleid
3531 AND rc.contextid = c.id $search
3532 ORDER BY c.contextlevel DESC,
3533 rc.capability DESC";
3535 $capabilities = array();
3537 if ($records = get_records_sql($SQL)) {
3538 // We are traversing via reverse order.
3539 foreach ($records as $record) {
3540 // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3541 if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
3542 $capabilities[$record->capability] = $record->permission;
3546 return $capabilities;
3550 * Recursive function which, given a context, find all parent context ids,
3551 * and return the array in reverse order, i.e. parent first, then grand
3552 * parent, etc.
3554 * @param object $context
3555 * @return array()
3557 function get_parent_contexts($context) {
3559 if ($context->path == '') {
3560 return array();
3563 $parentcontexts = substr($context->path, 1); // kill leading slash
3564 $parentcontexts = explode('/', $parentcontexts);
3565 array_pop($parentcontexts); // and remove its own id
3567 return array_reverse($parentcontexts);
3571 * Return the id of the parent of this context, or false if there is no parent (only happens if this
3572 * is the site context.)
3574 * @param object $context
3575 * @return integer the id of the parent context.
3577 function get_parent_contextid($context) {
3578 $parentcontexts = get_parent_contexts($context);
3579 if (count($parentcontexts) == 0) {
3580 return false;
3582 return array_shift($parentcontexts);
3586 * Recursive function which, given a context, find all its children context ids.
3588 * When called for a course context, it will return the modules and blocks
3589 * displayed in the course page.
3591 * For course category contexts it will return categories and courses. It will
3592 * NOT recurse into courses - if you want to do that, call it on the returned
3593 * courses.
3595 * If called on a course context it _will_ populate the cache with the appropriate
3596 * contexts ;-)
3598 * @param object $context.
3599 * @return array of child records
3601 function get_child_contexts($context) {
3603 global $CFG, $context_cache;
3605 // We *MUST* populate the context_cache as the callers
3606 // will probably ask for the full record anyway soon after
3607 // soon after calling us ;-)
3609 switch ($context->contextlevel) {
3611 case CONTEXT_BLOCK:
3612 // No children.
3613 return array();
3614 break;
3616 case CONTEXT_MODULE:
3617 // No children.
3618 return array();
3619 break;
3621 case CONTEXT_GROUP:
3622 // No children.
3623 return array();
3624 break;
3626 case CONTEXT_COURSE:
3627 // Find
3628 // - module instances - easy
3629 // - groups
3630 // - blocks assigned to the course-view page explicitly - easy
3631 // - blocks pinned (note! we get all of them here, regardless of vis)
3632 $sql = " SELECT ctx.*
3633 FROM {$CFG->prefix}context ctx
3634 WHERE ctx.path LIKE '{$context->path}/%'
3635 AND ctx.contextlevel IN (".CONTEXT_MODULE.",".CONTEXT_BLOCK.")
3636 UNION
3637 SELECT ctx.*
3638 FROM {$CFG->prefix}context ctx
3639 JOIN {$CFG->prefix}groups g
3640 ON (ctx.instanceid=g.id AND ctx.contextlevel=".CONTEXT_GROUP.")
3641 WHERE g.courseid={$context->instanceid}
3642 UNION
3643 SELECT ctx.*
3644 FROM {$CFG->prefix}context ctx
3645 JOIN {$CFG->prefix}block_pinned b
3646 ON (ctx.instanceid=b.blockid AND ctx.contextlevel=".CONTEXT_BLOCK.")
3647 WHERE b.pagetype='course-view'
3649 $rs = get_recordset_sql($sql);
3650 $records = array();
3651 while ($rec = rs_fetch_next_record($rs)) {
3652 $records[$rec->id] = $rec;
3653 $context_cache[$rec->contextlevel][$rec->instanceid] = $rec;
3655 rs_close($rs);
3656 return $records;
3657 break;
3659 case CONTEXT_COURSECAT:
3660 // Find
3661 // - categories
3662 // - courses
3663 $sql = " SELECT ctx.*
3664 FROM {$CFG->prefix}context ctx
3665 WHERE ctx.path LIKE '{$context->path}/%'
3666 AND ctx.contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.")
3668 $rs = get_recordset_sql($sql);
3669 $records = array();
3670 while ($rec = rs_fetch_next_record($rs)) {
3671 $records[$rec->id] = $rec;
3672 $context_cache[$rec->contextlevel][$rec->instanceid] = $rec;
3674 rs_close($rs);
3675 return $records;
3676 break;
3678 case CONTEXT_USER:
3679 // No children.
3680 return array();
3681 break;
3683 case CONTEXT_SYSTEM:
3684 // Just get all the contexts except for CONTEXT_SYSTEM level
3685 // and hope we don't OOM in the process - don't cache
3686 $sql = 'SELECT c.*'.
3687 'FROM '.$CFG->prefix.'context c '.
3688 'WHERE contextlevel != '.CONTEXT_SYSTEM;
3690 return get_records_sql($sql);
3691 break;
3693 default:
3694 error('This is an unknown context (' . $context->contextlevel . ') in get_child_contexts!');
3695 return false;
3701 * Gets a string for sql calls, searching for stuff in this context or above
3702 * @param object $context
3703 * @return string
3705 function get_related_contexts_string($context) {
3706 if ($parents = get_parent_contexts($context)) {
3707 return (' IN ('.$context->id.','.implode(',', $parents).')');
3708 } else {
3709 return (' ='.$context->id);
3714 * Returns the human-readable, translated version of the capability.
3715 * Basically a big switch statement.
3716 * @param $capabilityname - e.g. mod/choice:readresponses
3718 function get_capability_string($capabilityname) {
3720 // Typical capabilityname is mod/choice:readresponses
3722 $names = split('/', $capabilityname);
3723 $stringname = $names[1]; // choice:readresponses
3724 $components = split(':', $stringname);
3725 $componentname = $components[0]; // choice
3727 switch ($names[0]) {
3728 case 'mod':
3729 $string = get_string($stringname, $componentname);
3730 break;
3732 case 'block':
3733 $string = get_string($stringname, 'block_'.$componentname);
3734 break;
3736 case 'moodle':
3737 if ($componentname == 'local') {
3738 $string = get_string($stringname, 'local');
3739 } else {
3740 $string = get_string($stringname, 'role');
3742 break;
3744 case 'enrol':
3745 $string = get_string($stringname, 'enrol_'.$componentname);
3746 break;
3748 case 'format':
3749 $string = get_string($stringname, 'format_'.$componentname);
3750 break;
3752 case 'gradeexport':
3753 $string = get_string($stringname, 'gradeexport_'.$componentname);
3754 break;
3756 case 'gradeimport':
3757 $string = get_string($stringname, 'gradeimport_'.$componentname);
3758 break;
3760 case 'gradereport':
3761 $string = get_string($stringname, 'gradereport_'.$componentname);
3762 break;
3764 default:
3765 $string = get_string($stringname);
3766 break;
3769 return $string;
3774 * This gets the mod/block/course/core etc strings.
3775 * @param $component
3776 * @param $contextlevel
3778 function get_component_string($component, $contextlevel) {
3780 switch ($contextlevel) {
3782 case CONTEXT_SYSTEM:
3783 if (preg_match('|^enrol/|', $component)) {
3784 $langname = str_replace('/', '_', $component);
3785 $string = get_string('enrolname', $langname);
3786 } else if (preg_match('|^block/|', $component)) {
3787 $langname = str_replace('/', '_', $component);
3788 $string = get_string('blockname', $langname);
3789 } else if (preg_match('|^local|', $component)) {
3790 $langname = str_replace('/', '_', $component);
3791 $string = get_string('local');
3792 } else {
3793 $string = get_string('coresystem');
3795 break;
3797 case CONTEXT_USER:
3798 $string = get_string('users');
3799 break;
3801 case CONTEXT_COURSECAT:
3802 $string = get_string('categories');
3803 break;
3805 case CONTEXT_COURSE:
3806 if (preg_match('|^gradeimport/|', $component)
3807 || preg_match('|^gradeexport/|', $component)
3808 || preg_match('|^gradereport/|', $component)) {
3809 $string = get_string('gradebook', 'admin');
3810 } else {
3811 $string = get_string('course');
3813 break;
3815 case CONTEXT_GROUP:
3816 $string = get_string('group');
3817 break;
3819 case CONTEXT_MODULE:
3820 $string = get_string('modulename', basename($component));
3821 break;
3823 case CONTEXT_BLOCK:
3824 if( $component == 'moodle' ){
3825 $string = get_string('block');
3826 }else{
3827 $string = get_string('blockname', 'block_'.basename($component));
3829 break;
3831 default:
3832 error ('This is an unknown context $contextlevel (' . $contextlevel . ') in get_component_string!');
3833 return false;
3836 return $string;
3840 * Gets the list of roles assigned to this context and up (parents)
3841 * @param object $context
3842 * @param view - set to true when roles are pulled for display only
3843 * this is so that we can filter roles with no visible
3844 * assignment, for example, you might want to "hide" all
3845 * course creators when browsing the course participants
3846 * list.
3847 * @return array
3849 function get_roles_used_in_context($context, $view = false) {
3851 global $CFG;
3853 // filter for roles with all hidden assignments
3854 // no need to return when only pulling roles for reviewing
3855 // e.g. participants page.
3856 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
3857 $contextlist = get_related_contexts_string($context);
3859 $sql = "SELECT DISTINCT r.id,
3860 r.name,
3861 r.shortname,
3862 r.sortorder
3863 FROM {$CFG->prefix}role_assignments ra,
3864 {$CFG->prefix}role r
3865 WHERE r.id = ra.roleid
3866 AND ra.contextid $contextlist
3867 $hiddensql
3868 ORDER BY r.sortorder ASC";
3870 return get_records_sql($sql);
3874 * This function is used to print roles column in user profile page.
3875 * @param int userid
3876 * @param object context
3877 * @return string
3879 function get_user_roles_in_context($userid, $context, $view=true){
3880 global $CFG, $USER;
3882 $rolestring = '';
3883 $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';
3884 $rolenames = array();
3885 if ($roles = get_records_sql($SQL)) {
3886 foreach ($roles as $userrole) {
3887 // MDL-12544, if we are in view mode and current user has no capability to view hidden assignment, skip it
3888 if ($userrole->hidden && $view && !has_capability('moodle/role:viewhiddenassigns', $context)) {
3889 continue;
3891 $rolenames[$userrole->roleid] = $userrole->name;
3894 $rolenames = role_fix_names($rolenames, $context); // Substitute aliases
3896 foreach ($rolenames as $roleid => $rolename) {
3897 $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
3899 $rolestring = implode(',', $rolenames);
3901 return $rolestring;
3906 * Checks if a user can override capabilities of a particular role in this context
3907 * @param object $context
3908 * @param int targetroleid - the id of the role you want to override
3909 * @return boolean
3911 function user_can_override($context, $targetroleid) {
3913 // TODO: not needed anymore, remove in 2.0
3915 // first check if user has override capability
3916 // if not return false;
3917 if (!has_capability('moodle/role:override', $context)) {
3918 return false;
3920 // pull out all active roles of this user from this context(or above)
3921 if ($userroles = get_user_roles($context)) {
3922 foreach ($userroles as $userrole) {
3923 // if any in the role_allow_override table, then it's ok
3924 if (get_record('role_allow_override', 'roleid', $userrole->roleid, 'allowoverride', $targetroleid)) {
3925 return true;
3930 return false;
3935 * Checks if a user can assign users to a particular role in this context
3936 * @param object $context
3937 * @param int targetroleid - the id of the role you want to assign users to
3938 * @return boolean
3940 function user_can_assign($context, $targetroleid) {
3942 // first check if user has override capability
3943 // if not return false;
3944 if (!has_capability('moodle/role:assign', $context)) {
3945 return false;
3947 // pull out all active roles of this user from this context(or above)
3948 if ($userroles = get_user_roles($context)) {
3949 foreach ($userroles as $userrole) {
3950 // if any in the role_allow_override table, then it's ok
3951 if (get_record('role_allow_assign', 'roleid', $userrole->roleid, 'allowassign', $targetroleid)) {
3952 return true;
3957 return false;
3960 /** Returns all site roles in correct sort order.
3963 function get_all_roles() {
3964 return get_records('role', '', '', 'sortorder ASC');
3968 * gets all the user roles assigned in this context, or higher contexts
3969 * this is mainly used when checking if a user can assign a role, or overriding a role
3970 * i.e. we need to know what this user holds, in order to verify against allow_assign and
3971 * allow_override tables
3972 * @param object $context
3973 * @param int $userid
3974 * @param view - set to true when roles are pulled for display only
3975 * this is so that we can filter roles with no visible
3976 * assignment, for example, you might want to "hide" all
3977 * course creators when browsing the course participants
3978 * list.
3979 * @return array
3981 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC', $view=false) {
3983 global $USER, $CFG, $db;
3985 if (empty($userid)) {
3986 if (empty($USER->id)) {
3987 return array();
3989 $userid = $USER->id;
3991 // set up hidden sql
3992 $hiddensql = ($view && !has_capability('moodle/role:viewhiddenassigns', $context))? ' AND ra.hidden = 0 ':'';
3994 if ($checkparentcontexts && ($parents = get_parent_contexts($context))) {
3995 $contexts = ' ra.contextid IN ('.implode(',' , $parents).','.$context->id.')';
3996 } else {
3997 $contexts = ' ra.contextid = \''.$context->id.'\'';
4000 if (!$return = get_records_sql('SELECT ra.*, r.name, r.shortname
4001 FROM '.$CFG->prefix.'role_assignments ra,
4002 '.$CFG->prefix.'role r,
4003 '.$CFG->prefix.'context c
4004 WHERE ra.userid = '.$userid.'
4005 AND ra.roleid = r.id
4006 AND ra.contextid = c.id
4007 AND '.$contexts . $hiddensql .'
4008 ORDER BY '.$order)) {
4009 $return = array();
4012 return $return;
4016 * Creates a record in the allow_override table
4017 * @param int sroleid - source roleid
4018 * @param int troleid - target roleid
4019 * @return int - id or false
4021 function allow_override($sroleid, $troleid) {
4022 $record = new object();
4023 $record->roleid = $sroleid;
4024 $record->allowoverride = $troleid;
4025 return insert_record('role_allow_override', $record);
4029 * Creates a record in the allow_assign table
4030 * @param int sroleid - source roleid
4031 * @param int troleid - target roleid
4032 * @return int - id or false
4034 function allow_assign($sroleid, $troleid) {
4035 $record = new object;
4036 $record->roleid = $sroleid;
4037 $record->allowassign = $troleid;
4038 return insert_record('role_allow_assign', $record);
4042 * Gets a list of roles that this user can assign in this context
4043 * @param object $context
4044 * @param string $field
4045 * @param int $rolenamedisplay
4046 * @return array
4048 function get_assignable_roles($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS) {
4049 global $USER, $CFG;
4051 if (!has_capability('moodle/role:assign', $context)) {
4052 return array();
4055 $parents = get_parent_contexts($context);
4056 $parents[] = $context->id;
4057 $contexts = implode(',' , $parents);
4059 if (!$roles = get_records_sql("SELECT ro.*
4060 FROM {$CFG->prefix}role ro,
4062 SELECT DISTINCT r.id
4063 FROM {$CFG->prefix}role r,
4064 {$CFG->prefix}role_assignments ra,
4065 {$CFG->prefix}role_allow_assign raa
4066 WHERE ra.userid = $USER->id AND ra.contextid IN ($contexts)
4067 AND raa.roleid = ra.roleid AND r.id = raa.allowassign
4068 ) inline_view
4069 WHERE ro.id = inline_view.id
4070 ORDER BY ro.sortorder ASC")) {
4071 return array();
4074 foreach ($roles as $role) {
4075 $roles[$role->id] = $role->$field;
4078 return role_fix_names($roles, $context, $rolenamedisplay);
4082 * Gets a list of roles that this user can assign in this context, for the switchrole menu
4084 * @param object $context
4085 * @param string $field
4086 * @param int $rolenamedisplay
4087 * @return array
4089 function get_assignable_roles_for_switchrole($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS) {
4090 global $USER, $CFG;
4092 if (!has_capability('moodle/role:assign', $context)) {
4093 return array();
4096 $parents = get_parent_contexts($context);
4097 $parents[] = $context->id;
4098 $contexts = implode(',' , $parents);
4100 if (!$roles = get_records_sql("SELECT ro.*
4101 FROM {$CFG->prefix}role ro,
4103 SELECT DISTINCT r.id
4104 FROM {$CFG->prefix}role r,
4105 {$CFG->prefix}role_assignments ra,
4106 {$CFG->prefix}role_allow_assign raa,
4107 {$CFG->prefix}role_capabilities rc
4108 WHERE ra.userid = $USER->id AND ra.contextid IN ($contexts)
4109 AND raa.roleid = ra.roleid AND r.id = raa.allowassign
4110 AND r.id = rc.roleid AND rc.capability = 'moodle/course:view' AND rc.capability != 'moodle/site:doanything'
4111 ) inline_view
4112 WHERE ro.id = inline_view.id
4113 ORDER BY ro.sortorder ASC")) {
4114 return array();
4117 foreach ($roles as $role) {
4118 $roles[$role->id] = $role->$field;
4121 return role_fix_names($roles, $context, $rolenamedisplay);
4125 * Gets a list of roles that this user can override or safeoverride in this context
4126 * @param object $context
4127 * @param string $field
4128 * @param int $rolenamedisplay
4129 * @return array
4131 function get_overridable_roles($context, $field='name', $rolenamedisplay=ROLENAME_ALIAS) {
4132 global $USER, $CFG;
4134 if (!has_capability('moodle/role:override', $context) and !has_capability('moodle/role:safeoverride', $context)) {
4135 return array();
4138 $parents = get_parent_contexts($context);
4139 $parents[] = $context->id;
4140 $contexts = implode(',' , $parents);
4142 if (!$roles = get_records_sql("SELECT ro.*
4143 FROM {$CFG->prefix}role ro,
4145 SELECT DISTINCT r.id
4146 FROM {$CFG->prefix}role r,
4147 {$CFG->prefix}role_assignments ra,
4148 {$CFG->prefix}role_allow_override rao
4149 WHERE ra.userid = $USER->id AND ra.contextid IN ($contexts)
4150 AND rao.roleid = ra.roleid AND r.id = rao.allowoverride
4151 ) inline_view
4152 WHERE ro.id = inline_view.id
4153 ORDER BY ro.sortorder ASC")) {
4154 return array();
4157 foreach ($roles as $role) {
4158 $roles[$role->id] = $role->$field;
4161 return role_fix_names($roles, $context, $rolenamedisplay);
4165 * Returns a role object that is the default role for new enrolments
4166 * in a given course
4168 * @param object $course
4169 * @return object $role
4171 function get_default_course_role($course) {
4172 global $CFG;
4174 /// First let's take the default role the course may have
4175 if (!empty($course->defaultrole)) {
4176 if ($role = get_record('role', 'id', $course->defaultrole)) {
4177 return $role;
4181 /// Otherwise the site setting should tell us
4182 if ($CFG->defaultcourseroleid) {
4183 if ($role = get_record('role', 'id', $CFG->defaultcourseroleid)) {
4184 return $role;
4188 /// It's unlikely we'll get here, but just in case, try and find a student role
4189 if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
4190 return array_shift($studentroles); /// Take the first one
4193 return NULL;
4198 * Who has this capability in this context?
4200 * This can be a very expensive call - use sparingly and keep
4201 * the results if you are going to need them again soon.
4203 * Note if $fields is empty this function attempts to get u.*
4204 * which can get rather large - and has a serious perf impact
4205 * on some DBs.
4207 * @param $context - object
4208 * @param $capability - string capability
4209 * @param $fields - fields to be pulled
4210 * @param $sort - the sort order
4211 * @param $limitfrom - number of records to skip (offset)
4212 * @param $limitnum - number of records to fetch
4213 * @param $groups - single group or array of groups - only return
4214 * users who are in one of these group(s).
4215 * @param $exceptions - list of users to exclude
4216 * @param view - set to true when roles are pulled for display only
4217 * this is so that we can filter roles with no visible
4218 * assignment, for example, you might want to "hide" all
4219 * course creators when browsing the course participants
4220 * list.
4221 * @param boolean $useviewallgroups if $groups is set the return users who
4222 * have capability both $capability and moodle/site:accessallgroups
4223 * in this context, as well as users who have $capability and who are
4224 * in $groups.
4226 function get_users_by_capability($context, $capability, $fields='', $sort='',
4227 $limitfrom='', $limitnum='', $groups='', $exceptions='', $doanything=true,
4228 $view=false, $useviewallgroups=false) {
4229 global $CFG;
4231 $ctxids = substr($context->path, 1); // kill leading slash
4232 $ctxids = str_replace('/', ',', $ctxids);
4234 // Context is the frontpage
4235 $isfrontpage = false;
4236 $iscoursepage = false; // coursepage other than fp
4237 if ($context->contextlevel == CONTEXT_COURSE) {
4238 if ($context->instanceid == SITEID) {
4239 $isfrontpage = true;
4240 } else {
4241 $iscoursepage = true;
4245 // What roles/rolecaps are interesting?
4246 $caps = "'$capability'";
4247 if ($doanything===true) {
4248 $caps.=",'moodle/site:doanything'";
4249 $doanything_join='';
4250 $doanything_cond='';
4251 } else {
4252 // This is an outer join against
4253 // admin-ish roleids. Any row that succeeds
4254 // in JOINing here ends up removed from
4255 // the resultset. This means we remove
4256 // rolecaps from roles that also have
4257 // 'doanything' capabilities.
4258 $doanything_join="LEFT OUTER JOIN (
4259 SELECT DISTINCT rc.roleid
4260 FROM {$CFG->prefix}role_capabilities rc
4261 WHERE rc.capability='moodle/site:doanything'
4262 AND rc.permission=".CAP_ALLOW."
4263 AND rc.contextid IN ($ctxids)
4264 ) dar
4265 ON rc.roleid=dar.roleid";
4266 $doanything_cond="AND dar.roleid IS NULL";
4269 // fetch all capability records - we'll walk several
4270 // times over them, and should be a small set
4272 $negperm = false; // has any negative (<0) permission?
4273 $roleids = array();
4275 $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability,
4276 ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
4277 FROM {$CFG->prefix}role_capabilities rc
4278 JOIN {$CFG->prefix}context ctx on rc.contextid = ctx.id
4279 $doanything_join
4280 WHERE rc.capability IN ($caps) AND ctx.id IN ($ctxids)
4281 $doanything_cond
4282 ORDER BY rc.roleid ASC, ctx.depth ASC";
4283 if ($capdefs = get_records_sql($sql)) {
4284 foreach ($capdefs AS $rcid=>$rc) {
4285 $roleids[] = (int)$rc->roleid;
4286 if ($rc->permission < 0) {
4287 $negperm = true;
4292 $roleids = array_unique($roleids);
4294 if (count($roleids)===0) { // noone here!
4295 return false;
4298 // is the default role interesting? does it have
4299 // a relevant rolecap? (we use this a lot later)
4300 if (in_array((int)$CFG->defaultuserroleid, $roleids, true)) {
4301 $defaultroleinteresting = true;
4302 } else {
4303 $defaultroleinteresting = false;
4307 // Prepare query clauses
4309 $wherecond = array();
4310 /// Groups
4311 if ($groups) {
4312 if (is_array($groups)) {
4313 $grouptest = 'gm.groupid IN (' . implode(',', $groups) . ')';
4314 } else {
4315 $grouptest = 'gm.groupid = ' . $groups;
4317 $grouptest = 'ra.userid IN (SELECT userid FROM ' .
4318 $CFG->prefix . 'groups_members gm WHERE ' . $grouptest . ')';
4320 if ($useviewallgroups) {
4321 $viewallgroupsusers = get_users_by_capability($context,
4322 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
4323 $wherecond['groups'] = '('. $grouptest . ' OR ra.userid IN (' .
4324 implode(',', array_keys($viewallgroupsusers)) . '))';
4325 } else {
4326 $wherecond['groups'] = '(' . $grouptest .')';
4330 /// User exceptions
4331 if (!empty($exceptions)) {
4332 $wherecond['userexceptions'] = ' u.id NOT IN ('.$exceptions.')';
4335 /// Set up hidden role-assignments sql
4336 if ($view && !has_capability('moodle/role:viewhiddenassigns', $context)) {
4337 $condhiddenra = 'AND ra.hidden = 0 ';
4338 $sscondhiddenra = 'AND ssra.hidden = 0 ';
4339 } else {
4340 $condhiddenra = '';
4341 $sscondhiddenra = '';
4344 // Collect WHERE conditions
4345 $where = implode(' AND ', array_values($wherecond));
4346 if ($where != '') {
4347 $where = 'WHERE ' . $where;
4350 /// Set up default fields
4351 if (empty($fields)) {
4352 if ($iscoursepage) {
4353 $fields = 'u.*, ul.timeaccess as lastaccess';
4354 } else {
4355 $fields = 'u.*';
4359 /// Set up default sort
4360 if (empty($sort)) { // default to course lastaccess or just lastaccess
4361 if ($iscoursepage) {
4362 $sort = 'ul.timeaccess';
4363 } else {
4364 $sort = 'u.lastaccess';
4367 $sortby = $sort ? " ORDER BY $sort " : '';
4369 // User lastaccess JOIN
4370 if ((strpos($sort, 'ul.timeaccess') === FALSE) and (strpos($fields, 'ul.timeaccess') === FALSE)) { // user_lastaccess is not required MDL-13810
4371 $uljoin = '';
4372 } else {
4373 $uljoin = "LEFT OUTER JOIN {$CFG->prefix}user_lastaccess ul
4374 ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
4378 // Simple cases - No negative permissions means we can take shortcuts
4380 if (!$negperm) {
4382 // at the frontpage, and all site users have it - easy!
4383 if ($isfrontpage && !empty($CFG->defaultfrontpageroleid)
4384 && in_array((int)$CFG->defaultfrontpageroleid, $roleids, true)) {
4386 return get_records_sql("SELECT $fields
4387 FROM {$CFG->prefix}user u
4388 ORDER BY $sort",
4389 $limitfrom, $limitnum);
4392 // all site users have it, anyway
4393 // TODO: NOT ALWAYS! Check this case because this gets run for cases like this:
4394 // 1) Default role has the permission for a module thing like mod/choice:choose
4395 // 2) We are checking for an activity module context in a course
4396 // 3) Thus all users are returned even though course:view is also required
4397 if ($defaultroleinteresting) {
4398 $sql = "SELECT $fields
4399 FROM {$CFG->prefix}user u
4400 $uljoin
4401 $where
4402 ORDER BY $sort";
4403 return get_records_sql($sql, $limitfrom, $limitnum);
4406 /// Simple SQL assuming no negative rolecaps.
4407 /// We use a subselect to grab the role assignments
4408 /// ensuring only one row per user -- even if they
4409 /// have many "relevant" role assignments.
4410 $select = " SELECT $fields";
4411 $from = " FROM {$CFG->prefix}user u
4412 JOIN (SELECT DISTINCT ssra.userid
4413 FROM {$CFG->prefix}role_assignments ssra
4414 WHERE ssra.contextid IN ($ctxids)
4415 AND ssra.roleid IN (".implode(',',$roleids) .")
4416 $sscondhiddenra
4417 ) ra ON ra.userid = u.id
4418 $uljoin ";
4419 $where = " WHERE u.deleted = 0 ";
4420 if (count(array_keys($wherecond))) {
4421 $where .= ' AND ' . implode(' AND ', array_values($wherecond));
4423 return get_records_sql($select.$from.$where.$sortby, $limitfrom, $limitnum);
4427 // If there are any negative rolecaps, we need to
4428 // work through a subselect that will bring several rows
4429 // per user (one per RA).
4430 // Since we cannot do the job in pure SQL (not without SQL stored
4431 // procedures anyway), we end up tied to processing the data in PHP
4432 // all the way down to pagination.
4434 // In some cases, this will mean bringing across a ton of data --
4435 // when paginating, we have to walk the permisisons of all the rows
4436 // in the _previous_ pages to get the pagination correct in the case
4437 // of users that end up not having the permission - this removed.
4440 // Prepare the role permissions datastructure for fast lookups
4441 $roleperms = array(); // each role cap and depth
4442 foreach ($capdefs AS $rcid=>$rc) {
4444 $rid = (int)$rc->roleid;
4445 $perm = (int)$rc->permission;
4446 $rcdepth = (int)$rc->ctxdepth;
4447 if (!isset($roleperms[$rc->capability][$rid])) {
4448 $roleperms[$rc->capability][$rid] = (object)array('perm' => $perm,
4449 'rcdepth' => $rcdepth);
4450 } else {
4451 if ($roleperms[$rc->capability][$rid]->perm == CAP_PROHIBIT) {
4452 continue;
4454 // override - as we are going
4455 // from general to local perms
4456 // (as per the ORDER BY...depth ASC above)
4457 // and local perms win...
4458 $roleperms[$rc->capability][$rid] = (object)array('perm' => $perm,
4459 'rcdepth' => $rcdepth);
4464 if ($context->contextlevel == CONTEXT_SYSTEM
4465 || $isfrontpage
4466 || $defaultroleinteresting) {
4468 // Handle system / sitecourse / defaultrole-with-perhaps-neg-overrides
4469 // with a SELECT FROM user LEFT OUTER JOIN against ra -
4470 // This is expensive on the SQL and PHP sides -
4471 // moves a ton of data across the wire.
4472 $ss = "SELECT u.id as userid, ra.roleid,
4473 ctx.depth
4474 FROM {$CFG->prefix}user u
4475 LEFT OUTER JOIN {$CFG->prefix}role_assignments ra
4476 ON (ra.userid = u.id
4477 AND ra.contextid IN ($ctxids)
4478 AND ra.roleid IN (".implode(',',$roleids) .")
4479 $condhiddenra)
4480 LEFT OUTER JOIN {$CFG->prefix}context ctx
4481 ON ra.contextid=ctx.id
4482 WHERE u.deleted=0";
4483 } else {
4484 // "Normal complex case" - the rolecaps we are after will
4485 // be defined in a role assignment somewhere.
4486 $ss = "SELECT ra.userid as userid, ra.roleid,
4487 ctx.depth
4488 FROM {$CFG->prefix}role_assignments ra
4489 JOIN {$CFG->prefix}context ctx
4490 ON ra.contextid=ctx.id
4491 WHERE ra.contextid IN ($ctxids)
4492 $condhiddenra
4493 AND ra.roleid IN (".implode(',',$roleids) .")";
4496 $select = "SELECT $fields ,ra.roleid, ra.depth ";
4497 $from = "FROM ($ss) ra
4498 JOIN {$CFG->prefix}user u
4499 ON ra.userid=u.id
4500 $uljoin ";
4501 $where = "WHERE u.deleted = 0 ";
4502 if (count(array_keys($wherecond))) {
4503 $where .= ' AND ' . implode(' AND ', array_values($wherecond));
4506 // Each user's entries MUST come clustered together
4507 // and RAs ordered in depth DESC - the role/cap resolution
4508 // code depends on this.
4509 $sort .= ' , ra.userid ASC, ra.depth DESC';
4510 $sortby .= ' , ra.userid ASC, ra.depth DESC ';
4512 $rs = get_recordset_sql($select.$from.$where.$sortby);
4515 // Process the user accounts+RAs, folding repeats together...
4517 // The processing for this recordset is tricky - to fold
4518 // the role/perms of users with multiple role-assignments
4519 // correctly while still processing one-row-at-a-time
4520 // we need to add a few additional 'private' fields to
4521 // the results array - so we can treat the rows as a
4522 // state machine to track the cap/perms and at what RA-depth
4523 // and RC-depth they were defined.
4525 // So what we do here is:
4526 // - loop over rows, checking pagination limits
4527 // - when we find a new user, if we are in the page add it to the
4528 // $results, and start building $ras array with its role-assignments
4529 // - when we are dealing with the next user, or are at the end of the userlist
4530 // (last rec or last in page), trigger the check-permission idiom
4531 // - the check permission idiom will
4532 // - add the default enrolment if needed
4533 // - call has_capability_from_rarc(), which based on RAs and RCs will return a bool
4534 // (should be fairly tight code ;-) )
4535 // - if the user has permission, all is good, just $c++ (counter)
4536 // - ...else, decrease the counter - so pagination is kept straight,
4537 // and (if we are in the page) remove from the results
4539 $results = array();
4541 // pagination controls
4542 $c = 0;
4543 $limitfrom = (int)$limitfrom;
4544 $limitnum = (int)$limitnum;
4547 // Track our last user id so we know when we are dealing
4548 // with a new user...
4550 $lastuserid = 0;
4552 // In this loop, we
4553 // $ras: role assignments, multidimensional array
4554 // treat as a stack - going from local to general
4555 // $ras = (( roleid=> x, $depth=>y) , ( roleid=> x, $depth=>y))
4557 while ($user = rs_fetch_next_record($rs)) {
4559 //error_log(" Record: " . print_r($user,1));
4562 // Pagination controls
4563 // Note that we might end up removing a user
4564 // that ends up _not_ having the rights,
4565 // therefore rolling back $c
4567 if ($lastuserid != $user->id) {
4569 // Did the last user end up with a positive permission?
4570 if ($lastuserid !=0) {
4571 if ($defaultroleinteresting) {
4572 // add the role at the end of $ras
4573 $ras[] = array( 'roleid' => $CFG->defaultuserroleid,
4574 'depth' => 1 );
4576 if (has_capability_from_rarc($ras, $roleperms, $capability, $doanything)) {
4577 $c++;
4578 } else {
4579 // remove the user from the result set,
4580 // only if we are 'in the page'
4581 if ($limitfrom === 0 || $c >= $limitfrom) {
4582 unset($results[$lastuserid]);
4587 // Did we hit pagination limit?
4588 if ($limitnum !==0 && $c >= ($limitfrom+$limitnum)) { // we are done!
4589 break;
4592 // New user setup, and $ras reset
4593 $lastuserid = $user->id;
4594 $ras = array();
4595 if (!empty($user->roleid)) {
4596 $ras[] = array( 'roleid' => (int)$user->roleid,
4597 'depth' => (int)$user->depth );
4600 // if we are 'in the page', also add the rec
4601 // to the results...
4602 if ($limitfrom === 0 || $c >= $limitfrom) {
4603 $results[$user->id] = $user; // trivial
4605 } else {
4606 // Additional RA for $lastuserid
4607 $ras[] = array( 'roleid'=>(int)$user->roleid,
4608 'depth'=>(int)$user->depth );
4611 } // end while(fetch)
4613 // Prune last entry if necessary
4614 if ($lastuserid !=0) {
4615 if ($defaultroleinteresting) {
4616 // add the role at the end of $ras
4617 $ras[] = array( 'roleid' => $CFG->defaultuserroleid,
4618 'depth' => 1 );
4620 if (!has_capability_from_rarc($ras, $roleperms, $capability, $doanything)) {
4621 // remove the user from the result set,
4622 // only if we are 'in the page'
4623 if ($limitfrom === 0 || $c >= $limitfrom) {
4624 if (isset($results[$lastuserid])) {
4625 unset($results[$lastuserid]);
4631 return $results;
4635 * Fast (fast!) utility function to resolve if a capability is granted,
4636 * based on Role Assignments and Role Capabilities.
4638 * Used (at least) by get_users_by_capability().
4640 * If PHP had fast built-in memoize functions, we could
4641 * add a $contextid parameter and memoize the return values.
4643 * @param array $ras - role assignments
4644 * @param array $roleperms - role permissions
4645 * @param string $capability - name of the capability
4646 * @param bool $doanything
4647 * @return boolean
4650 function has_capability_from_rarc($ras, $roleperms, $capability, $doanything) {
4651 // Mini-state machine, using $hascap
4652 // $hascap[ 'moodle/foo:bar' ]->perm = CAP_SOMETHING (numeric constant)
4653 // $hascap[ 'moodle/foo:bar' ]->radepth = depth of the role assignment that set it
4654 // $hascap[ 'moodle/foo:bar' ]->rcdepth = depth of the rolecap that set it
4655 // -- when resolving conflicts, we need to look into radepth first, if unresolved
4657 $caps = array($capability);
4658 if ($doanything) {
4659 $caps[] = 'moodle/site:candoanything';
4662 $hascap = array();
4665 // Compute which permission/roleassignment/rolecap
4666 // wins for each capability we are walking
4668 foreach ($ras as $ra) {
4669 foreach ($caps as $cap) {
4670 if (!isset($roleperms[$cap][$ra['roleid']])) {
4671 // nothing set for this cap - skip
4672 continue;
4674 // We explicitly clone here as we
4675 // add more properties to it
4676 // that must stay separate from the
4677 // original roleperm data structure
4678 $rp = clone($roleperms[$cap][$ra['roleid']]);
4679 $rp->radepth = $ra['depth'];
4681 // Trivial case, we are the first to set
4682 if (!isset($hascap[$cap])) {
4683 $hascap[$cap] = $rp;
4687 // Resolve who prevails, in order of precendence
4688 // - Prohibits always wins
4689 // - Locality of RA
4690 // - Locality of RC
4692 //// Prohibits...
4693 if ($rp->perm === CAP_PROHIBIT) {
4694 $hascap[$cap] = $rp;
4695 continue;
4697 if ($hascap[$cap]->perm === CAP_PROHIBIT) {
4698 continue;
4701 // Locality of RA - the look is ordered by depth DESC
4702 // so from local to general -
4703 // Higher RA loses to local RA... unless perm===0
4704 /// Thanks to the order of the records, $rp->radepth <= $hascap[$cap]->radepth
4705 if ($rp->radepth > $hascap[$cap]->radepth) {
4706 error_log('Should not happen @ ' . __FUNCTION__.':'.__LINE__);
4708 if ($rp->radepth < $hascap[$cap]->radepth) {
4709 if ($hascap[$cap]->perm!==0) {
4710 // Wider RA loses to local RAs...
4711 continue;
4712 } else {
4713 // "Higher RA resolves conflict" case,
4714 // local RAs had cancelled eachother
4715 $hascap[$cap] = $rp;
4716 continue;
4719 // Same ralevel - locality of RC wins
4720 if ($rp->rcdepth > $hascap[$cap]->rcdepth) {
4721 $hascap[$cap] = $rp;
4722 continue;
4724 if ($rp->rcdepth > $hascap[$cap]->rcdepth) {
4725 continue;
4727 // We match depth - add them
4728 $hascap[$cap]->perm += $rp->perm;
4731 if ($hascap[$capability]->perm > 0
4732 || ($doanything && isset($hascap['moodle/site:candoanything'])
4733 && $hascap['moodle/site:candoanything']->perm > 0)) {
4734 return true;
4736 return false;
4740 * Will re-sort a $users results array (from get_users_by_capability(), usually)
4741 * based on a sorting policy. This is to support the odd practice of
4742 * sorting teachers by 'authority', where authority was "lowest id of the role
4743 * assignment".
4745 * Will execute 1 database query. Only suitable for small numbers of users, as it
4746 * uses an u.id IN() clause.
4748 * Notes about the sorting criteria.
4750 * As a default, we cannot rely on role.sortorder because then
4751 * admins/coursecreators will always win. That is why the sane
4752 * rule "is locality matters most", with sortorder as 2nd
4753 * consideration.
4755 * If you want role.sortorder, use the 'sortorder' policy, and
4756 * name explicitly what roles you want to cover. It's probably
4757 * a good idea to see what roles have the capabilities you want
4758 * (array_diff() them against roiles that have 'can-do-anything'
4759 * to weed out admin-ish roles. Or fetch a list of roles from
4760 * variables like $CFG->coursemanagers .
4762 * @param array users Users' array, keyed on userid
4763 * @param object context
4764 * @param array roles - ids of the roles to include, optional
4765 * @param string policy - defaults to locality, more about
4766 * @return array - sorted copy of the array
4768 function sort_by_roleassignment_authority($users, $context, $roles=array(), $sortpolicy='locality') {
4769 global $CFG;
4771 $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
4772 $contextwhere = ' ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
4773 if (empty($roles)) {
4774 $roleswhere = '';
4775 } else {
4776 $roleswhere = ' AND ra.roleid IN ('.implode(',',$roles).')';
4779 $sql = "SELECT ra.userid
4780 FROM {$CFG->prefix}role_assignments ra
4781 JOIN {$CFG->prefix}role r
4782 ON ra.roleid=r.id
4783 JOIN {$CFG->prefix}context ctx
4784 ON ra.contextid=ctx.id
4785 WHERE
4786 $userswhere
4787 AND $contextwhere
4788 $roleswhere
4791 // Default 'locality' policy -- read PHPDoc notes
4792 // about sort policies...
4793 $orderby = 'ORDER BY
4794 ctx.depth DESC, /* locality wins */
4795 r.sortorder ASC, /* rolesorting 2nd criteria */
4796 ra.id /* role assignment order tie-breaker */';
4797 if ($sortpolicy === 'sortorder') {
4798 $orderby = 'ORDER BY
4799 r.sortorder ASC, /* rolesorting 2nd criteria */
4800 ra.id /* role assignment order tie-breaker */';
4803 $sortedids = get_fieldset_sql($sql . $orderby);
4804 $sortedusers = array();
4805 $seen = array();
4807 foreach ($sortedids as $id) {
4808 // Avoid duplicates
4809 if (isset($seen[$id])) {
4810 continue;
4812 $seen[$id] = true;
4814 // assign
4815 $sortedusers[$id] = $users[$id];
4817 return $sortedusers;
4821 * gets all the users assigned this role in this context or higher
4822 * @param int roleid (can also be an array of ints!)
4823 * @param int contextid
4824 * @param bool parent if true, get list of users assigned in higher context too
4825 * @param string fields - fields from user (u.) , role assignment (ra) or role (r.)
4826 * @param string sort - sort from user (u.) , role assignment (ra) or role (r.)
4827 * @param bool gethidden - whether to fetch hidden enrolments too
4828 * @return array()
4830 function get_role_users($roleid, $context, $parent=false, $fields='', $sort='u.lastname ASC', $gethidden=true, $group='', $limitfrom='', $limitnum='') {
4831 global $CFG;
4833 if (empty($fields)) {
4834 $fields = 'u.id, u.confirmed, u.username, u.firstname, u.lastname, '.
4835 'u.maildisplay, u.mailformat, u.maildigest, u.email, u.city, '.
4836 'u.country, u.picture, u.idnumber, u.department, u.institution, '.
4837 'u.emailstop, u.lang, u.timezone, r.name as rolename';
4840 // whether this assignment is hidden
4841 $hiddensql = $gethidden ? '': ' AND ra.hidden = 0 ';
4843 $parentcontexts = '';
4844 if ($parent) {
4845 $parentcontexts = substr($context->path, 1); // kill leading slash
4846 $parentcontexts = str_replace('/', ',', $parentcontexts);
4847 if ($parentcontexts !== '') {
4848 $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
4852 if (is_array($roleid)) {
4853 $roleselect = ' AND ra.roleid IN (' . implode(',',$roleid) .')';
4854 } elseif (!empty($roleid)) { // should not test for int, because it can come in as a string
4855 $roleselect = "AND ra.roleid = $roleid";
4856 } else {
4857 $roleselect = '';
4860 if ($group) {
4861 $groupjoin = "JOIN {$CFG->prefix}groups_members gm
4862 ON gm.userid = u.id";
4863 $groupselect = " AND gm.groupid = $group ";
4864 } else {
4865 $groupjoin = '';
4866 $groupselect = '';
4869 $SQL = "SELECT $fields, ra.roleid
4870 FROM {$CFG->prefix}role_assignments ra
4871 JOIN {$CFG->prefix}user u
4872 ON u.id = ra.userid
4873 JOIN {$CFG->prefix}role r
4874 ON ra.roleid = r.id
4875 $groupjoin
4876 WHERE (ra.contextid = $context->id $parentcontexts)
4877 $roleselect
4878 $groupselect
4879 $hiddensql
4880 ORDER BY $sort
4881 "; // join now so that we can just use fullname() later
4883 return get_records_sql($SQL, $limitfrom, $limitnum);
4887 * Counts all the users assigned this role in this context or higher
4888 * @param int roleid
4889 * @param int contextid
4890 * @param bool parent if true, get list of users assigned in higher context too
4891 * @return array()
4893 function count_role_users($roleid, $context, $parent=false) {
4894 global $CFG;
4896 if ($parent) {
4897 if ($contexts = get_parent_contexts($context)) {
4898 $parentcontexts = ' OR r.contextid IN ('.implode(',', $contexts).')';
4899 } else {
4900 $parentcontexts = '';
4902 } else {
4903 $parentcontexts = '';
4906 $SQL = "SELECT count(u.id)
4907 FROM {$CFG->prefix}role_assignments r
4908 JOIN {$CFG->prefix}user u
4909 ON u.id = r.userid
4910 WHERE (r.contextid = $context->id $parentcontexts)
4911 AND r.roleid = $roleid
4912 AND u.deleted = 0";
4914 return count_records_sql($SQL);
4918 * This function gets the list of courses that this user has a particular capability in.
4919 * It is still not very efficient.
4920 * @param string $capability Capability in question
4921 * @param int $userid User ID or null for current user
4922 * @param bool $doanything True if 'doanything' is permitted (default)
4923 * @param string $fieldsexceptid Leave blank if you only need 'id' in the course records;
4924 * otherwise use a comma-separated list of the fields you require, not including id
4925 * @param string $orderby If set, use a comma-separated list of fields from course
4926 * table with sql modifiers (DESC) if needed
4927 * @return array Array of courses, may have zero entries. Or false if query failed.
4929 function get_user_capability_course($capability, $userid=NULL,$doanything=true,$fieldsexceptid='',$orderby='') {
4930 // Convert fields list and ordering
4931 $fieldlist='';
4932 if($fieldsexceptid) {
4933 $fields=explode(',',$fieldsexceptid);
4934 foreach($fields as $field) {
4935 $fieldlist.=',c.'.$field;
4938 if($orderby) {
4939 $fields=explode(',',$orderby);
4940 $orderby='';
4941 foreach($fields as $field) {
4942 if($orderby) {
4943 $orderby.=',';
4945 $orderby.='c.'.$field;
4947 $orderby='ORDER BY '.$orderby;
4950 // Obtain a list of everything relevant about all courses including context.
4951 // Note the result can be used directly as a context (we are going to), the course
4952 // fields are just appended.
4953 global $CFG;
4954 $rs=get_recordset_sql("
4955 SELECT
4956 x.*,c.id AS courseid$fieldlist
4957 FROM
4958 {$CFG->prefix}course c
4959 INNER JOIN {$CFG->prefix}context x ON c.id=x.instanceid AND x.contextlevel=".CONTEXT_COURSE."
4960 $orderby
4962 if(!$rs) {
4963 return false;
4966 // Check capability for each course in turn
4967 $courses=array();
4968 while($coursecontext=rs_fetch_next_record($rs)) {
4969 if(has_capability($capability,$coursecontext,$userid,$doanything)) {
4970 // We've got the capability. Make the record look like a course record
4971 // and store it
4972 $coursecontext->id=$coursecontext->courseid;
4973 unset($coursecontext->courseid);
4974 unset($coursecontext->contextlevel);
4975 unset($coursecontext->instanceid);
4976 $courses[]=$coursecontext;
4979 return $courses;
4982 /** This function finds the roles assigned directly to this context only
4983 * i.e. no parents role
4984 * @param object $context
4985 * @return array
4987 function get_roles_on_exact_context($context) {
4989 global $CFG;
4991 return get_records_sql("SELECT r.*
4992 FROM {$CFG->prefix}role_assignments ra,
4993 {$CFG->prefix}role r
4994 WHERE ra.roleid = r.id
4995 AND ra.contextid = $context->id");
5000 * Switches the current user to another role for the current session and only
5001 * in the given context.
5003 * The caller *must* check
5004 * - that this op is allowed
5005 * - that the requested role can be assigned in this ctx
5006 * (hint, use get_assignable_roles_for_switchrole())
5007 * - that the requested role is NOT $CFG->defaultuserroleid
5009 * To "unswitch" pass 0 as the roleid.
5011 * This function *will* modify $USER->access - beware
5013 * @param integer $roleid
5014 * @param object $context
5015 * @return bool
5017 function role_switch($roleid, $context) {
5018 global $USER, $CFG;
5021 // Plan of action
5023 // - Add the ghost RA to $USER->access
5024 // as $USER->access['rsw'][$path] = $roleid
5026 // - Make sure $USER->access['rdef'] has the roledefs
5027 // it needs to honour the switcheroo
5029 // Roledefs will get loaded "deep" here - down to the last child
5030 // context. Note that
5032 // - When visiting subcontexts, our selective accessdata loading
5033 // will still work fine - though those ra/rdefs will be ignored
5034 // appropriately while the switch is in place
5036 // - If a switcheroo happens at a category with tons of courses
5037 // (that have many overrides for switched-to role), the session
5038 // will get... quite large. Sometimes you just can't win.
5040 // To un-switch just unset($USER->access['rsw'][$path])
5043 // Add the switch RA
5044 if (!isset($USER->access['rsw'])) {
5045 $USER->access['rsw'] = array();
5048 if ($roleid == 0) {
5049 unset($USER->access['rsw'][$context->path]);
5050 if (empty($USER->access['rsw'])) {
5051 unset($USER->access['rsw']);
5053 return true;
5056 $USER->access['rsw'][$context->path]=$roleid;
5058 // Load roledefs
5059 $USER->access = get_role_access_bycontext($roleid, $context,
5060 $USER->access);
5062 /* DO WE NEED THIS AT ALL???
5063 // Add some permissions we are really going
5064 // to always need, even if the role doesn't have them!
5066 $USER->capabilities[$context->id]['moodle/course:view'] = CAP_ALLOW;
5069 return true;
5073 // get any role that has an override on exact context
5074 function get_roles_with_override_on_context($context) {
5076 global $CFG;
5078 return get_records_sql("SELECT r.*
5079 FROM {$CFG->prefix}role_capabilities rc,
5080 {$CFG->prefix}role r
5081 WHERE rc.roleid = r.id
5082 AND rc.contextid = $context->id");
5085 // get all capabilities for this role on this context (overrids)
5086 function get_capabilities_from_role_on_context($role, $context) {
5088 global $CFG;
5090 return get_records_sql("SELECT *
5091 FROM {$CFG->prefix}role_capabilities
5092 WHERE contextid = $context->id
5093 AND roleid = $role->id");
5096 // find out which roles has assignment on this context
5097 function get_roles_with_assignment_on_context($context) {
5099 global $CFG;
5101 return get_records_sql("SELECT r.*
5102 FROM {$CFG->prefix}role_assignments ra,
5103 {$CFG->prefix}role r
5104 WHERE ra.roleid = r.id
5105 AND ra.contextid = $context->id");
5111 * Find all user assignemnt of users for this role, on this context
5113 function get_users_from_role_on_context($role, $context) {
5115 global $CFG;
5117 return get_records_sql("SELECT *
5118 FROM {$CFG->prefix}role_assignments
5119 WHERE contextid = $context->id
5120 AND roleid = $role->id");
5124 * Simple function returning a boolean true if roles exist, otherwise false
5126 function user_has_role_assignment($userid, $roleid, $contextid=0) {
5128 if ($contextid) {
5129 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid, 'contextid', $contextid);
5130 } else {
5131 return record_exists('role_assignments', 'userid', $userid, 'roleid', $roleid);
5136 * Get role name or alias if exists and format the text.
5137 * @param object $role role object
5138 * @param object $coursecontext
5139 * @return $string name of role in course context
5141 function role_get_name($role, $coursecontext) {
5142 if ($r = get_record('role_names','roleid', $role->id,'contextid', $coursecontext->id)) {
5143 return strip_tags(format_string($r->name));
5144 } else {
5145 return strip_tags(format_string($role->name));
5150 * Prepare list of roles for display, apply aliases and format text
5151 * @param array $roleoptions array roleid=>rolename
5152 * @param object $context
5153 * @return array of role names
5155 function role_fix_names($roleoptions, $context, $rolenamedisplay=ROLENAME_ALIAS) {
5156 if ($rolenamedisplay != ROLENAME_ORIGINAL && !empty($context->id)) {
5157 if ($context->contextlevel == CONTEXT_MODULE || $context->contextlevel == CONTEXT_BLOCK) { // find the parent course context
5158 if ($parentcontextid = array_shift(get_parent_contexts($context))) {
5159 $context = get_context_instance_by_id($parentcontextid);
5162 if ($aliasnames = get_records('role_names', 'contextid', $context->id)) {
5163 if ($rolenamedisplay == ROLENAME_ALIAS) {
5164 foreach ($aliasnames as $alias) {
5165 if (isset($roleoptions[$alias->roleid])) {
5166 $roleoptions[$alias->roleid] = format_string($alias->name);
5169 } else if ($rolenamedisplay == ROLENAME_BOTH) {
5170 foreach ($aliasnames as $alias) {
5171 if (isset($roleoptions[$alias->roleid])) {
5172 $roleoptions[$alias->roleid] = format_string($alias->name).' ('.format_string($roleoptions[$alias->roleid]).')';
5178 foreach ($roleoptions as $rid => $name) {
5179 $roleoptions[$rid] = strip_tags($name);
5181 return $roleoptions;
5185 * This function helps admin/roles/manage.php etc to detect if a new line should be printed
5186 * when we read in a new capability
5187 * most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
5188 * but when we are in grade, all reports/import/export capabilites should be together
5189 * @param string a - component string a
5190 * @param string b - component string b
5191 * @return bool - whether 2 component are in different "sections"
5193 function component_level_changed($cap, $comp, $contextlevel) {
5195 if ($cap->component == 'enrol/authorize' && $comp =='enrol/authorize') {
5196 return false;
5199 if (strstr($cap->component, '/') && strstr($comp, '/')) {
5200 $compsa = explode('/', $cap->component);
5201 $compsb = explode('/', $comp);
5205 // we are in gradebook, still
5206 if (($compsa[0] == 'gradeexport' || $compsa[0] == 'gradeimport' || $compsa[0] == 'gradereport') &&
5207 ($compsb[0] == 'gradeexport' || $compsb[0] == 'gradeimport' || $compsb[0] == 'gradereport')) {
5208 return false;
5212 return ($cap->component != $comp || $cap->contextlevel != $contextlevel);
5216 * Populate context.path and context.depth where missing.
5217 * @param bool $force force a complete rebuild of the path and depth fields.
5218 * @param bool $feedback display feedback (during upgrade usually)
5219 * @return void
5221 function build_context_path($force=false, $feedback=false) {
5222 global $CFG;
5223 require_once($CFG->libdir.'/ddllib.php');
5225 // System context
5226 $sitectx = get_system_context(!$force);
5227 $base = '/'.$sitectx->id;
5229 // Sitecourse
5230 $sitecoursectx = get_record('context',
5231 'contextlevel', CONTEXT_COURSE,
5232 'instanceid', SITEID);
5233 if ($force || $sitecoursectx->path !== "$base/{$sitecoursectx->id}") {
5234 set_field('context', 'path', "$base/{$sitecoursectx->id}",
5235 'id', $sitecoursectx->id);
5236 set_field('context', 'depth', 2,
5237 'id', $sitecoursectx->id);
5238 $sitecoursectx = get_record('context',
5239 'contextlevel', CONTEXT_COURSE,
5240 'instanceid', SITEID);
5243 $ctxemptyclause = " AND (ctx.path IS NULL
5244 OR ctx.depth=0) ";
5245 $emptyclause = " AND ({$CFG->prefix}context.path IS NULL
5246 OR {$CFG->prefix}context.depth=0) ";
5247 if ($force) {
5248 $ctxemptyclause = $emptyclause = '';
5251 /* MDL-11347:
5252 * - mysql does not allow to use FROM in UPDATE statements
5253 * - using two tables after UPDATE works in mysql, but might give unexpected
5254 * results in pg 8 (depends on configuration)
5255 * - using table alias in UPDATE does not work in pg < 8.2
5257 if ($CFG->dbfamily == 'mysql') {
5258 $updatesql = "UPDATE {$CFG->prefix}context ct, {$CFG->prefix}context_temp temp
5259 SET ct.path = temp.path,
5260 ct.depth = temp.depth
5261 WHERE ct.id = temp.id";
5262 } else if ($CFG->dbfamily == 'oracle') {
5263 $updatesql = "UPDATE {$CFG->prefix}context ct
5264 SET (ct.path, ct.depth) =
5265 (SELECT temp.path, temp.depth
5266 FROM {$CFG->prefix}context_temp temp
5267 WHERE temp.id=ct.id)
5268 WHERE EXISTS (SELECT 'x'
5269 FROM {$CFG->prefix}context_temp temp
5270 WHERE temp.id = ct.id)";
5271 } else {
5272 $updatesql = "UPDATE {$CFG->prefix}context
5273 SET path = temp.path,
5274 depth = temp.depth
5275 FROM {$CFG->prefix}context_temp temp
5276 WHERE temp.id={$CFG->prefix}context.id";
5279 $udelsql = "TRUNCATE TABLE {$CFG->prefix}context_temp";
5281 // Top level categories
5282 $sql = "UPDATE {$CFG->prefix}context
5283 SET depth=2, path=" . sql_concat("'$base/'", 'id') . "
5284 WHERE contextlevel=".CONTEXT_COURSECAT."
5285 AND EXISTS (SELECT 'x'
5286 FROM {$CFG->prefix}course_categories cc
5287 WHERE cc.id = {$CFG->prefix}context.instanceid
5288 AND cc.depth=1)
5289 $emptyclause";
5291 execute_sql($sql, $feedback);
5293 execute_sql($udelsql, $feedback);
5295 // Deeper categories - one query per depthlevel
5296 $maxdepth = get_field_sql("SELECT MAX(depth)
5297 FROM {$CFG->prefix}course_categories");
5298 for ($n=2;$n<=$maxdepth;$n++) {
5299 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5300 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", $n+1
5301 FROM {$CFG->prefix}context ctx
5302 JOIN {$CFG->prefix}course_categories c ON ctx.instanceid=c.id
5303 JOIN {$CFG->prefix}context pctx ON c.parent=pctx.instanceid
5304 WHERE ctx.contextlevel=".CONTEXT_COURSECAT."
5305 AND pctx.contextlevel=".CONTEXT_COURSECAT."
5306 AND c.depth=$n
5307 AND NOT EXISTS (SELECT 'x'
5308 FROM {$CFG->prefix}context_temp temp
5309 WHERE temp.id = ctx.id)
5310 $ctxemptyclause";
5311 execute_sql($sql, $feedback);
5313 // this is needed after every loop
5314 // MDL-11532
5315 execute_sql($updatesql, $feedback);
5316 execute_sql($udelsql, $feedback);
5319 // Courses -- except sitecourse
5320 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5321 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5322 FROM {$CFG->prefix}context ctx
5323 JOIN {$CFG->prefix}course c ON ctx.instanceid=c.id
5324 JOIN {$CFG->prefix}context pctx ON c.category=pctx.instanceid
5325 WHERE ctx.contextlevel=".CONTEXT_COURSE."
5326 AND c.id!=".SITEID."
5327 AND pctx.contextlevel=".CONTEXT_COURSECAT."
5328 AND NOT EXISTS (SELECT 'x'
5329 FROM {$CFG->prefix}context_temp temp
5330 WHERE temp.id = ctx.id)
5331 $ctxemptyclause";
5332 execute_sql($sql, $feedback);
5334 execute_sql($updatesql, $feedback);
5335 execute_sql($udelsql, $feedback);
5337 // Module instances
5338 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5339 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5340 FROM {$CFG->prefix}context ctx
5341 JOIN {$CFG->prefix}course_modules cm ON ctx.instanceid=cm.id
5342 JOIN {$CFG->prefix}context pctx ON cm.course=pctx.instanceid
5343 WHERE ctx.contextlevel=".CONTEXT_MODULE."
5344 AND pctx.contextlevel=".CONTEXT_COURSE."
5345 AND NOT EXISTS (SELECT 'x'
5346 FROM {$CFG->prefix}context_temp temp
5347 WHERE temp.id = ctx.id)
5348 $ctxemptyclause";
5349 execute_sql($sql, $feedback);
5351 execute_sql($updatesql, $feedback);
5352 execute_sql($udelsql, $feedback);
5354 // Blocks - non-pinned course-view only
5355 $sql = "INSERT INTO {$CFG->prefix}context_temp (id, path, depth)
5356 SELECT ctx.id, ".sql_concat('pctx.path', "'/'", 'ctx.id').", pctx.depth+1
5357 FROM {$CFG->prefix}context ctx
5358 JOIN {$CFG->prefix}block_instance bi ON ctx.instanceid = bi.id
5359 JOIN {$CFG->prefix}context pctx ON bi.pageid=pctx.instanceid
5360 WHERE ctx.contextlevel=".CONTEXT_BLOCK."
5361 AND pctx.contextlevel=".CONTEXT_COURSE."
5362 AND bi.pagetype='course-view'
5363 AND NOT EXISTS (SELECT 'x'
5364 FROM {$CFG->prefix}context_temp temp
5365 WHERE temp.id = ctx.id)
5366 $ctxemptyclause";
5367 execute_sql($sql, $feedback);
5369 execute_sql($updatesql, $feedback);
5370 execute_sql($udelsql, $feedback);
5372 // Blocks - others
5373 $sql = "UPDATE {$CFG->prefix}context
5374 SET depth=2, path=".sql_concat("'$base/'", 'id')."
5375 WHERE contextlevel=".CONTEXT_BLOCK."
5376 AND EXISTS (SELECT 'x'
5377 FROM {$CFG->prefix}block_instance bi
5378 WHERE bi.id = {$CFG->prefix}context.instanceid
5379 AND bi.pagetype!='course-view')
5380 $emptyclause ";
5381 execute_sql($sql, $feedback);
5383 // User
5384 $sql = "UPDATE {$CFG->prefix}context
5385 SET depth=2, path=".sql_concat("'$base/'", 'id')."
5386 WHERE contextlevel=".CONTEXT_USER."
5387 AND EXISTS (SELECT 'x'
5388 FROM {$CFG->prefix}user u
5389 WHERE u.id = {$CFG->prefix}context.instanceid)
5390 $emptyclause ";
5391 execute_sql($sql, $feedback);
5393 // Personal TODO
5395 //TODO: fix group contexts
5397 // reset static course cache - it might have incorrect cached data
5398 global $context_cache, $context_cache_id;
5399 $context_cache = array();
5400 $context_cache_id = array();
5405 * Update the path field of the context and
5406 * all the dependent subcontexts that follow
5407 * the move.
5409 * The most important thing here is to be as
5410 * DB efficient as possible. This op can have a
5411 * massive impact in the DB.
5413 * @param obj current context obj
5414 * @param obj newparent new parent obj
5417 function context_moved($context, $newparent) {
5418 global $CFG;
5420 $frompath = $context->path;
5421 $newpath = $newparent->path . '/' . $context->id;
5423 $setdepth = '';
5424 if (($newparent->depth +1) != $context->depth) {
5425 $setdepth = ", depth= depth + ({$newparent->depth} - {$context->depth}) + 1";
5427 $sql = "UPDATE {$CFG->prefix}context
5428 SET path='$newpath'
5429 $setdepth
5430 WHERE path='$frompath'";
5431 execute_sql($sql,false);
5433 $len = strlen($frompath);
5434 $sql = "UPDATE {$CFG->prefix}context
5435 SET path = ".sql_concat("'$newpath'", 'SUBSTR(path, '.$len.' +1)')."
5436 $setdepth
5437 WHERE path LIKE '{$frompath}/%'";
5438 execute_sql($sql,false);
5440 mark_context_dirty($frompath);
5441 mark_context_dirty($newpath);
5446 * Turn the ctx* fields in an objectlike record
5447 * into a context subobject. This allows
5448 * us to SELECT from major tables JOINing with
5449 * context at no cost, saving a ton of context
5450 * lookups...
5452 function make_context_subobj($rec) {
5453 $ctx = new StdClass;
5454 $ctx->id = $rec->ctxid; unset($rec->ctxid);
5455 $ctx->path = $rec->ctxpath; unset($rec->ctxpath);
5456 $ctx->depth = $rec->ctxdepth; unset($rec->ctxdepth);
5457 $ctx->contextlevel = $rec->ctxlevel; unset($rec->ctxlevel);
5458 $ctx->instanceid = $rec->id;
5460 $rec->context = $ctx;
5461 return $rec;
5465 * Fetch recent dirty contexts to know cheaply whether our $USER->access
5466 * is stale and needs to be reloaded.
5468 * Uses cache_flags
5469 * @param int $time
5470 * @return array of dirty contexts
5472 function get_dirty_contexts($time) {
5473 return get_cache_flags('accesslib/dirtycontexts', $time-2);
5477 * Mark a context as dirty (with timestamp)
5478 * so as to force reloading of the context.
5479 * @param string $path context path
5481 function mark_context_dirty($path) {
5482 global $CFG, $DIRTYCONTEXTS;
5483 // only if it is a non-empty string
5484 if (is_string($path) && $path !== '') {
5485 set_cache_flag('accesslib/dirtycontexts', $path, 1, time()+$CFG->sessiontimeout);
5486 if (isset($DIRTYCONTEXTS)) {
5487 $DIRTYCONTEXTS[$path] = 1;
5493 * Will walk the contextpath to answer whether
5494 * the contextpath is dirty
5496 * @param array $contexts array of strings
5497 * @param obj/array dirty contexts from get_dirty_contexts()
5498 * @return bool
5500 function is_contextpath_dirty($pathcontexts, $dirty) {
5501 $path = '';
5502 foreach ($pathcontexts as $ctx) {
5503 $path = $path.'/'.$ctx;
5504 if (isset($dirty[$path])) {
5505 return true;
5508 return false;
5513 * switch role order (used in admin/roles/manage.php)
5515 * @param int $first id of role to move down
5516 * @param int $second id of role to move up
5518 * @return bool success or failure
5520 function switch_roles($first, $second) {
5521 $status = true;
5522 //first find temorary sortorder number
5523 $tempsort = count_records('role') + 3;
5524 while (get_record('role','sortorder', $tempsort)) {
5525 $tempsort += 3;
5528 $r1 = new object();
5529 $r1->id = $first->id;
5530 $r1->sortorder = $tempsort;
5531 $r2 = new object();
5532 $r2->id = $second->id;
5533 $r2->sortorder = $first->sortorder;
5535 if (!update_record('role', $r1)) {
5536 debugging("Can not update role with ID $r1->id!");
5537 $status = false;
5540 if (!update_record('role', $r2)) {
5541 debugging("Can not update role with ID $r2->id!");
5542 $status = false;
5545 $r1->sortorder = $second->sortorder;
5546 if (!update_record('role', $r1)) {
5547 debugging("Can not update role with ID $r1->id!");
5548 $status = false;
5551 return $status;
5555 * duplicates all the base definitions of a role
5557 * @param object $sourcerole role to copy from
5558 * @param int $targetrole id of role to copy to
5560 * @return void
5562 function role_cap_duplicate($sourcerole, $targetrole) {
5563 global $CFG;
5564 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
5565 $caps = get_records_sql("SELECT * FROM {$CFG->prefix}role_capabilities
5566 WHERE roleid = $sourcerole->id
5567 AND contextid = $systemcontext->id");
5568 // adding capabilities
5569 foreach ($caps as $cap) {
5570 unset($cap->id);
5571 $cap->roleid = $targetrole;
5572 insert_record('role_capabilities', $cap);