52c480d8fa52cc908bf799307366540032a93591
[moodle.git] / lib / accesslib.php
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
18 /**
19  * This file contains functions for managing user access
20  *
21  * <b>Public API vs internals</b>
22  *
23  * General users probably only care about
24  *
25  * Context handling
26  * - get_context_instance()
27  * - get_context_instance_by_id()
28  * - get_parent_contexts()
29  * - get_child_contexts()
30  *
31  * Whether the user can do something...
32  * - has_capability()
33  * - has_any_capability()
34  * - has_all_capabilities()
35  * - require_capability()
36  * - require_login() (from moodlelib)
37  *
38  * What courses has this user access to?
39  * - get_user_courses_bycap()
40  *
41  * What users can do X in this context?
42  * - get_users_by_capability()
43  *
44  * Enrol/unenrol
45  * - enrol_into_course()
46  * - role_assign()/role_unassign()
47  *
48  *
49  * Advanced use
50  * - load_all_capabilities()
51  * - reload_all_capabilities()
52  * - has_capability_in_accessdata()
53  * - is_siteadmin()
54  * - get_user_access_sitewide()
55  * - load_subcontext()
56  * - get_role_access_bycontext()
57  *
58  * <b>Name conventions</b>
59  *
60  * "ctx" means context
61  *
62  * <b>accessdata</b>
63  *
64  * Access control data is held in the "accessdata" array
65  * which - for the logged-in user, will be in $USER->access
66  *
67  * For other users can be generated and passed around (but may also be cached
68  * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser.
69  *
70  * $accessdata is a multidimensional array, holding
71  * role assignments (RAs), role-capabilities-perm sets
72  * (role defs) and a list of courses we have loaded
73  * data for.
74  *
75  * Things are keyed on "contextpaths" (the path field of
76  * the context table) for fast walking up/down the tree.
77  * <code>
78  * $accessdata[ra][$contextpath]= array($roleid)
79  *                [$contextpath]= array($roleid)
80  *                [$contextpath]= array($roleid)
81  * </code>
82  *
83  * Role definitions are stored like this
84  * (no cap merge is done - so it's compact)
85  *
86  * <code>
87  * $accessdata[rdef][$contextpath:$roleid][mod/forum:viewpost] = 1
88  *                                        [mod/forum:editallpost] = -1
89  *                                        [mod/forum:startdiscussion] = -1000
90  * </code>
91  *
92  * See how has_capability_in_accessdata() walks up/down the tree.
93  *
94  * Normally - specially for the logged-in user, we only load
95  * rdef and ra down to the course level, but not below. This
96  * keeps accessdata small and compact. Below-the-course ra/rdef
97  * are loaded as needed. We keep track of which courses we
98  * have loaded ra/rdef in
99  * <code>
100  * $accessdata[loaded] = array($contextpath, $contextpath)
101  * </code>
102  *
103  * <b>Stale accessdata</b>
104  *
105  * For the logged-in user, accessdata is long-lived.
106  *
107  * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
108  * context paths affected by changes. Any check at-or-below
109  * a dirty context will trigger a transparent reload of accessdata.
110  *
111  * Changes at the system level will force the reload for everyone.
112  *
113  * <b>Default role caps</b>
114  * The default role assignment is not in the DB, so we
115  * add it manually to accessdata.
116  *
117  * This means that functions that work directly off the
118  * DB need to ensure that the default role caps
119  * are dealt with appropriately.
120  *
121  * @package    core
122  * @subpackage role
123  * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
124  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
125  */
127 defined('MOODLE_INTERNAL') || die();
129 /** permission definitions */
130 define('CAP_INHERIT', 0);
131 /** permission definitions */
132 define('CAP_ALLOW', 1);
133 /** permission definitions */
134 define('CAP_PREVENT', -1);
135 /** permission definitions */
136 define('CAP_PROHIBIT', -1000);
138 /** context definitions */
139 define('CONTEXT_SYSTEM', 10);
140 /** context definitions */
141 define('CONTEXT_USER', 30);
142 /** context definitions */
143 define('CONTEXT_COURSECAT', 40);
144 /** context definitions */
145 define('CONTEXT_COURSE', 50);
146 /** context definitions */
147 define('CONTEXT_MODULE', 70);
148 /** context definitions */
149 define('CONTEXT_BLOCK', 80);
151 /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
152 define('RISK_MANAGETRUST', 0x0001);
153 /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
154 define('RISK_CONFIG',      0x0002);
155 /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
156 define('RISK_XSS',         0x0004);
157 /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
158 define('RISK_PERSONAL',    0x0008);
159 /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
160 define('RISK_SPAM',        0x0010);
161 /** capability risks - see {@link http://docs.moodle.org/en/Development:Hardening_new_Roles_system} */
162 define('RISK_DATALOSS',    0x0020);
164 /** rolename displays - the name as defined in the role definition */
165 define('ROLENAME_ORIGINAL', 0);
166 /** rolename displays - the name as defined by a role alias */
167 define('ROLENAME_ALIAS', 1);
168 /** rolename displays - Both, like this:  Role alias (Original)*/
169 define('ROLENAME_BOTH', 2);
170 /** rolename displays - the name as defined in the role definition and the shortname in brackets*/
171 define('ROLENAME_ORIGINALANDSHORT', 3);
172 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing*/
173 define('ROLENAME_ALIAS_RAW', 4);
174 /** rolename displays - the name is simply short role name*/
175 define('ROLENAME_SHORT', 5);
177 /** size limit for context cache */
178 if (!defined('MAX_CONTEXT_CACHE_SIZE')) {
179     define('MAX_CONTEXT_CACHE_SIZE', 5000);
182 /**
183  * Although this looks like a global variable, it isn't really.
184  *
185  * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
186  * It is used to cache various bits of data between function calls for performance reasons.
187  * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
188  * as methods of a class, instead of functions.
189  *
190  * @global stdClass $ACCESSLIB_PRIVATE
191  * @name $ACCESSLIB_PRIVATE
192  */
193 global $ACCESSLIB_PRIVATE;
194 $ACCESSLIB_PRIVATE = new stdClass;
195 $ACCESSLIB_PRIVATE->contexts = array(); // Cache of context objects by level and instance
196 $ACCESSLIB_PRIVATE->contextsbyid = array(); // Cache of context objects by id
197 $ACCESSLIB_PRIVATE->systemcontext = NULL; // Used in get_system_context
198 $ACCESSLIB_PRIVATE->dirtycontexts = NULL; // Dirty contexts cache
199 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the $accessdata structure for users other than $USER
200 $ACCESSLIB_PRIVATE->roledefinitions = array(); // role definitions cache - helps a lot with mem usage in cron
201 $ACCESSLIB_PRIVATE->croncache = array(); // Used in get_role_access
202 $ACCESSLIB_PRIVATE->preloadedcourses = array(); // Used in preload_course_contexts.
203 $ACCESSLIB_PRIVATE->capabilities = NULL; // detailed information about the capabilities
205 /**
206  * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
207  *
208  * This method should ONLY BE USED BY UNIT TESTS. It clears all of
209  * accesslib's private caches. You need to do this before setting up test data,
210  * and also at the end of the tests.
211  * @global object
212  * @global object
213  * @global object
214  */
215 function accesslib_clear_all_caches_for_unit_testing() {
216     global $UNITTEST, $USER, $ACCESSLIB_PRIVATE;
217     if (empty($UNITTEST->running)) {
218         throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
219     }
220     $ACCESSLIB_PRIVATE->contexts = array();
221     $ACCESSLIB_PRIVATE->contextsbyid = array();
222     $ACCESSLIB_PRIVATE->systemcontext = NULL;
223     $ACCESSLIB_PRIVATE->dirtycontexts = NULL;
224     $ACCESSLIB_PRIVATE->accessdatabyuser = array();
225     $ACCESSLIB_PRIVATE->roledefinitions = array();
226     $ACCESSLIB_PRIVATE->croncache = array();
227     $ACCESSLIB_PRIVATE->preloadedcourses = array();
228     $ACCESSLIB_PRIVATE->capabilities = NULL;
230     unset($USER->access);
233 /**
234  * Private function. Add a context object to accesslib's caches.
235  * @global object
236  * @param object $context
237  */
238 function cache_context($context) {
239     global $ACCESSLIB_PRIVATE;
241     // If there are too many items in the cache already, remove items until
242     // there is space
243     while (count($ACCESSLIB_PRIVATE->contextsbyid) >= MAX_CONTEXT_CACHE_SIZE) {
244         $first = reset($ACCESSLIB_PRIVATE->contextsbyid);
245         unset($ACCESSLIB_PRIVATE->contextsbyid[$first->id]);
246         unset($ACCESSLIB_PRIVATE->contexts[$first->contextlevel][$first->instanceid]);
247     }
249     $ACCESSLIB_PRIVATE->contexts[$context->contextlevel][$context->instanceid] = $context;
250     $ACCESSLIB_PRIVATE->contextsbyid[$context->id] = $context;
253 /**
254  * This is really slow!!! do not use above course context level
255  *
256  * @global object
257  * @param int $roleid
258  * @param object $context
259  * @return array
260  */
261 function get_role_context_caps($roleid, $context) {
262     global $DB;
264     //this is really slow!!!! - do not use above course context level!
265     $result = array();
266     $result[$context->id] = array();
268     // first emulate the parent context capabilities merging into context
269     $searchcontexts = array_reverse(get_parent_contexts($context));
270     array_push($searchcontexts, $context->id);
271     foreach ($searchcontexts as $cid) {
272         if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
273             foreach ($capabilities as $cap) {
274                 if (!array_key_exists($cap->capability, $result[$context->id])) {
275                     $result[$context->id][$cap->capability] = 0;
276                 }
277                 $result[$context->id][$cap->capability] += $cap->permission;
278             }
279         }
280     }
282     // now go through the contexts bellow given context
283     $searchcontexts = array_keys(get_child_contexts($context));
284     foreach ($searchcontexts as $cid) {
285         if ($capabilities = $DB->get_records('role_capabilities', array('roleid'=>$roleid, 'contextid'=>$cid))) {
286             foreach ($capabilities as $cap) {
287                 if (!array_key_exists($cap->contextid, $result)) {
288                     $result[$cap->contextid] = array();
289                 }
290                 $result[$cap->contextid][$cap->capability] = $cap->permission;
291             }
292         }
293     }
295     return $result;
298 /**
299  * Gets the accessdata for role "sitewide" (system down to course)
300  *
301  * @global object
302  * @global object
303  * @param int $roleid
304  * @param array $accessdata defaults to NULL
305  * @return array
306  */
307 function get_role_access($roleid, $accessdata=NULL) {
309     global $CFG, $DB;
311     /* Get it in 1 cheap DB query...
312      * - relevant role caps at the root and down
313      *   to the course level - but not below
314      */
315     if (is_null($accessdata)) {
316         $accessdata           = array(); // named list
317         $accessdata['ra']     = array();
318         $accessdata['rdef']   = array();
319         $accessdata['loaded'] = array();
320     }
322     //
323     // Overrides for the role IN ANY CONTEXTS
324     // down to COURSE - not below -
325     //
326     $sql = "SELECT ctx.path,
327                    rc.capability, rc.permission
328               FROM {context} ctx
329               JOIN {role_capabilities} rc
330                    ON rc.contextid=ctx.id
331              WHERE rc.roleid = ?
332                    AND ctx.contextlevel <= ".CONTEXT_COURSE."
333           ORDER BY ctx.depth, ctx.path";
334     $params = array($roleid);
336     // we need extra caching in CLI scripts and cron
337     if (CLI_SCRIPT) {
338         global $ACCESSLIB_PRIVATE;
340         if (!isset($ACCESSLIB_PRIVATE->croncache[$roleid])) {
341             $ACCESSLIB_PRIVATE->croncache[$roleid] = array();
342             if ($rs = $DB->get_recordset_sql($sql, $params)) {
343                 foreach ($rs as $rd) {
344                     $ACCESSLIB_PRIVATE->croncache[$roleid][] = $rd;
345                 }
346                 $rs->close();
347             }
348         }
350         foreach ($ACCESSLIB_PRIVATE->croncache[$roleid] as $rd) {
351             $k = "{$rd->path}:{$roleid}";
352             $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
353         }
355     } else {
356         if ($rs = $DB->get_recordset_sql($sql, $params)) {
357             foreach ($rs as $rd) {
358                 $k = "{$rd->path}:{$roleid}";
359                 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
360             }
361             unset($rd);
362             $rs->close();
363         }
364     }
366     return $accessdata;
369 /**
370  * Gets the accessdata for role "sitewide" (system down to course)
371  *
372  * @global object
373  * @global object
374  * @param int $roleid
375  * @param array $accessdata defaults to NULL
376  * @return array
377  */
378 function get_default_frontpage_role_access($roleid, $accessdata=NULL) {
380     global $CFG, $DB;
382     $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
383     $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
385     //
386     // Overrides for the role in any contexts related to the course
387     //
388     $sql = "SELECT ctx.path,
389                    rc.capability, rc.permission
390               FROM {context} ctx
391               JOIN {role_capabilities} rc
392                    ON rc.contextid=ctx.id
393              WHERE rc.roleid = ?
394                    AND (ctx.id = ".SYSCONTEXTID." OR ctx.path LIKE ?)
395                    AND ctx.contextlevel <= ".CONTEXT_COURSE."
396           ORDER BY ctx.depth, ctx.path";
397     $params = array($roleid, "$base/%");
399     if ($rs = $DB->get_recordset_sql($sql, $params)) {
400         foreach ($rs as $rd) {
401             $k = "{$rd->path}:{$roleid}";
402             $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
403         }
404         unset($rd);
405         $rs->close();
406     }
408     return $accessdata;
412 /**
413  * Get the default guest role
414  *
415  * @global object
416  * @global object
417  * @return object role
418  */
419 function get_guest_role() {
420     global $CFG, $DB;
422     if (empty($CFG->guestroleid)) {
423         if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
424             $guestrole = array_shift($roles);   // Pick the first one
425             set_config('guestroleid', $guestrole->id);
426             return $guestrole;
427         } else {
428             debugging('Can not find any guest role!');
429             return false;
430         }
431     } else {
432         if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
433             return $guestrole;
434         } else {
435             //somebody is messing with guest roles, remove incorrect setting and try to find a new one
436             set_config('guestroleid', '');
437             return get_guest_role();
438         }
439     }
442 /**
443  * Check whether a user has a particular capability in a given context.
444  *
445  * For example::
446  *      $context = get_context_instance(CONTEXT_MODULE, $cm->id);
447  *      has_capability('mod/forum:replypost',$context)
448  *
449  * By default checks the capabilities of the current user, but you can pass a
450  * different userid. By default will return true for admin users, but you can override that with the fourth argument.
451  *
452  * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
453  * or capabilities with XSS, config or data loss risks.
454  *
455  * @param string $capability the name of the capability to check. For example mod/forum:view
456  * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
457  * @param integer|object $user A user id or object. By default (NULL) checks the permissions of the current user.
458  * @param boolean $doanything If false, ignores effect of admin role assignment
459  * @return boolean true if the user has this capability. Otherwise false.
460  */
461 function has_capability($capability, $context, $user = NULL, $doanything=true) {
462     global $USER, $CFG, $DB, $SCRIPT, $ACCESSLIB_PRIVATE;
464     if (during_initial_install()) {
465         if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cliupgrade.php") {
466             // we are in an installer - roles can not work yet
467             return true;
468         } else {
469             return false;
470         }
471     }
473     if (strpos($capability, 'moodle/legacy:') === 0) {
474         throw new coding_exception('Legacy capabilities can not be used any more!');
475     }
477     // the original $CONTEXT here was hiding serious errors
478     // for security reasons do not reuse previous context
479     if (empty($context)) {
480         debugging('Incorrect context specified');
481         return false;
482     }
483     if (!is_bool($doanything)) {
484         throw new coding_exception('Capability parameter "doanything" is wierd ("'.$doanything.'"). This has to be fixed in code.');
485     }
487     // make sure there is a real user specified
488     if ($user === NULL) {
489         $userid = !empty($USER->id) ? $USER->id : 0;
490     } else {
491         $userid = !empty($user->id) ? $user->id : $user;
492     }
494     // capability must exist
495     if (!$capinfo = get_capability_info($capability)) {
496         debugging('Capability "'.$capability.'" was not found! This should be fixed in code.');
497         return false;
498     }
499     // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
500     if (($capinfo->captype === 'write') or ((int)$capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
501         if (isguestuser($userid) or $userid == 0) {
502             return false;
503         }
504     }
506     if (is_null($context->path) or $context->depth == 0) {
507         //this should not happen
508         $contexts = array(SYSCONTEXTID, $context->id);
509         $context->path = '/'.SYSCONTEXTID.'/'.$context->id;
510         debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()', DEBUG_DEVELOPER);
512     } else {
513         $contexts = explode('/', $context->path);
514         array_shift($contexts);
515     }
517     if (CLI_SCRIPT && !isset($USER->access)) {
518         // In cron, some modules setup a 'fake' $USER,
519         // ensure we load the appropriate accessdata.
520         if (isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
521             $ACCESSLIB_PRIVATE->dirtycontexts = NULL; //load fresh dirty contexts
522         } else {
523             load_user_accessdata($userid);
524             $ACCESSLIB_PRIVATE->dirtycontexts = array();
525         }
526         $USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
528     } else if (isset($USER->id) && ($USER->id == $userid) && !isset($USER->access)) {
529         // caps not loaded yet - better to load them to keep BC with 1.8
530         // not-logged-in user or $USER object set up manually first time here
531         load_all_capabilities();
532         $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // reset the cache for other users too, the dirty contexts are empty now
533         $ACCESSLIB_PRIVATE->roledefinitions = array();
534     }
536     // Load dirty contexts list if needed
537     if (!isset($ACCESSLIB_PRIVATE->dirtycontexts)) {
538         if (isset($USER->access['time'])) {
539             $ACCESSLIB_PRIVATE->dirtycontexts = get_dirty_contexts($USER->access['time']);
540         }
541         else {
542             $ACCESSLIB_PRIVATE->dirtycontexts = array();
543         }
544     }
546     // Careful check for staleness...
547     if (count($ACCESSLIB_PRIVATE->dirtycontexts) !== 0 and is_contextpath_dirty($contexts, $ACCESSLIB_PRIVATE->dirtycontexts)) {
548         // reload all capabilities - preserving loginas, roleswitches, etc
549         // and then cleanup any marks of dirtyness... at least from our short
550         // term memory! :-)
551         $ACCESSLIB_PRIVATE->accessdatabyuser = array();
552         $ACCESSLIB_PRIVATE->roledefinitions = array();
554         if (CLI_SCRIPT) {
555             load_user_accessdata($userid);
556             $USER->access = $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
557             $ACCESSLIB_PRIVATE->dirtycontexts = array();
559         } else {
560             reload_all_capabilities();
561         }
562     }
564     // Find out if user is admin - it is not possible to override the doanything in any way
565     // and it is not possible to switch to admin role either.
566     if ($doanything) {
567         if (is_siteadmin($userid)) {
568             if ($userid != $USER->id) {
569                 return true;
570             }
571             // make sure switchrole is not used in this context
572             if (empty($USER->access['rsw'])) {
573                 return true;
574             }
575             $parts = explode('/', trim($context->path, '/'));
576             $path = '';
577             $switched = false;
578             foreach ($parts as $part) {
579                 $path .= '/' . $part;
580                 if (!empty($USER->access['rsw'][$path])) {
581                     $switched = true;
582                     break;
583                 }
584             }
585             if (!$switched) {
586                 return true;
587             }
588             //ok, admin switched role in this context, let's use normal access control rules
589         }
590     }
592     // divulge how many times we are called
593     //// error_log("has_capability: id:{$context->id} path:{$context->path} userid:$userid cap:$capability");
595     if (isset($USER->id) && ($USER->id == $userid)) { // we must accept strings and integers in $userid
596         //
597         // For the logged in user, we have $USER->access
598         // which will have all RAs and caps preloaded for
599         // course and above contexts.
600         //
601         // Contexts below courses && contexts that do not
602         // hang from courses are loaded into $USER->access
603         // on demand, and listed in $USER->access[loaded]
604         //
605         if ($context->contextlevel <= CONTEXT_COURSE) {
606             // Course and above are always preloaded
607             return has_capability_in_accessdata($capability, $context, $USER->access);
608         }
609         // Load accessdata for below-the-course contexts
610         if (!path_inaccessdata($context->path,$USER->access)) {
611             // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
612             // $bt = debug_backtrace();
613             // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
614             load_subcontext($USER->id, $context, $USER->access);
615         }
616         return has_capability_in_accessdata($capability, $context, $USER->access);
617     }
619     if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
620         load_user_accessdata($userid);
621     }
623     if ($context->contextlevel <= CONTEXT_COURSE) {
624         // Course and above are always preloaded
625         return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
626     }
627     // Load accessdata for below-the-course contexts as needed
628     if (!path_inaccessdata($context->path, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
629         // error_log("loading access for context {$context->path} for $capability at {$context->contextlevel} {$context->id}");
630         // $bt = debug_backtrace();
631         // error_log("bt {$bt[0]['file']} {$bt[0]['line']}");
632         load_subcontext($userid, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
633     }
634     return has_capability_in_accessdata($capability, $context, $ACCESSLIB_PRIVATE->accessdatabyuser[$userid]);
637 /**
638  * Check if the user has any one of several capabilities from a list.
639  *
640  * This is just a utility method that calls has_capability in a loop. Try to put
641  * the capabilities that most users are likely to have first in the list for best
642  * performance.
643  *
644  * There are probably tricks that could be done to improve the performance here, for example,
645  * check the capabilities that are already cached first.
646  *
647  * @see has_capability()
648  * @param array $capabilities an array of capability names.
649  * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
650  * @param integer $userid A user id. By default (NULL) checks the permissions of the current user.
651  * @param boolean $doanything If false, ignore effect of admin role assignment
652  * @return boolean true if the user has any of these capabilities. Otherwise false.
653  */
654 function has_any_capability($capabilities, $context, $userid=NULL, $doanything=true) {
655     if (!is_array($capabilities)) {
656         debugging('Incorrect $capabilities parameter in has_any_capabilities() call - must be an array');
657         return false;
658     }
659     foreach ($capabilities as $capability) {
660         if (has_capability($capability, $context, $userid, $doanything)) {
661             return true;
662         }
663     }
664     return false;
667 /**
668  * Check if the user has all the capabilities in a list.
669  *
670  * This is just a utility method that calls has_capability in a loop. Try to put
671  * the capabilities that fewest users are likely to have first in the list for best
672  * performance.
673  *
674  * There are probably tricks that could be done to improve the performance here, for example,
675  * check the capabilities that are already cached first.
676  *
677  * @see has_capability()
678  * @param array $capabilities an array of capability names.
679  * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
680  * @param integer $userid A user id. By default (NULL) checks the permissions of the current user.
681  * @param boolean $doanything If false, ignore effect of admin role assignment
682  * @return boolean true if the user has all of these capabilities. Otherwise false.
683  */
684 function has_all_capabilities($capabilities, $context, $userid=NULL, $doanything=true) {
685     if (!is_array($capabilities)) {
686         debugging('Incorrect $capabilities parameter in has_all_capabilities() call - must be an array');
687         return false;
688     }
689     foreach ($capabilities as $capability) {
690         if (!has_capability($capability, $context, $userid, $doanything)) {
691             return false;
692         }
693     }
694     return true;
697 /**
698  * Check if the user is an admin at the site level.
699  *
700  * Please note that use of proper capabilities is always encouraged,
701  * this function is supposed to be used from core or for temporary hacks.
702  *
703  * @param   int|object  $user_or_id user id or user object
704  * @returns bool true if user is one of the administrators, false otherwise
705  */
706 function is_siteadmin($user_or_id = NULL) {
707     global $CFG, $USER;
709     if ($user_or_id === NULL) {
710         $user_or_id = $USER;
711     }
713     if (empty($user_or_id)) {
714         return false;
715     }
716     if (!empty($user_or_id->id)) {
717         // we support
718         $userid = $user_or_id->id;
719     } else {
720         $userid = $user_or_id;
721     }
723     $siteadmins = explode(',', $CFG->siteadmins);
724     return in_array($userid, $siteadmins);
727 /**
728  * Returns true if user has at least one role assign
729  * of 'coursecontact' role (is potentially listed in some course descriptions).
730  * @param $userid
731  * @return unknown_type
732  */
733 function has_coursecontact_role($userid) {
734     global $DB, $CFG;
736     if (empty($CFG->coursecontact)) {
737         return false;
738     }
739     $sql = "SELECT 1
740               FROM {role_assignments}
741              WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
742     return $DB->record_exists_sql($sql, array('userid'=>$userid));
745 /**
746  * @param string $path
747  * @return string
748  */
749 function get_course_from_path($path) {
750     // assume that nothing is more than 1 course deep
751     if (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
752         return $matches[1];
753     }
754     return false;
757 /**
758  * @param string $path
759  * @param array $accessdata
760  * @return bool
761  */
762 function path_inaccessdata($path, $accessdata) {
763     if (empty($accessdata['loaded'])) {
764         return false;
765     }
767     // assume that contexts hang from sys or from a course
768     // this will only work well with stuff that hangs from a course
769     if (in_array($path, $accessdata['loaded'], true)) {
770             // error_log("found it!");
771         return true;
772     }
773     $base = '/' . SYSCONTEXTID;
774     while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
775         $path = $matches[1];
776         if ($path === $base) {
777             return false;
778         }
779         if (in_array($path, $accessdata['loaded'], true)) {
780             return true;
781         }
782     }
783     return false;
786 /**
787  * Does the user have a capability to do something?
788  *
789  * Walk the accessdata array and return true/false.
790  * Deals with prohibits, roleswitching, aggregating
791  * capabilities, etc.
792  *
793  * The main feature of here is being FAST and with no
794  * side effects.
795  *
796  * Notes:
797  *
798  * Switch Roles exits early
799  * ------------------------
800  * cap checks within a switchrole need to exit early
801  * in our bottom up processing so they don't "see" that
802  * there are real RAs that can do all sorts of things.
803  *
804  * Switch Role merges with default role
805  * ------------------------------------
806  * If you are a teacher in course X, you have at least
807  * teacher-in-X + defaultloggedinuser-sitewide. So in the
808  * course you'll have techer+defaultloggedinuser.
809  * We try to mimic that in switchrole.
810  *
811  * Permission evaluation
812  * ---------------------
813  * Originally there was an extremely complicated way
814  * to determine the user access that dealt with
815  * "locality" or role assignments and role overrides.
816  * Now we simply evaluate access for each role separately
817  * and then verify if user has at least one role with allow
818  * and at the same time no role with prohibit.
819  *
820  * @param string $capability
821  * @param object $context
822  * @param array $accessdata
823  * @return bool
824  */
825 function has_capability_in_accessdata($capability, $context, array $accessdata) {
826     global $CFG;
828     if (empty($context->id)) {
829         throw new coding_exception('Invalid context specified');
830     }
832     // Build $paths as a list of current + all parent "paths" with order bottom-to-top
833     $contextids = explode('/', trim($context->path, '/'));
834     $paths = array($context->path);
835     while ($contextids) {
836         array_pop($contextids);
837         $paths[] = '/' . implode('/', $contextids);
838     }
839     unset($contextids);
841     $roles = array();
842     $switchedrole = false;
844     // Find out if role switched
845     if (!empty($accessdata['rsw'])) {
846         // From the bottom up...
847         foreach ($paths as $path) {
848             if (isset($accessdata['rsw'][$path])) {
849                 // Found a switchrole assignment - check for that role _plus_ the default user role
850                 $roles = array($accessdata['rsw'][$path]=>NULL, $CFG->defaultuserroleid=>NULL);
851                 $switchedrole = true;
852                 break;
853             }
854         }
855     }
857     if (!$switchedrole) {
858         // get all users roles in this context and above
859         foreach ($paths as $path) {
860             if (isset($accessdata['ra'][$path])) {
861                 foreach ($accessdata['ra'][$path] as $roleid) {
862                     $roles[$roleid] = NULL;
863                 }
864             }
865         }
866     }
868     // Now find out what access is given to each role, going bottom-->up direction
869     foreach ($roles as $roleid => $ignored) {
870         foreach ($paths as $path) {
871             if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
872                 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
873                 if ($perm === CAP_PROHIBIT or is_null($roles[$roleid])) {
874                     $roles[$roleid] = $perm;
875                 }
876             }
877         }
878     }
879     // any CAP_PROHIBIT found means no permission for the user
880     if (array_search(CAP_PROHIBIT, $roles) !== false) {
881         return false;
882     }
884     // at least one CAP_ALLOW means the user has a permission
885     return (array_search(CAP_ALLOW, $roles) !== false);
888 /**
889  * @param object $context
890  * @param array $accessdata
891  * @return array
892  */
893 function aggregate_roles_from_accessdata($context, $accessdata) {
895     $path = $context->path;
897     // build $contexts as a list of "paths" of the current
898     // contexts and parents with the order top-to-bottom
899     $contexts = array($path);
900     while (preg_match('!^(/.+)/\d+$!', $path, $matches)) {
901         $path = $matches[1];
902         array_unshift($contexts, $path);
903     }
905     $cc = count($contexts);
907     $roles = array();
908     // From the bottom up...
909     for ($n=$cc-1;$n>=0;$n--) {
910         $ctxp = $contexts[$n];
911         if (isset($accessdata['ra'][$ctxp]) && count($accessdata['ra'][$ctxp])) {
912             // Found assignments on this leaf
913             $addroles = $accessdata['ra'][$ctxp];
914             $roles    = array_merge($roles, $addroles);
915         }
916     }
918     return array_unique($roles);
921 /**
922  * A convenience function that tests has_capability, and displays an error if
923  * the user does not have that capability.
924  *
925  * NOTE before Moodle 2.0, this function attempted to make an appropriate
926  * require_login call before checking the capability. This is no longer the case.
927  * You must call require_login (or one of its variants) if you want to check the
928  * user is logged in, before you call this function.
929  *
930  * @see has_capability()
931  *
932  * @param string $capability the name of the capability to check. For example mod/forum:view
933  * @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
934  * @param integer $userid A user id. By default (NULL) checks the permissions of the current user.
935  * @param bool $doanything If false, ignore effect of admin role assignment
936  * @param string $errorstring The error string to to user. Defaults to 'nopermissions'.
937  * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
938  * @return void terminates with an error if the user does not have the given capability.
939  */
940 function require_capability($capability, $context, $userid = NULL, $doanything = true,
941                             $errormessage = 'nopermissions', $stringfile = '') {
942     if (!has_capability($capability, $context, $userid, $doanything)) {
943         throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
944     }
947 /**
948  * Get an array of courses where cap requested is available
949  * and user is enrolled, this can be relatively slow.
950  *
951  * @param string $capability - name of the capability
952  * @param array  $accessdata_ignored
953  * @param bool   $doanything_ignored
954  * @param string $sort - sorting fields - prefix each fieldname with "c."
955  * @param array  $fields - additional fields you are interested in...
956  * @param int    $limit_ignored
957  * @return array $courses - ordered array of course objects - see notes above
958  */
959 function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort='c.sortorder ASC', $fields=NULL, $limit_ignored=0) {
961     //TODO: this should be most probably deprecated
963     $courses = enrol_get_users_courses($userid, true, $fields, $sort);
964     foreach ($courses as $id=>$course) {
965         $context = get_context_instance(CONTEXT_COURSE, $id);
966         if (!has_capability($cap, $context, $userid)) {
967             unset($courses[$id]);
968         }
969     }
971     return $courses;
975 /**
976  * Return a nested array showing role assignments
977  * all relevant role capabilities for the user at
978  * site/course_category/course levels
979  *
980  * We do _not_ delve deeper than courses because the number of
981  * overrides at the module/block levels is HUGE.
982  *
983  * [ra]   => [/path/][]=roleid
984  * [rdef] => [/path/:roleid][capability]=permission
985  * [loaded] => array('/path', '/path')
986  *
987  * @global object
988  * @global object
989  * @param $userid integer - the id of the user
990  */
991 function get_user_access_sitewide($userid) {
993     global $CFG, $DB;
995     /* Get in 3 cheap DB queries...
996      * - role assignments
997      * - relevant role caps
998      *   - above and within this user's RAs
999      *   - below this user's RAs - limited to course level
1000      */
1002     $accessdata           = array(); // named list
1003     $accessdata['ra']     = array();
1004     $accessdata['rdef']   = array();
1005     $accessdata['loaded'] = array();
1007     //
1008     // Role assignments
1009     //
1010     $sql = "SELECT ctx.path, ra.roleid
1011               FROM {role_assignments} ra
1012               JOIN {context} ctx ON ctx.id=ra.contextid
1013              WHERE ra.userid = ? AND ctx.contextlevel <= ".CONTEXT_COURSE;
1014     $params = array($userid);
1015     $rs = $DB->get_recordset_sql($sql, $params);
1017     //
1018     // raparents collects paths & roles we need to walk up
1019     // the parenthood to build the rdef
1020     //
1021     $raparents = array();
1022     if ($rs) {
1023         foreach ($rs as $ra) {
1024             // RAs leafs are arrays to support multi
1025             // role assignments...
1026             if (!isset($accessdata['ra'][$ra->path])) {
1027                 $accessdata['ra'][$ra->path] = array();
1028             }
1029             array_push($accessdata['ra'][$ra->path], $ra->roleid);
1031             // Concatenate as string the whole path (all related context)
1032             // for this role. This is damn faster than using array_merge()
1033             // Will unique them later
1034             if (isset($raparents[$ra->roleid])) {
1035                 $raparents[$ra->roleid] .= $ra->path;
1036             } else {
1037                 $raparents[$ra->roleid] = $ra->path;
1038             }
1039         }
1040         unset($ra);
1041         $rs->close();
1042     }
1044     // Walk up the tree to grab all the roledefs
1045     // of interest to our user...
1046     //
1047     // NOTE: we use a series of IN clauses here - which
1048     // might explode on huge sites with very convoluted nesting of
1049     // categories... - extremely unlikely that the number of categories
1050     // and roletypes is so large that we hit the limits of IN()
1051     $clauses = '';
1052     $cparams = array();
1053     foreach ($raparents as $roleid=>$strcontexts) {
1054         $contexts = implode(',', array_unique(explode('/', trim($strcontexts, '/'))));
1055         if ($contexts ==! '') {
1056             if ($clauses) {
1057                 $clauses .= ' OR ';
1058             }
1059             $clauses .= "(roleid=? AND contextid IN ($contexts))";
1060             $cparams[] = $roleid;
1061         }
1062     }
1064     if ($clauses !== '') {
1065         $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1066                 FROM {role_capabilities} rc
1067                 JOIN {context} ctx
1068                   ON rc.contextid=ctx.id
1069                 WHERE $clauses";
1071         unset($clauses);
1072         $rs = $DB->get_recordset_sql($sql, $cparams);
1074         if ($rs) {
1075             foreach ($rs as $rd) {
1076                 $k = "{$rd->path}:{$rd->roleid}";
1077                 $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1078             }
1079             unset($rd);
1080             $rs->close();
1081         }
1082     }
1084     //
1085     // Overrides for the role assignments IN SUBCONTEXTS
1086     // (though we still do _not_ go below the course level.
1087     //
1088     // NOTE that the JOIN w sctx is with 3-way triangulation to
1089     // catch overrides to the applicable role in any subcontext, based
1090     // on the path field of the parent.
1091     //
1092     $sql = "SELECT sctx.path, ra.roleid,
1093                    ctx.path AS parentpath,
1094                    rco.capability, rco.permission
1095               FROM {role_assignments} ra
1096               JOIN {context} ctx
1097                    ON ra.contextid=ctx.id
1098               JOIN {context} sctx
1099                    ON (sctx.path LIKE " . $DB->sql_concat('ctx.path',"'/%'"). " )
1100               JOIN {role_capabilities} rco
1101                    ON (rco.roleid=ra.roleid AND rco.contextid=sctx.id)
1102              WHERE ra.userid = ?
1103                AND ctx.contextlevel <= ".CONTEXT_COURSECAT."
1104                AND sctx.contextlevel <= ".CONTEXT_COURSE."
1105           ORDER BY sctx.depth, sctx.path, ra.roleid";
1106     $params = array($userid);
1107     $rs = $DB->get_recordset_sql($sql, $params);
1108     if ($rs) {
1109         foreach ($rs as $rd) {
1110             $k = "{$rd->path}:{$rd->roleid}";
1111             $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1112         }
1113         unset($rd);
1114         $rs->close();
1115     }
1116     return $accessdata;
1119 /**
1120  * Add to the access ctrl array the data needed by a user for a given context
1121  *
1122  * @global object
1123  * @global object
1124  * @param integer $userid the id of the user
1125  * @param object $context needs path!
1126  * @param array $accessdata accessdata array
1127  */
1128 function load_subcontext($userid, $context, &$accessdata) {
1130     global $CFG, $DB;
1132     /* Get the additional RAs and relevant rolecaps
1133      * - role assignments - with role_caps
1134      * - relevant role caps
1135      *   - above this user's RAs
1136      *   - below this user's RAs - limited to course level
1137      */
1139     $base = "/" . SYSCONTEXTID;
1141     //
1142     // Replace $context with the target context we will
1143     // load. Normally, this will be a course context, but
1144     // may be a different top-level context.
1145     //
1146     // We have 3 cases
1147     //
1148     // - Course
1149     // - BLOCK/PERSON/USER/COURSE(sitecourse) hanging from SYSTEM
1150     // - BLOCK/MODULE/GROUP hanging from a course
1151     //
1152     // For course contexts, we _already_ have the RAs
1153     // but the cost of re-fetching is minimal so we don't care.
1154     //
1155     if ($context->contextlevel !== CONTEXT_COURSE
1156         && $context->path !== "$base/{$context->id}") {
1157         // Case BLOCK/MODULE/GROUP hanging from a course
1158         // Assumption: the course _must_ be our parent
1159         // If we ever see stuff nested further this needs to
1160         // change to do 1 query over the exploded path to
1161         // find out which one is the course
1162         $courses = explode('/',get_course_from_path($context->path));
1163         $targetid = array_pop($courses);
1164         $context = get_context_instance_by_id($targetid);
1166     }
1168     //
1169     // Role assignments in the context and below
1170     //
1171     $sql = "SELECT ctx.path, ra.roleid
1172               FROM {role_assignments} ra
1173               JOIN {context} ctx
1174                    ON ra.contextid=ctx.id
1175              WHERE ra.userid = ?
1176                    AND (ctx.path = ? OR ctx.path LIKE ?)
1177           ORDER BY ctx.depth, ctx.path, ra.roleid";
1178     $params = array($userid, $context->path, $context->path."/%");
1179     $rs = $DB->get_recordset_sql($sql, $params);
1181     //
1182     // Read in the RAs, preventing duplicates
1183     //
1184     if ($rs) {
1185         $localroles = array();
1186         $lastseen  = '';
1187         foreach ($rs as $ra) {
1188             if (!isset($accessdata['ra'][$ra->path])) {
1189                 $accessdata['ra'][$ra->path] = array();
1190             }
1191             // only add if is not a repeat caused
1192             // by capability join...
1193             // (this check is cheaper than in_array())
1194             if ($lastseen !== $ra->path.':'.$ra->roleid) {
1195                 $lastseen = $ra->path.':'.$ra->roleid;
1196                 array_push($accessdata['ra'][$ra->path], $ra->roleid);
1197                 array_push($localroles,           $ra->roleid);
1198             }
1199         }
1200         $rs->close();
1201     }
1203     //
1204     // Walk up and down the tree to grab all the roledefs
1205     // of interest to our user...
1206     //
1207     // NOTES
1208     // - we use IN() but the number of roles is very limited.
1209     //
1210     $courseroles    = aggregate_roles_from_accessdata($context, $accessdata);
1212     // Do we have any interesting "local" roles?
1213     $localroles = array_diff($localroles,$courseroles); // only "new" local roles
1214     $wherelocalroles='';
1215     if (count($localroles)) {
1216         // Role defs for local roles in 'higher' contexts...
1217         $contexts = substr($context->path, 1); // kill leading slash
1218         $contexts = str_replace('/', ',', $contexts);
1219         $localroleids = implode(',',$localroles);
1220         $wherelocalroles="OR (rc.roleid IN ({$localroleids})
1221                               AND ctx.id IN ($contexts))" ;
1222     }
1224     // We will want overrides for all of them
1225     $whereroles = '';
1226     if ($roleids  = implode(',',array_merge($courseroles,$localroles))) {
1227         $whereroles = "rc.roleid IN ($roleids) AND";
1228     }
1229     $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
1230               FROM {role_capabilities} rc
1231               JOIN {context} ctx
1232                    ON rc.contextid=ctx.id
1233              WHERE ($whereroles
1234                     (ctx.id=? OR ctx.path LIKE ?))
1235                    $wherelocalroles
1236           ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1237     $params = array($context->id, $context->path."/%");
1239     $newrdefs = array();
1240     if ($rs = $DB->get_recordset_sql($sql, $params)) {
1241         foreach ($rs as $rd) {
1242             $k = "{$rd->path}:{$rd->roleid}";
1243             if (!array_key_exists($k, $newrdefs)) {
1244                 $newrdefs[$k] = array();
1245             }
1246             $newrdefs[$k][$rd->capability] = $rd->permission;
1247         }
1248         $rs->close();
1249     } else {
1250         debugging('Bad SQL encountered!');
1251     }
1253     compact_rdefs($newrdefs);
1254     foreach ($newrdefs as $key=>$value) {
1255         $accessdata['rdef'][$key] =& $newrdefs[$key];
1256     }
1258     // error_log("loaded {$context->path}");
1259     $accessdata['loaded'][] = $context->path;
1262 /**
1263  * Add to the access ctrl array the data needed by a role for a given context.
1264  *
1265  * The data is added in the rdef key.
1266  *
1267  * This role-centric function is useful for role_switching
1268  * and to get an overview of what a role gets under a
1269  * given context and below...
1270  *
1271  * @global object
1272  * @global object
1273  * @param integer $roleid the id of the user
1274  * @param object $context needs path!
1275  * @param array $accessdata accessdata array NULL by default
1276  * @return array
1277  */
1278 function get_role_access_bycontext($roleid, $context, $accessdata=NULL) {
1280     global $CFG, $DB;
1282     /* Get the relevant rolecaps into rdef
1283      * - relevant role caps
1284      *   - at ctx and above
1285      *   - below this ctx
1286      */
1288     if (is_null($accessdata)) {
1289         $accessdata           = array(); // named list
1290         $accessdata['ra']     = array();
1291         $accessdata['rdef']   = array();
1292         $accessdata['loaded'] = array();
1293     }
1295     $contexts = substr($context->path, 1); // kill leading slash
1296     $contexts = str_replace('/', ',', $contexts);
1298     //
1299     // Walk up and down the tree to grab all the roledefs
1300     // of interest to our role...
1301     //
1302     // NOTE: we use an IN clauses here - which
1303     // might explode on huge sites with very convoluted nesting of
1304     // categories... - extremely unlikely that the number of nested
1305     // categories is so large that we hit the limits of IN()
1306     //
1307     $sql = "SELECT ctx.path, rc.capability, rc.permission
1308               FROM {role_capabilities} rc
1309               JOIN {context} ctx
1310                    ON rc.contextid=ctx.id
1311              WHERE rc.roleid=? AND
1312                    ( ctx.id IN ($contexts) OR
1313                     ctx.path LIKE ? )
1314           ORDER BY ctx.depth ASC, ctx.path DESC, rc.roleid ASC ";
1315     $params = array($roleid, $context->path."/%");
1317     if ($rs = $DB->get_recordset_sql($sql, $params)) {
1318         foreach ($rs as $rd) {
1319             $k = "{$rd->path}:{$roleid}";
1320             $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1321         }
1322         $rs->close();
1323     }
1325     return $accessdata;
1328 /**
1329  * Load accessdata for a user into the $ACCESSLIB_PRIVATE->accessdatabyuser global
1330  *
1331  * Used by has_capability() - but feel free
1332  * to call it if you are about to run a BIG
1333  * cron run across a bazillion users.
1334  *
1335  * @global object
1336  * @global object
1337  * @param int $userid
1338  * @return array returns ACCESSLIB_PRIVATE->accessdatabyuser[userid]
1339  */
1340 function load_user_accessdata($userid) {
1341     global $CFG, $ACCESSLIB_PRIVATE;
1343     $base = '/'.SYSCONTEXTID;
1345     $accessdata = get_user_access_sitewide($userid);
1346     $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1347     //
1348     // provide "default role" & set 'dr'
1349     //
1350     if (!empty($CFG->defaultuserroleid)) {
1351         $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1352         if (!isset($accessdata['ra'][$base])) {
1353             $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
1354         } else {
1355             array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
1356         }
1357         $accessdata['dr'] = $CFG->defaultuserroleid;
1358     }
1360     //
1361     // provide "default frontpage role"
1362     //
1363     if (!empty($CFG->defaultfrontpageroleid)) {
1364         $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1365         $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1366         if (!isset($accessdata['ra'][$base])) {
1367             $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
1368         } else {
1369             array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
1370         }
1371     }
1372     // for dirty timestamps in cron
1373     $accessdata['time'] = time();
1375     $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1376     compact_rdefs($ACCESSLIB_PRIVATE->accessdatabyuser[$userid]['rdef']);
1378     return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1381 /**
1382  * Use shared copy of role definitions stored in ACCESSLIB_PRIVATE->roledefinitions;
1383  *
1384  * @global object
1385  * @param array $rdefs array of role definitions in contexts
1386  */
1387 function compact_rdefs(&$rdefs) {
1388     global $ACCESSLIB_PRIVATE;
1390     /*
1391      * This is a basic sharing only, we could also
1392      * use md5 sums of values. The main purpose is to
1393      * reduce mem in cron jobs - many users in $ACCESSLIB_PRIVATE->accessdatabyuser array.
1394      */
1396     foreach ($rdefs as $key => $value) {
1397         if (!array_key_exists($key, $ACCESSLIB_PRIVATE->roledefinitions)) {
1398             $ACCESSLIB_PRIVATE->roledefinitions[$key] = $rdefs[$key];
1399         }
1400         $rdefs[$key] =& $ACCESSLIB_PRIVATE->roledefinitions[$key];
1401     }
1404 /**
1405  * A convenience function to completely load all the capabilities
1406  * for the current user.   This is what gets called from complete_user_login()
1407  * for example. Call it only _after_ you've setup $USER and called
1408  * check_enrolment_plugins();
1409  * @see check_enrolment_plugins()
1410  *
1411  * @global object
1412  * @global object
1413  * @global object
1414  */
1415 function load_all_capabilities() {
1416     global $CFG, $ACCESSLIB_PRIVATE;
1418     //NOTE: we can not use $USER here because it may no be linked to $_SESSION['USER'] yet!
1420     // roles not installed yet - we are in the middle of installation
1421     if (during_initial_install()) {
1422         return;
1423     }
1425     $base = '/'.SYSCONTEXTID;
1427     if (isguestuser($_SESSION['USER'])) {
1428         $guest = get_guest_role();
1430         // Load the rdefs
1431         $_SESSION['USER']->access = get_role_access($guest->id);
1432         // Put the ghost enrolment in place...
1433         $_SESSION['USER']->access['ra'][$base] = array($guest->id);
1436     } else if (!empty($_SESSION['USER']->id)) { // can not use isloggedin() yet
1438         $accessdata = get_user_access_sitewide($_SESSION['USER']->id);
1440         //
1441         // provide "default role" & set 'dr'
1442         //
1443         if (!empty($CFG->defaultuserroleid)) {
1444             $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
1445             if (!isset($accessdata['ra'][$base])) {
1446                 $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
1447             } else {
1448                 array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
1449             }
1450             $accessdata['dr'] = $CFG->defaultuserroleid;
1451         }
1453         $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
1455         //
1456         // provide "default frontpage role"
1457         //
1458         if (!empty($CFG->defaultfrontpageroleid)) {
1459             $base = '/'. SYSCONTEXTID .'/'. $frontpagecontext->id;
1460             $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
1461             if (!isset($accessdata['ra'][$base])) {
1462                 $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
1463             } else {
1464                 array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
1465             }
1466         }
1467         $_SESSION['USER']->access = $accessdata;
1469     } else if (!empty($CFG->notloggedinroleid)) {
1470         $_SESSION['USER']->access = get_role_access($CFG->notloggedinroleid);
1471         $_SESSION['USER']->access['ra'][$base] = array($CFG->notloggedinroleid);
1472     }
1474     // Timestamp to read dirty context timestamps later
1475     $_SESSION['USER']->access['time'] = time();
1476     $ACCESSLIB_PRIVATE->dirtycontexts = array();
1478     // Clear to force a refresh
1479     unset($_SESSION['USER']->mycourses);
1482 /**
1483  * A convenience function to completely reload all the capabilities
1484  * for the current user when roles have been updated in a relevant
1485  * context -- but PRESERVING switchroles and loginas.
1486  *
1487  * That is - completely transparent to the user.
1488  *
1489  * Note: rewrites $USER->access completely.
1490  *
1491  * @global object
1492  * @global object
1493  */
1494 function reload_all_capabilities() {
1495     global $USER, $DB;
1497     // error_log("reloading");
1498     // copy switchroles
1499     $sw = array();
1500     if (isset($USER->access['rsw'])) {
1501         $sw = $USER->access['rsw'];
1502         // error_log(print_r($sw,1));
1503     }
1505     unset($USER->access);
1506     unset($USER->mycourses);
1508     load_all_capabilities();
1510     foreach ($sw as $path => $roleid) {
1511         $context = $DB->get_record('context', array('path'=>$path));
1512         role_switch($roleid, $context);
1513     }
1517 /**
1518  * Adds a temp role to an accessdata array.
1519  *
1520  * Useful for the "temporary guest" access
1521  * we grant to logged-in users.
1522  *
1523  * Note - assumes a course context!
1524  *
1525  * @param object $content
1526  * @param int $roleid
1527  * @param array $accessdata
1528  * @return array Returns access data
1529  */
1530 function load_temp_role($context, $roleid, array $accessdata) {
1531     global $CFG, $DB;
1533     //
1534     // Load rdefs for the role in -
1535     // - this context
1536     // - all the parents
1537     // - and below - IOWs overrides...
1538     //
1540     // turn the path into a list of context ids
1541     $contexts = substr($context->path, 1); // kill leading slash
1542     $contexts = str_replace('/', ',', $contexts);
1544     $sql = "SELECT ctx.path, rc.capability, rc.permission
1545               FROM {context} ctx
1546               JOIN {role_capabilities} rc
1547                    ON rc.contextid=ctx.id
1548              WHERE (ctx.id IN ($contexts)
1549                     OR ctx.path LIKE ?)
1550                    AND rc.roleid = ?
1551           ORDER BY ctx.depth, ctx.path";
1552     $params = array($context->path."/%", $roleid);
1553     if ($rs = $DB->get_recordset_sql($sql, $params)) {
1554         foreach ($rs as $rd) {
1555             $k = "{$rd->path}:{$roleid}";
1556             $accessdata['rdef'][$k][$rd->capability] = $rd->permission;
1557         }
1558         $rs->close();
1559     }
1561     //
1562     // Say we loaded everything for the course context
1563     // - which we just did - if the user gets a proper
1564     // RA in this session, this data will need to be reloaded,
1565     // but that is handled by the complete accessdata reload
1566     //
1567     array_push($accessdata['loaded'], $context->path);
1569     //
1570     // Add the ghost RA
1571     //
1572     if (isset($accessdata['ra'][$context->path])) {
1573         array_push($accessdata['ra'][$context->path], $roleid);
1574     } else {
1575         $accessdata['ra'][$context->path] = array($roleid);
1576     }
1578     return $accessdata;
1581 /**
1582  * Removes any extra guest roels from accessdata
1583  * @param object $context
1584  * @param array $accessdata
1585  * @return array access data
1586  */
1587 function remove_temp_roles($context, array $accessdata) {
1588     global $DB, $USER;
1589     $sql = "SELECT DISTINCT ra.roleid AS id
1590               FROM {role_assignments} ra
1591              WHERE ra.contextid = :contextid AND ra.userid = :userid";
1592     $ras = $DB->get_records_sql($sql, array('contextid'=>$context->id, 'userid'=>$USER->id));
1594     $accessdata['ra'][$context->path] = array_keys($ras);
1595     return $accessdata;
1598 /**
1599  * Returns array of all role archetypes.
1600  *
1601  * @return array
1602  */
1603 function get_role_archetypes() {
1604     return array(
1605         'manager'        => 'manager',
1606         'coursecreator'  => 'coursecreator',
1607         'editingteacher' => 'editingteacher',
1608         'teacher'        => 'teacher',
1609         'student'        => 'student',
1610         'guest'          => 'guest',
1611         'user'           => 'user',
1612         'frontpage'      => 'frontpage'
1613     );
1616 /**
1617  * Assign the defaults found in this capability definition to roles that have
1618  * the corresponding legacy capabilities assigned to them.
1619  *
1620  * @param string $capability
1621  * @param array $legacyperms an array in the format (example):
1622  *                      'guest' => CAP_PREVENT,
1623  *                      'student' => CAP_ALLOW,
1624  *                      'teacher' => CAP_ALLOW,
1625  *                      'editingteacher' => CAP_ALLOW,
1626  *                      'coursecreator' => CAP_ALLOW,
1627  *                      'manager' => CAP_ALLOW
1628  * @return boolean success or failure.
1629  */
1630 function assign_legacy_capabilities($capability, $legacyperms) {
1632     $archetypes = get_role_archetypes();
1634     foreach ($legacyperms as $type => $perm) {
1636         $systemcontext = get_context_instance(CONTEXT_SYSTEM);
1637         if ($type === 'admin') {
1638             debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1639             $type = 'manager';
1640         }
1642         if (!array_key_exists($type, $archetypes)) {
1643             print_error('invalidlegacy', '', '', $type);
1644         }
1646         if ($roles = get_archetype_roles($type)) {
1647             foreach ($roles as $role) {
1648                 // Assign a site level capability.
1649                 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1650                     return false;
1651                 }
1652             }
1653         }
1654     }
1655     return true;
1658 /**
1659  * @param object $capability a capability - a row from the capabilities table.
1660  * @return boolean whether this capability is safe - that is, whether people with the
1661  *      safeoverrides capability should be allowed to change it.
1662  */
1663 function is_safe_capability($capability) {
1664     return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1667 /**********************************
1668  * Context Manipulation functions *
1669  **********************************/
1671 /**
1672  * Context creation - internal implementation.
1673  *
1674  * Create a new context record for use by all roles-related stuff
1675  * assumes that the caller has done the homework.
1676  *
1677  * DO NOT CALL THIS DIRECTLY, instead use {@link get_context_instance}!
1678  *
1679  * @param int $contextlevel
1680  * @param int $instanceid
1681  * @param int $strictness
1682  * @return object newly created context
1683  */
1684 function create_context($contextlevel, $instanceid, $strictness=IGNORE_MISSING) {
1686     global $CFG, $DB;
1688     if ($contextlevel == CONTEXT_SYSTEM) {
1689         return get_system_context();
1690     }
1692     $context = new stdClass();
1693     $context->contextlevel = $contextlevel;
1694     $context->instanceid = $instanceid;
1696     // Define $context->path based on the parent
1697     // context. In other words... Who is your daddy?
1698     $basepath  = '/' . SYSCONTEXTID;
1699     $basedepth = 1;
1701     $result = true;
1702     $error_message = NULL;
1704     switch ($contextlevel) {
1705         case CONTEXT_COURSECAT:
1706             $sql = "SELECT ctx.path, ctx.depth
1707                       FROM {context}           ctx
1708                       JOIN {course_categories} cc
1709                            ON (cc.parent=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
1710                      WHERE cc.id=?";
1711             $params = array($instanceid);
1712             if ($p = $DB->get_record_sql($sql, $params)) {
1713                 $basepath  = $p->path;
1714                 $basedepth = $p->depth;
1715             } else if ($category = $DB->get_record('course_categories', array('id'=>$instanceid), '*', $strictness)) {
1716                 if (empty($category->parent)) {
1717                     // ok - this is a top category
1718                 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $category->parent)) {
1719                     $basepath  = $parent->path;
1720                     $basedepth = $parent->depth;
1721                 } else {
1722                     // wrong parent category - no big deal, this can be fixed later
1723                     $basepath  = NULL;
1724                     $basedepth = 0;
1725                 }
1726             } else {
1727                 // incorrect category id
1728                 $error_message = "incorrect course category id ($instanceid)";
1729                 $result = false;
1730             }
1731             break;
1733         case CONTEXT_COURSE:
1734             $sql = "SELECT ctx.path, ctx.depth
1735                       FROM {context} ctx
1736                       JOIN {course}  c
1737                            ON (c.category=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSECAT.")
1738                      WHERE c.id=? AND c.id !=" . SITEID;
1739             $params = array($instanceid);
1740             if ($p = $DB->get_record_sql($sql, $params)) {
1741                 $basepath  = $p->path;
1742                 $basedepth = $p->depth;
1743             } else if ($course = $DB->get_record('course', array('id'=>$instanceid), '*', $strictness)) {
1744                 if ($course->id == SITEID) {
1745                     //ok - no parent category
1746                 } else if ($parent = get_context_instance(CONTEXT_COURSECAT, $course->category)) {
1747                     $basepath  = $parent->path;
1748                     $basedepth = $parent->depth;
1749                 } else {
1750                     // wrong parent category of course - no big deal, this can be fixed later
1751                     $basepath  = NULL;
1752                     $basedepth = 0;
1753                 }
1754             } else if ($instanceid == SITEID) {
1755                 // no errors for missing site course during installation
1756                 return false;
1757             } else {
1758                 // incorrect course id
1759                 $error_message = "incorrect course id ($instanceid)";
1760                 $result = false;
1761             }
1762             break;
1764         case CONTEXT_MODULE:
1765             $sql = "SELECT ctx.path, ctx.depth
1766                       FROM {context}        ctx
1767                       JOIN {course_modules} cm
1768                            ON (cm.course=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
1769                      WHERE cm.id=?";
1770             $params = array($instanceid);
1771             if ($p = $DB->get_record_sql($sql, $params)) {
1772                 $basepath  = $p->path;
1773                 $basedepth = $p->depth;
1774             } else if ($cm = $DB->get_record('course_modules', array('id'=>$instanceid), '*', $strictness)) {
1775                 if ($parent = get_context_instance(CONTEXT_COURSE, $cm->course, $strictness)) {
1776                     $basepath  = $parent->path;
1777                     $basedepth = $parent->depth;
1778                 } else {
1779                     // course does not exist - modules can not exist without a course
1780                     $error_message = "course does not exist ($cm->course) - modules can not exist without a course";
1781                     $result = false;
1782                 }
1783             } else {
1784                 // cm does not exist
1785                 $error_message = "cm with id $instanceid does not exist";
1786                 $result = false;
1787             }
1788             break;
1790         case CONTEXT_BLOCK:
1791             $sql = "SELECT ctx.path, ctx.depth
1792                       FROM {context} ctx
1793                       JOIN {block_instances} bi ON (bi.parentcontextid=ctx.id)
1794                      WHERE bi.id = ?";
1795             $params = array($instanceid, CONTEXT_COURSE);
1796             if ($p = $DB->get_record_sql($sql, $params, '*', $strictness)) {
1797                 $basepath  = $p->path;
1798                 $basedepth = $p->depth;
1799             } else {
1800                 // block does not exist
1801                 $error_message = 'block or parent context does not exist';
1802                 $result = false;
1803             }
1804             break;
1805         case CONTEXT_USER:
1806             // default to basepath
1807             break;
1808     }
1810     // if grandparents unknown, maybe rebuild_context_path() will solve it later
1811     if ($basedepth != 0) {
1812         $context->depth = $basedepth+1;
1813     }
1815     if (!$result) {
1816         debugging('Error: could not insert new context level "'.
1817                   s($contextlevel).'", instance "'.
1818                   s($instanceid).'". ' . $error_message);
1820         return false;
1821     }
1823     $id = $DB->insert_record('context', $context);
1824     // can't set the full path till we know the id!
1825     if ($basedepth != 0 and !empty($basepath)) {
1826         $DB->set_field('context', 'path', $basepath.'/'. $id, array('id'=>$id));
1827     }
1828     return get_context_instance_by_id($id);
1831 /**
1832  * Returns system context or NULL if can not be created yet.
1833  *
1834  * @todo can not use get_record() because we do not know if query failed :-(
1835  * switch to get_record() later
1836  *
1837  * @global object
1838  * @global object
1839  * @param bool $cache use caching
1840  * @return mixed system context or NULL
1841  */
1842 function get_system_context($cache=true) {
1843     global $DB, $ACCESSLIB_PRIVATE;
1844     if ($cache and defined('SYSCONTEXTID')) {
1845         if (is_null($ACCESSLIB_PRIVATE->systemcontext)) {
1846             $ACCESSLIB_PRIVATE->systemcontext = new stdClass();
1847             $ACCESSLIB_PRIVATE->systemcontext->id           = SYSCONTEXTID;
1848             $ACCESSLIB_PRIVATE->systemcontext->contextlevel = CONTEXT_SYSTEM;
1849             $ACCESSLIB_PRIVATE->systemcontext->instanceid   = 0;
1850             $ACCESSLIB_PRIVATE->systemcontext->path         = '/'.SYSCONTEXTID;
1851             $ACCESSLIB_PRIVATE->systemcontext->depth        = 1;
1852         }
1853         return $ACCESSLIB_PRIVATE->systemcontext;
1854     }
1855     try {
1856         $context = $DB->get_record('context', array('contextlevel'=>CONTEXT_SYSTEM));
1857     } catch (dml_exception $e) {
1858         //table does not exist yet, sorry
1859         return NULL;
1860     }
1862     if (!$context) {
1863         $context = new stdClass();
1864         $context->contextlevel = CONTEXT_SYSTEM;
1865         $context->instanceid   = 0;
1866         $context->depth        = 1;
1867         $context->path         = NULL; //not known before insert
1869         try {
1870             $context->id = $DB->insert_record('context', $context);
1871         } catch (dml_exception $e) {
1872             // can not create context yet, sorry
1873             return NULL;
1874         }
1875     }
1877     if (!isset($context->depth) or $context->depth != 1 or $context->instanceid != 0 or $context->path != '/'.$context->id) {
1878         $context->instanceid   = 0;
1879         $context->path         = '/'.$context->id;
1880         $context->depth        = 1;
1881         $DB->update_record('context', $context);
1882     }
1884     if (!defined('SYSCONTEXTID')) {
1885         define('SYSCONTEXTID', $context->id);
1886     }
1888     $ACCESSLIB_PRIVATE->systemcontext = $context;
1889     return $ACCESSLIB_PRIVATE->systemcontext;
1892 /**
1893  * Remove a context record and any dependent entries,
1894  * removes context from static context cache too
1895  *
1896  * @param int $level
1897  * @param int $instanceid
1898  * @param bool $deleterecord false means keep record for now
1899  * @return bool returns true or throws an exception
1900  */
1901 function delete_context($contextlevel, $instanceid, $deleterecord = true) {
1902     global $DB, $ACCESSLIB_PRIVATE, $CFG;
1904     // do not use get_context_instance(), because the related object might not exist,
1905     // or the context does not exist yet and it would be created now
1906     if ($context = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
1907         // delete these first because they might fetch the context and try to recreate it!
1908         blocks_delete_all_for_context($context->id);
1909         filter_delete_all_for_context($context->id);
1911         require_once($CFG->dirroot . '/comment/lib.php');
1912         comment::delete_comments(array('contextid'=>$context->id));
1914         require_once($CFG->dirroot.'/rating/lib.php');
1915         $delopt = new stdclass();
1916         $delopt->contextid = $context->id;
1917         $rm = new rating_manager();
1918         $rm->delete_ratings($delopt);
1920         // delete all files attached to this context
1921         $fs = get_file_storage();
1922         $fs->delete_area_files($context->id);
1924         // now delete stuff from role related tables, role_unassign_all
1925         // and unenrol should be called earlier to do proper cleanup
1926         $DB->delete_records('role_assignments', array('contextid'=>$context->id));
1927         $DB->delete_records('role_capabilities', array('contextid'=>$context->id));
1928         $DB->delete_records('role_names', array('contextid'=>$context->id));
1930         // and finally it is time to delete the context record if requested
1931         if ($deleterecord) {
1932             $DB->delete_records('context', array('id'=>$context->id));
1933             // purge static context cache if entry present
1934             unset($ACCESSLIB_PRIVATE->contexts[$contextlevel][$instanceid]);
1935             unset($ACCESSLIB_PRIVATE->contextsbyid[$context->id]);
1936         }
1938         // do not mark dirty contexts if parents unknown
1939         if (!is_null($context->path) and $context->depth > 0) {
1940             mark_context_dirty($context->path);
1941         }
1942     }
1944     return true;
1947 /**
1948  * Precreates all contexts including all parents
1949  *
1950  * @global object
1951  * @param int $contextlevel empty means all
1952  * @param bool $buildpaths update paths and depths
1953  * @return void
1954  */
1955 function create_contexts($contextlevel=NULL, $buildpaths=true) {
1956     global $DB;
1958     //make sure system context exists
1959     $syscontext = get_system_context(false);
1961     if (empty($contextlevel) or $contextlevel == CONTEXT_COURSECAT
1962                              or $contextlevel == CONTEXT_COURSE
1963                              or $contextlevel == CONTEXT_MODULE
1964                              or $contextlevel == CONTEXT_BLOCK) {
1965         $sql = "INSERT INTO {context} (contextlevel, instanceid)
1966                 SELECT ".CONTEXT_COURSECAT.", cc.id
1967                   FROM {course}_categories cc
1968                  WHERE NOT EXISTS (SELECT 'x'
1969                                      FROM {context} cx
1970                                     WHERE cc.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSECAT.")";
1971         $DB->execute($sql);
1973     }
1975     if (empty($contextlevel) or $contextlevel == CONTEXT_COURSE
1976                              or $contextlevel == CONTEXT_MODULE
1977                              or $contextlevel == CONTEXT_BLOCK) {
1978         $sql = "INSERT INTO {context} (contextlevel, instanceid)
1979                 SELECT ".CONTEXT_COURSE.", c.id
1980                   FROM {course} c
1981                  WHERE NOT EXISTS (SELECT 'x'
1982                                      FROM {context} cx
1983                                     WHERE c.id = cx.instanceid AND cx.contextlevel=".CONTEXT_COURSE.")";
1984         $DB->execute($sql);
1986     }
1988     if (empty($contextlevel) or $contextlevel == CONTEXT_MODULE
1989                              or $contextlevel == CONTEXT_BLOCK) {
1990         $sql = "INSERT INTO {context} (contextlevel, instanceid)
1991                 SELECT ".CONTEXT_MODULE.", cm.id
1992                   FROM {course}_modules cm
1993                  WHERE NOT EXISTS (SELECT 'x'
1994                                      FROM {context} cx
1995                                     WHERE cm.id = cx.instanceid AND cx.contextlevel=".CONTEXT_MODULE.")";
1996         $DB->execute($sql);
1997     }
1999     if (empty($contextlevel) or $contextlevel == CONTEXT_USER
2000                              or $contextlevel == CONTEXT_BLOCK) {
2001         $sql = "INSERT INTO {context} (contextlevel, instanceid)
2002                 SELECT ".CONTEXT_USER.", u.id
2003                   FROM {user} u
2004                  WHERE u.deleted=0
2005                    AND NOT EXISTS (SELECT 'x'
2006                                      FROM {context} cx
2007                                     WHERE u.id = cx.instanceid AND cx.contextlevel=".CONTEXT_USER.")";
2008         $DB->execute($sql);
2010     }
2012     if (empty($contextlevel) or $contextlevel == CONTEXT_BLOCK) {
2013         $sql = "INSERT INTO {context} (contextlevel, instanceid)
2014                 SELECT ".CONTEXT_BLOCK.", bi.id
2015                   FROM {block_instances} bi
2016                  WHERE NOT EXISTS (SELECT 'x'
2017                                      FROM {context} cx
2018                                     WHERE bi.id = cx.instanceid AND cx.contextlevel=".CONTEXT_BLOCK.")";
2019         $DB->execute($sql);
2020     }
2022     if ($buildpaths) {
2023         build_context_path(false);
2024     }
2027 /**
2028  * Remove stale context records
2029  *
2030  * @global object
2031  * @return bool
2032  */
2033 function cleanup_contexts() {
2034     global $DB;
2036     $sql = "  SELECT c.contextlevel,
2037                      c.instanceid AS instanceid
2038                 FROM {context} c
2039                 LEFT OUTER JOIN {course}_categories t
2040                      ON c.instanceid = t.id
2041                WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_COURSECAT."
2042             UNION
2043               SELECT c.contextlevel,
2044                      c.instanceid
2045                 FROM {context} c
2046                 LEFT OUTER JOIN {course} t
2047                      ON c.instanceid = t.id
2048                WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_COURSE."
2049             UNION
2050               SELECT c.contextlevel,
2051                      c.instanceid
2052                 FROM {context} c
2053                 LEFT OUTER JOIN {course}_modules t
2054                      ON c.instanceid = t.id
2055                WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_MODULE."
2056             UNION
2057               SELECT c.contextlevel,
2058                      c.instanceid
2059                 FROM {context} c
2060                 LEFT OUTER JOIN {user} t
2061                      ON c.instanceid = t.id
2062                WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_USER."
2063             UNION
2064               SELECT c.contextlevel,
2065                      c.instanceid
2066                 FROM {context} c
2067                 LEFT OUTER JOIN {block_instances} t
2068                      ON c.instanceid = t.id
2069                WHERE t.id IS NULL AND c.contextlevel = ".CONTEXT_BLOCK."
2070            ";
2072     // transactions used only for performance reasons here
2073     $transaction = $DB->start_delegated_transaction();
2075     if ($rs = $DB->get_recordset_sql($sql)) {
2076         foreach ($rs as $ctx) {
2077             delete_context($ctx->contextlevel, $ctx->instanceid);
2078         }
2079         $rs->close();
2080     }
2082     $transaction->allow_commit();
2083     return true;
2086 /**
2087  * Preloads all contexts relating to a course: course, modules. Block contexts
2088  * are no longer loaded here. The contexts for all the blocks on the current
2089  * page are now efficiently loaded by {@link block_manager::load_blocks()}.
2090  *
2091  * @param int $courseid Course ID
2092  * @return void
2093  */
2094 function preload_course_contexts($courseid) {
2095     global $DB, $ACCESSLIB_PRIVATE;
2097     // Users can call this multiple times without doing any harm
2098     global $ACCESSLIB_PRIVATE;
2099     if (array_key_exists($courseid, $ACCESSLIB_PRIVATE->preloadedcourses)) {
2100         return;
2101     }
2103     $params = array($courseid, $courseid, $courseid);
2104     $sql = "SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
2105               FROM {course_modules} cm
2106               JOIN {context} x ON x.instanceid=cm.id
2107              WHERE cm.course=? AND x.contextlevel=".CONTEXT_MODULE."
2109          UNION ALL
2111             SELECT x.instanceid, x.id, x.contextlevel, x.path, x.depth
2112               FROM {context} x
2113              WHERE x.instanceid=? AND x.contextlevel=".CONTEXT_COURSE."";
2115     $rs = $DB->get_recordset_sql($sql, $params);
2116     foreach($rs as $context) {
2117         cache_context($context);
2118     }
2119     $rs->close();
2120     $ACCESSLIB_PRIVATE->preloadedcourses[$courseid] = true;
2123 /**
2124  * Get the context instance as an object. This function will create the
2125  * context instance if it does not exist yet.
2126  *
2127  * @todo Remove code branch from previous fix MDL-9016 which is no longer needed
2128  *
2129  * @param integer $level The context level, for example CONTEXT_COURSE, or CONTEXT_MODULE.
2130  * @param integer $instance The instance id. For $level = CONTEXT_COURSE, this would be $course->id,
2131  *      for $level = CONTEXT_MODULE, this would be $cm->id. And so on. Defaults to 0
2132  * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
2133  *      MUST_EXIST means throw exception if no record or multiple records found
2134  * @return object The context object.
2135  */
2136 function get_context_instance($contextlevel, $instance=0, $strictness=IGNORE_MISSING) {
2138     global $DB, $ACCESSLIB_PRIVATE;
2139     static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK);
2141 /// System context has special cache
2142     if ($contextlevel == CONTEXT_SYSTEM) {
2143         return get_system_context();
2144     }
2146 /// check allowed context levels
2147     if (!in_array($contextlevel, $allowed_contexts)) {
2148         // fatal error, code must be fixed - probably typo or switched parameters
2149         print_error('invalidcourselevel');
2150     }
2152     if (!is_array($instance)) {
2153     /// Check the cache
2154         if (isset($ACCESSLIB_PRIVATE->contexts[$contextlevel][$instance])) {  // Already cached
2155             return $ACCESSLIB_PRIVATE->contexts[$contextlevel][$instance];
2156         }
2158     /// Get it from the database, or create it
2159         if (!$context = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instance))) {
2160             $context = create_context($contextlevel, $instance, $strictness);
2161         }
2163     /// Only add to cache if context isn't empty.
2164         if (!empty($context)) {
2165             cache_context($context);
2166         }
2168         return $context;
2169     }
2172 /// ok, somebody wants to load several contexts to save some db queries ;-)
2173     $instances = $instance;
2174     $result = array();
2176     foreach ($instances as $key=>$instance) {
2177     /// Check the cache first
2178         if (isset($ACCESSLIB_PRIVATE->contexts[$contextlevel][$instance])) {  // Already cached
2179             $result[$instance] = $ACCESSLIB_PRIVATE->contexts[$contextlevel][$instance];
2180             unset($instances[$key]);
2181             continue;
2182         }
2183     }
2185     if ($instances) {
2186         list($instanceids, $params) = $DB->get_in_or_equal($instances, SQL_PARAMS_QM);
2187         array_unshift($params, $contextlevel);
2188         $sql = "SELECT instanceid, id, contextlevel, path, depth
2189                   FROM {context}
2190                  WHERE contextlevel=? AND instanceid $instanceids";
2192         if (!$contexts = $DB->get_records_sql($sql, $params)) {
2193             $contexts = array();
2194         }
2196         foreach ($instances as $instance) {
2197             if (isset($contexts[$instance])) {
2198                 $context = $contexts[$instance];
2199             } else {
2200                 $context = create_context($contextlevel, $instance);
2201             }
2203             if (!empty($context)) {
2204                 cache_context($context);
2205             }
2207             $result[$instance] = $context;
2208         }
2209     }
2211     return $result;
2215 /**
2216  * Get a context instance as an object, from a given context id.
2217  *
2218  * @param mixed $id a context id or array of ids.
2219  * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
2220  *                        MUST_EXIST means throw exception if no record or multiple records found
2221  * @return mixed object, array of the context object, or false.
2222  */
2223 function get_context_instance_by_id($id, $strictness=IGNORE_MISSING) {
2224     global $DB, $ACCESSLIB_PRIVATE;
2226     if ($id == SYSCONTEXTID) {
2227         return get_system_context();
2228     }
2230     if (isset($ACCESSLIB_PRIVATE->contextsbyid[$id])) {  // Already cached
2231         return $ACCESSLIB_PRIVATE->contextsbyid[$id];
2232     }
2234     if ($context = $DB->get_record('context', array('id'=>$id), '*', $strictness)) {
2235         cache_context($context);
2236         return $context;
2237     }
2239     return false;
2243 /**
2244  * Get the local override (if any) for a given capability in a role in a context
2245  *
2246  * @global object
2247  * @param int $roleid
2248  * @param int $contextid
2249  * @param string $capability
2250  */
2251 function get_local_override($roleid, $contextid, $capability) {
2252     global $DB;
2253     return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
2256 /**
2257  * Returns context instance plus related course and cm instances
2258  * @param int $contextid
2259  * @return array of ($context, $course, $cm)
2260  */
2261 function get_context_info_array($contextid) {
2262     global $DB;
2264     $context = get_context_instance_by_id($contextid, MUST_EXIST);
2265     $course  = NULL;
2266     $cm      = NULL;
2268     if ($context->contextlevel == CONTEXT_COURSE) {
2269         $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
2271     } else if ($context->contextlevel == CONTEXT_MODULE) {
2272         $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
2273         $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
2275     } else if ($context->contextlevel == CONTEXT_BLOCK) {
2276         $parentcontexts = get_parent_contexts($context, false);
2277         $parent = reset($parentcontexts);
2278         $parent = get_context_instance_by_id($parent);
2280         if ($parent->contextlevel == CONTEXT_COURSE) {
2281             $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
2282         } else if ($parent->contextlevel == CONTEXT_MODULE) {
2283             $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
2284             $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
2285         }
2286     }
2288     return array($context, $course, $cm);
2291 /**
2292  * Returns current course id or null if outside of course based on context parameter.
2293  * @param object $context
2294  * @return int|bool related course id or false
2295  */
2296 function get_courseid_from_context($context) {
2297     if ($context->contextlevel == CONTEXT_COURSE) {
2298         return $context->instanceid;
2299     }
2301     if ($context->contextlevel < CONTEXT_COURSE) {
2302         return false;
2303     }
2305     if ($context->contextlevel == CONTEXT_MODULE) {
2306         $parentcontexts = get_parent_contexts($context, false);
2307         $parent = reset($parentcontexts);
2308         $parent = get_context_instance_by_id($parent);
2309         return $parent->instanceid;
2310     }
2312     if ($context->contextlevel == CONTEXT_BLOCK) {
2313         $parentcontexts = get_parent_contexts($context, false);
2314         $parent = reset($parentcontexts);
2315         return get_courseid_from_context($parent);
2316     }
2318     return false;
2322 //////////////////////////////////////
2323 //    DB TABLE RELATED FUNCTIONS    //
2324 //////////////////////////////////////
2326 /**
2327  * function that creates a role
2328  *
2329  * @global object
2330  * @param string $name role name
2331  * @param string $shortname role short name
2332  * @param string $description role description
2333  * @param string $archetype
2334  * @return mixed id or dml_exception
2335  */
2336 function create_role($name, $shortname, $description, $archetype='') {
2337     global $DB;
2339     if (strpos($archetype, 'moodle/legacy:') !== false) {
2340         throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
2341     }
2343     // verify role archetype actually exists
2344     $archetypes = get_role_archetypes();
2345     if (empty($archetypes[$archetype])) {
2346         $archetype = '';
2347     }
2349     // Get the system context.
2350     $context = get_context_instance(CONTEXT_SYSTEM);
2352     // Insert the role record.
2353     $role = new stdClass();
2354     $role->name        = $name;
2355     $role->shortname   = $shortname;
2356     $role->description = $description;
2357     $role->archetype   = $archetype;
2359     //find free sortorder number
2360     $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
2361     if (empty($role->sortorder)) {
2362         $role->sortorder = 1;
2363     }
2364     $id = $DB->insert_record('role', $role);
2366     return $id;
2369 /**
2370  * Function that deletes a role and cleanups up after it
2371  *
2372  * @param int $roleid id of role to delete
2373  * @return bool always true
2374  */
2375 function delete_role($roleid) {
2376     global $CFG, $DB;
2378     // first unssign all users
2379     role_unassign_all(array('roleid'=>$roleid));
2381     // cleanup all references to this role, ignore errors
2382     $DB->delete_records('role_capabilities',   array('roleid'=>$roleid));
2383     $DB->delete_records('role_allow_assign',   array('roleid'=>$roleid));
2384     $DB->delete_records('role_allow_assign',   array('allowassign'=>$roleid));
2385     $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
2386     $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
2387     $DB->delete_records('role_names',          array('roleid'=>$roleid));
2388     $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
2390     // finally delete the role itself
2391     // get this before the name is gone for logging
2392     $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
2394     $DB->delete_records('role', array('id'=>$roleid));
2396     add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
2398     return true;
2401 /**
2402  * Function to write context specific overrides, or default capabilities.
2403  *
2404  * @global object
2405  * @global object
2406  * @param string module string name
2407  * @param string capability string name
2408  * @param int contextid context id
2409  * @param int roleid role id
2410  * @param int permission int 1,-1 or -1000 should not be writing if permission is 0
2411  * @return bool
2412  */
2413 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite=false) {
2414     global $USER, $DB;
2416     if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
2417         unassign_capability($capability, $roleid, $contextid);
2418         return true;
2419     }
2421     $existing = $DB->get_record('role_capabilities', array('contextid'=>$contextid, 'roleid'=>$roleid, 'capability'=>$capability));
2423     if ($existing and !$overwrite) {   // We want to keep whatever is there already
2424         return true;
2425     }
2427     $cap = new stdClass();
2428     $cap->contextid = $contextid;
2429     $cap->roleid = $roleid;
2430     $cap->capability = $capability;
2431     $cap->permission = $permission;
2432     $cap->timemodified = time();
2433     $cap->modifierid = empty($USER->id) ? 0 : $USER->id;
2435     if ($existing) {
2436         $cap->id = $existing->id;
2437         $DB->update_record('role_capabilities', $cap);
2438     } else {
2439         $c = $DB->get_record('context', array('id'=>$contextid));
2440         $DB->insert_record('role_capabilities', $cap);
2441     }
2442     return true;
2445 /**
2446  * Unassign a capability from a role.
2447  *
2448  * @global object
2449  * @param int $roleid the role id
2450  * @param string $capability the name of the capability
2451  * @return boolean success or failure
2452  */
2453 function unassign_capability($capability, $roleid, $contextid=NULL) {
2454     global $DB;
2456     if (!empty($contextid)) {
2457         // delete from context rel, if this is the last override in this context
2458         $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$contextid));
2459     } else {
2460         $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
2461     }
2462     return true;
2466 /**
2467  * Get the roles that have a given capability assigned to it
2468  *
2469  * This function does not resolve the actual permission of the capability.
2470  * It just checks for permissions and overrides.
2471  * Use get_roles_with_cap_in_context() if resolution is required.
2472  *
2473  * @param string $capability - capability name (string)
2474  * @param string $permission - optional, the permission defined for this capability
2475  *                      either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
2476  * @param stdClass $context, null means any
2477  * @return array of role objects
2478  */
2479 function get_roles_with_capability($capability, $permission = null, $context = null) {
2480     global $DB;
2482     if ($context) {
2483         $contexts = get_parent_contexts($context, true);
2484         list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx000');
2485         $contextsql = "AND rc.contextid $insql";
2486     } else {
2487         $params = array();
2488         $contextsql = '';
2489     }
2491     if ($permission) {
2492         $permissionsql = " AND rc.permission = :permission";
2493         $params['permission'] = $permission;
2494     } else {
2495         $permissionsql = '';
2496     }
2498     $sql = "SELECT r.*
2499               FROM {role} r
2500              WHERE r.id IN (SELECT rc.roleid
2501                               FROM {role_capabilities} rc
2502                              WHERE rc.capability = :capname
2503                                    $contextsql
2504                                    $permissionsql)";
2505     $params['capname'] = $capability;
2508     return $DB->get_records_sql($sql, $params);
2512 /**
2513  * This function makes a role-assignment (a role for a user in a particular context)
2514  *
2515  * @param int $roleid the role of the id
2516  * @param int $userid userid
2517  * @param int $contextid id of the context
2518  * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
2519  * @prama int $itemid id of enrolment/auth plugin
2520  * @param string $timemodified defaults to current time
2521  * @return int new/existing id of the assignment
2522  */
2523 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
2524     global $USER, $CFG, $DB;
2526     // first of all detect if somebody is using old style parameters
2527     if ($contextid === 0 or is_numeric($component)) {
2528         throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
2529     }
2531     // now validate all parameters
2532     if (empty($roleid)) {
2533         throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
2534     }
2536     if (empty($userid)) {
2537         throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
2538     }
2540     if ($itemid) {
2541         if (strpos($component, '_') === false) {
2542             throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
2543         }
2544     } else {
2545         $itemid = 0;
2546         if ($component !== '' and strpos($component, '_') === false) {
2547             throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
2548         }
2549     }
2551     if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
2552         throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
2553         return false;
2554     }
2556     $context = get_context_instance_by_id($contextid, MUST_EXIST);
2558     if (!$timemodified) {
2559         $timemodified = time();
2560     }
2562 /// Check for existing entry
2563     $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
2565     if ($ras) {
2566         // role already assigned - this should not happen
2567         if (count($ras) > 1) {
2568             //very weird - remove all duplicates!
2569             $ra = array_shift($ras);
2570             foreach ($ras as $r) {
2571                 $DB->delete_records('role_assignments', array('id'=>$r->id));
2572             }
2573         } else {
2574             $ra = reset($ras);
2575         }
2577         // actually there is no need to update, reset anything or trigger any event, so just return
2578         return $ra->id;
2579     }
2581     // Create a new entry
2582     $ra = new stdClass();
2583     $ra->roleid       = $roleid;
2584     $ra->contextid    = $context->id;
2585     $ra->userid       = $userid;
2586     $ra->component    = $component;
2587     $ra->itemid       = $itemid;
2588     $ra->timemodified = $timemodified;
2589     $ra->modifierid   = empty($USER->id) ? 0 : $USER->id;
2591     $ra->id = $DB->insert_record('role_assignments', $ra);
2593     // mark context as dirty - again expensive, but needed
2594     mark_context_dirty($context->path);
2596     if (!empty($USER->id) && $USER->id == $userid) {
2597         // If the user is the current user, then do full reload of capabilities too.
2598         load_all_capabilities();
2599     }
2601     events_trigger('role_assigned', $ra);
2603     return $ra->id;
2606 /**
2607  * Removes one role assignment
2608  *
2609  * @param int $roleid
2610  * @param int  $userid
2611  * @param int  $contextid
2612  * @param string $component
2613  * @param int  $itemid
2614  * @return void
2615  */
2616 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
2617     global $USER, $CFG, $DB;
2619     // first make sure the params make sense
2620     if ($roleid == 0 or $userid == 0 or $contextid == 0) {
2621         throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
2622     }
2624     if ($itemid) {
2625         if (strpos($component, '_') === false) {
2626             throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
2627         }
2628     } else {
2629         $itemid = 0;
2630         if ($component !== '' and strpos($component, '_') === false) {
2631             throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
2632         }
2633     }
2635     role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
2638 /**
2639  * Removes multiple role assignments, parameters may contain:
2640  *   'roleid', 'userid', 'contextid', 'component', 'enrolid'.
2641  *
2642  * @param array $params role assignment parameters
2643  * @param bool $subcontexts unassign in subcontexts too
2644  * @param bool $includmanual include manual role assignments too
2645  * @return void
2646  */
2647 function role_unassign_all(array $params, $subcontexts = false, $includemanual=false) {
2648     global $USER, $CFG, $DB;
2650     if (!$params) {
2651         throw new coding_exception('Missing parameters in role_unsassign_all() call');
2652     }
2654     $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
2655     foreach ($params as $key=>$value) {
2656         if (!in_array($key, $allowed)) {
2657             throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
2658         }
2659     }
2661     if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
2662         throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
2663     }
2665     if ($includemanual) {
2666         if (!isset($params['component']) or $params['component'] === '') {
2667             throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
2668         }
2669     }
2671     if ($subcontexts) {
2672         if (empty($params['contextid'])) {
2673             throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
2674         }
2675     }
2677     $ras = $DB->get_records('role_assignments', $params);
2678     foreach($ras as $ra) {
2679         $DB->delete_records('role_assignments', array('id'=>$ra->id));
2680         if ($context = get_context_instance_by_id($ra->contextid)) {
2681             // this is a bit expensive but necessary
2682             mark_context_dirty($context->path);
2683             /// If the user is the current user, then do full reload of capabilities too.
2684             if (!empty($USER->id) && $USER->id == $ra->userid) {
2685                 load_all_capabilities();
2686             }
2687         }
2688         events_trigger('role_unassigned', $ra);
2689     }
2690     unset($ras);
2692     // process subcontexts
2693     if ($subcontexts and $context = get_context_instance_by_id($params['contextid'])) {
2694         $contexts = get_child_contexts($context);
2695         $mparams = $params;
2696         foreach($contexts as $context) {
2697             $mparams['contextid'] = $context->id;
2698             $ras = $DB->get_records('role_assignments', $mparams);
2699             foreach($ras as $ra) {
2700                 $DB->delete_records('role_assignments', array('id'=>$ra->id));
2701                 // this is a bit expensive but necessary
2702                 mark_context_dirty($context->path);
2703                 /// If the user is the current user, then do full reload of capabilities too.
2704                 if (!empty($USER->id) && $USER->id == $ra->userid) {
2705                     load_all_capabilities();
2706                 }
2707                 events_trigger('role_unassigned', $ra);
2708             }
2709         }
2710     }
2712     // do this once more for all manual role assignments
2713     if ($includemanual) {
2714         $params['component'] = '';
2715         role_unassign_all($params, $subcontexts, false);
2716     }
2720 /**
2721  * Determines if a user is currently logged in
2722  *
2723  * @return bool
2724  */
2725 function isloggedin() {
2726     global $USER;
2728     return (!empty($USER->id));
2731 /**
2732  * Determines if a user is logged in as real guest user with username 'guest'.
2733  *
2734  * @param int|object $user mixed user object or id, $USER if not specified
2735  * @return bool true if user is the real guest user, false if not logged in or other user
2736  */
2737 function isguestuser($user = NULL) {
2738     global $USER, $DB, $CFG;
2740     // make sure we have the user id cached in config table, because we are going to use it a lot
2741     if (empty($CFG->siteguest)) {
2742         if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
2743             // guest does not exist yet, weird
2744             return false;
2745         }
2746         set_config('siteguest', $guestid);
2747     }
2748     if ($user === NULL) {
2749         $user = $USER;
2750     }
2752     if ($user === NULL) {
2753         // happens when setting the $USER
2754         return false;
2756     } else if (is_numeric($user)) {
2757         return ($CFG->siteguest == $user);
2759     } else if (is_object($user)) {
2760         if (empty($user->id)) {
2761             return false; // not logged in means is not be guest
2762         } else {
2763             return ($CFG->siteguest == $user->id);
2764         }
2766     } else {
2767         throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
2768     }
2771 /**
2772  * Does user have a (temporary or real) guest access to course?
2773  *
2774  * @param object $context
2775  * @param object|int $user
2776  * @return bool
2777  */
2778 function is_guest($context, $user = NULL) {
2779     global $USER;
2781     // first find the course context
2782     $coursecontext = get_course_context($context);
2784     // make sure there is a real user specified
2785     if ($user === NULL) {
2786         $userid = !empty($USER->id) ? $USER->id : 0;
2787     } else {
2788         $userid = !empty($user->id) ? $user->id : $user;
2789     }
2791     if (isguestuser($userid)) {
2792         // can not inspect or be enrolled
2793         return true;
2794     }
2796     if (has_capability('moodle/course:view', $coursecontext, $user)) {
2797         // viewing users appear out of nowhere, they are neither guests nor participants
2798         return false;
2799     }
2801     // consider only real active enrolments here
2802     if (is_enrolled($coursecontext, $user, '', true)) {
2803         return false;
2804     }
2806     return true;
2810 /**
2811  * Returns true if the user has moodle/course:view capability in the course,
2812  * this is intended for admins, managers (aka small admins), inspectors, etc.
2813  *
2814  * @param object $context
2815  * @param int|object $user, if NULL $USER is used
2816  * @param string $withcapability extra capability name
2817  * @return bool
2818  */
2819 function is_viewing($context, $user = NULL, $withcapability = '') {
2820     global $USER;
2822     // first find the course context
2823     $coursecontext = get_course_context($context);
2825     if (isguestuser($user)) {
2826         // can not inspect
2827         return false;
2828     }
2830     if (!has_capability('moodle/course:view', $coursecontext, $user)) {
2831         // admins are allowed to inspect courses
2832         return false;
2833     }
2835     if ($withcapability and !has_capability($withcapability, $context, $user)) {
2836         // site admins always have the capability, but the enrolment above blocks
2837         return false;
2838     }
2840     return true;
2843 /**
2844  * Returns true if user is enrolled (is participating) in course
2845  * this is intended for students and teachers.
2846  *
2847  * @param object $context
2848  * @param int|object $user, if NULL $USER is used, otherwise user object or id expected
2849  * @param string $withcapability extra capability name
2850  * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2851  * @return bool
2852  */
2853 function is_enrolled($context, $user = NULL, $withcapability = '', $onlyactive = false) {
2854     global $USER, $DB;
2856     // first find the course context
2857     $coursecontext = get_course_context($context);
2859     // make sure there is a real user specified
2860     if ($user === NULL) {
2861         $userid = !empty($USER->id) ? $USER->id : 0;
2862     } else {
2863         $userid = !empty($user->id) ? $user->id : $user;
2864     }
2866     if (empty($userid)) {
2867         // not-logged-in!
2868         return false;
2869     } else if (isguestuser($userid)) {
2870         // guest account can not be enrolled anywhere
2871         return false;
2872     }
2874     if ($coursecontext->instanceid == SITEID) {
2875         // everybody participates on frontpage
2876     } else {
2877         if ($onlyactive) {
2878             $sql = "SELECT ue.*
2879                       FROM {user_enrolments} ue
2880                       JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2881                       JOIN {user} u ON u.id = ue.userid
2882                      WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0";
2883             $params = array('enabled'=>ENROL_INSTANCE_ENABLED, 'active'=>ENROL_USER_ACTIVE, 'userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2884             // this result should be very small, better not do the complex time checks in sql for now ;-)
2885             $enrolments = $DB->get_records_sql($sql, $params);
2886             $now = time();
2887             // make sure the enrol period is ok
2888             $result = false;
2889             foreach ($enrolments as $e) {
2890                 if ($e->timestart > $now) {
2891                     continue;
2892                 }
2893                 if ($e->timeend and $e->timeend < $now) {
2894                     continue;
2895                 }
2896                 $result = true;
2897                 break;
2898             }
2899             if (!$result) {
2900                 return false;
2901             }
2903         } else {
2904             // any enrolment is good for us here, even outdated, disabled or inactive
2905             $sql = "SELECT 'x'
2906                       FROM {user_enrolments} ue
2907                       JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
2908                       JOIN {user} u ON u.id = ue.userid
2909                      WHERE ue.userid = :userid AND u.deleted = 0";
2910             $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
2911             if (!$DB->record_exists_sql($sql, $params)) {
2912                 return false;
2913             }
2914         }
2915     }
2917     if ($withcapability and !has_capability($withcapability, $context, $userid)) {
2918         return false;
2919     }
2921     return true;
2924 /**
2925  * Returns array with sql code and parameters returning all ids
2926  * of users enrolled into course.
2927  *
2928  * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2929  *
2930  * @param object $context
2931  * @param string $withcapability
2932  * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2933  * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2934  * @return array list($sql, $params)
2935  */
2936 function get_enrolled_sql($context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2937     global $DB, $CFG;
2939     // use unique prefix just in case somebody makes some SQL magic with the result
2940     static $i = 0;
2941     $i++;
2942     $prefix = 'eu'.$i.'_';
2944     // first find the course context
2945     $coursecontext = get_course_context($context);
2947     $isfrontpage = ($coursecontext->instanceid == SITEID);
2949     $joins  = array();
2950     $wheres = array();
2951     $params = array();
2953     list($contextids, $contextpaths) = get_context_info_list($context);
2955     // get all relevant capability info for all roles
2956     if ($withcapability) {
2957         list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx00');
2958         $cparams['cap'] = $withcapability;
2960         $defs = array();
2961         $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2962                   FROM {role_capabilities} rc
2963                   JOIN {context} ctx on rc.contextid = ctx.id
2964                  WHERE rc.contextid $incontexts AND rc.capability = :cap";
2965         $rcs = $DB->get_records_sql($sql, $cparams);
2966         foreach ($rcs as $rc) {
2967             $defs[$rc->path][$rc->roleid] = $rc->permission;
2968         }
2970         $access = array();
2971         if (!empty($defs)) {
2972             foreach ($contextpaths as $path) {
2973                 if (empty($defs[$path])) {
2974                     continue;
2975                 }
2976                 foreach($defs[$path] as $roleid => $perm) {
2977                     if ($perm == CAP_PROHIBIT) {
2978                         $access[$roleid] = CAP_PROHIBIT;
2979                         continue;
2980                     }
2981                     if (!isset($access[$roleid])) {
2982                         $access[$roleid] = (int)$perm;
2983                     }
2984                 }
2985             }
2986         }
2988         unset($defs);
2990         // make lists of roles that are needed and prohibited
2991         $needed     = array(); // one of these is enough
2992         $prohibited = array(); // must not have any of these
2993         foreach ($access as $roleid => $perm) {
2994             if ($perm == CAP_PROHIBIT) {
2995                 unset($needed[$roleid]);
2996                 $prohibited[$roleid] = true;
2997             } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2998                 $needed[$roleid] = true;
2999             }
3000         }
3002         $defaultuserroleid      = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : NULL;
3003         $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : NULL;
3005         $nobody = false;
3007         if ($isfrontpage) {
3008             if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
3009                 $nobody = true;
3010             } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
3011                 // everybody not having prohibit has the capability
3012                 $needed = array();
3013             } else if (empty($needed)) {
3014                 $nobody = true;
3015             }
3016         } else {
3017             if (!empty($prohibited[$defaultuserroleid])) {
3018                 $nobody = true;
3019             } else if (!empty($needed[$defaultuserroleid])) {
3020                 // everybody not having prohibit has the capability
3021                 $needed = array();
3022             } else if (empty($needed)) {
3023                 $nobody = true;
3024             }
3025         }
3027         if ($nobody) {
3028             // nobody can match so return some SQL that does not return any results
3029             $wheres[] = "1 = 2";
3031         } else {
3033             if ($needed) {
3034                 $ctxids = implode(',', $contextids);
3035                 $roleids = implode(',', array_keys($needed));
3036                 $joins[] = "JOIN {role_assignments} {$prefix}ra3 ON ({$prefix}ra3.userid = {$prefix}u.id AND {$prefix}ra3.roleid IN ($roleids) AND {$prefix}ra3.contextid IN ($ctxids))";
3037             }
3039             if ($prohibited) {
3040                 $ctxids = implode(',', $contextids);
3041                 $roleids = implode(',', array_keys($prohibited));
3042                 $joins[] = "LEFT JOIN {role_assignments} {$prefix}ra4 ON ({$prefix}ra4.userid = {$prefix}u.id AND {$prefix}ra4.roleid IN ($roleids) AND {$prefix}ra4.contextid IN ($ctxids))";
3043                 $wheres[] = "{$prefix}ra4.id IS NULL";
3044             }
3046             if ($groupid) {
3047                 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
3048                 $params["{$prefix}gmid"] = $groupid;
3049             }
3050         }
3052     } else {
3053         if ($groupid) {
3054             $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
3055             $params["{$prefix}gmid"] = $groupid;
3056         }
3057     }
3059     $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
3060     $params["{$prefix}guestid"] = $CFG->siteguest;
3062     if ($isfrontpage) {
3063         // all users are "enrolled" on the frontpage
3064     } else {
3065         $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
3066         $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
3067         $params[$prefix.'courseid'] = $coursecontext->instanceid;
3069         if ($onlyactive) {
3070             $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
3071             $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
3072             $now = round(time(), -2); // rounding helps caching in DB
3073             $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
3074                                                  $prefix.'active'=>ENROL_USER_ACTIVE,
3075                                                  $prefix.'now1'=>$now, $prefix.'now2'=>$now));
3076         }
3077     }
3079     $joins = implode("\n", $joins);
3080     $wheres = "WHERE ".implode(" AND ", $wheres);
3082     $sql = "SELECT DISTINCT {$prefix}u.id
3083                FROM {user} {$prefix}u
3084              $joins
3085             $wheres";
3087     return array($sql, $params);
3090 /**
3091  * Returns list of users enrolled into course.
3092  * @param object $context
3093  * @param string $withcapability
3094  * @param int $groupid 0 means ignore groups, any other value limits the result by group id
3095  * @param string $userfields requested user record fields
3096  * @param string $orderby
3097  * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
3098  * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
3099  * @return array of user records
3100  */
3101 function get_enrolled_users($context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
3102     global $DB;
3104     list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
3105     $sql = "SELECT $userfields
3106               FROM {user} u
3107               JOIN ($esql) je ON je.id = u.id
3108              WHERE u.deleted = 0";
3110     if ($orderby) {
3111         $sql = "$sql ORDER BY $orderby";
3112     } else {
3113         $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
3114     }
3116     return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3119 /**
3120  * Counts list of users enrolled into course (as per above function)
3121  * @param object $context
3122  * @param string $withcapability
3123  * @param int $groupid 0 means ignore groups, any other value limits the result by group id
3124  * @return array of user records
3125  */
3126 function count_enrolled_users($context, $withcapability = '', $groupid = 0) {
3127     global $DB;
3129     list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
3130     $sql = "SELECT count(u.id)
3131               FROM {user} u
3132               JOIN ($esql) je ON je.id = u.id
3133              WHERE u.deleted = 0";
3135     return $DB->count_records_sql($sql, $params);
3139 /**
3140  * Loads the capability definitions for the component (from file).
3141  *
3142  * Loads the capability definitions for the component (from file). If no
3143  * capabilities are defined for the component, we simply return an empty array.
3144  *
3145  * @global object
3146  * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
3147  * @return array array of capabilities
3148  */
3149 function load_capability_def($component) {
3150     $defpath = get_component_directory($component).'/db/access.php';
3152     $capabilities = array();
3153     if (file_exists($defpath)) {
3154         require($defpath);
3155         if (!empty(${$component.'_capabilities'})) {
3156             // BC capability array name
3157             // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
3158             debugging('componentname_capabilities array is deprecated, please use capabilities array only in access.php files');
3159             $capabilities = ${$component.'_capabilities'};
3160         }
3161     }
3163     return $capabilities;
3167 /**
3168  * Gets the capabilities that have been cached in the database for this component.
3169  * @param string $component - examples: 'moodle', 'mod_forum'
3170  * @return array array of capabilities
3171  */
3172 function get_cached_capabilities($component='moodle') {
3173     global $DB;
3174     return $DB->get_records('capabilities', array('component'=>$component));
3177 /**
3178  * Returns default capabilities for given role archetype.
3179  * @param string $archetype role archetype
3180  * @return array
3181  */
3182 function get_default_capabilities($archetype) {
3183     global $DB;
3185     if (!$archetype) {
3186         return array();
3187     }
3189     $alldefs = array();
3190     $defaults = array();
3191     $components = array();
3192     $allcaps = $DB->get_records('capabilities');
3194     foreach ($allcaps as $cap) {
3195         if (!in_array($cap->component, $components)) {
3196             $components[] = $cap->component;
3197             $alldefs = array_merge($alldefs, load_capability_def($cap->component));
3198         }
3199     }
3200     foreach($alldefs as $name=>$def) {
3201         // Use array 'archetypes if available. Only if not specified, use 'legacy'.
3202         if (isset($def['archetypes'])) {
3203             if (isset($def['archetypes'][$archetype])) {
3204                 $defaults[$name] = $def['archetypes'][$archetype];
3205             }
3206         // 'legacy' is for backward compatibility with 1.9 access.php
3207         } else {
3208             if (isset($def['legacy'][$archetype])) {
3209                 $defaults[$name] = $def['legacy'][$archetype];
3210             }
3211         }
3212     }
3214     return $defaults;
3217 /**
3218  * Reset role capabilities to default according to selected role archetype.
3219  * If no archetype selected, removes all capabilities.
3220  * @param int $roleid
3221  */
3222 function reset_role_capabilities($roleid) {
3223     global $DB;
3225     $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
3226     $defaultcaps = get_default_capabilities($role->archetype);
3228     $sitecontext = get_context_instance(CONTEXT_SYSTEM);
3230     $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
3232     foreach($defaultcaps as $cap=>$permission) {
3233         assign_capability($cap, $permission, $roleid, $sitecontext->id);
3234     }
3237 /**
3238  * Updates the capabilities table with the component capability definitions.
3239  * If no parameters are given, the function updates the core moodle
3240  * capabilities.
3241  *
3242  * Note that the absence of the db/access.php capabilities definition file
3243  * will cause any stored capabilities for the component to be removed from
3244  * the database.
3245  *
3246  * @global object
3247  * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
3248  * @return boolean true if success, exception in case of any problems
3249  */
3250 function update_capabilities($component='moodle') {
3251     global $DB, $OUTPUT, $ACCESSLIB_PRIVATE;
3253     $storedcaps = array();
3255     $filecaps = load_capability_def($component);
3256     $cachedcaps = get_cached_capabilities($component);
3257     if ($cachedcaps) {
3258         foreach ($cachedcaps as $cachedcap) {
3259             array_push($storedcaps, $cachedcap->name);
3260             // update risk bitmasks and context levels in existing capabilities if needed
3261             if (array_key_exists($cachedcap->name, $filecaps)) {
3262                 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
3263                     $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
3264                 }
3265                 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
3266                     $updatecap = new stdClass();
3267                     $updatecap->id = $cachedcap->id;
3268                     $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
3269                     $DB->update_record('capabilities', $updatecap);
3270                 }
3271                 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
3272                     $updatecap = new stdClass();
3273                     $updatecap->id = $cachedcap->id;
3274                     $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
3275                     $DB->update_record('capabilities', $updatecap);
3276                 }
3278                 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
3279                     $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
3280                 }
3281                 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
3282                     $updatecap = new stdClass();
3283                     $updatecap->id = $cachedcap->id;
3284                     $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
3285                     $DB->update_record('capabilities', $updatecap);
3286                 }
3287             }
3288         }
3289     }
3291     // Are there new capabilities in the file definition?
3292     $newcaps = array();
3294     foreach ($filecaps as $filecap => $def) {
3295         if (!$storedcaps ||
3296                 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
3297             if (!array_key_exists('riskbitmask', $def)) {
3298                 $def['riskbitmask'] = 0; // no risk if not specified
3299             }
3300             $newcaps[$filecap] = $def;
3301         }
3302     }
3303     // Add new capabilities to the stored definition.
3304     foreach ($newcaps as $capname => $capdef) {
3305         $capability = new stdClass();
3306         $capability->name = $capname;
3307         $capability->captype = $capdef['captype'];
3308         $capability->contextlevel = $capdef['contextlevel'];
3309         $capability->component = $component;
3310         $capability->riskbitmask = $capdef['riskbitmask'];
3312         $DB->insert_record('capabilities', $capability, false);
3314         if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
3315             if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
3316                 foreach ($rolecapabilities as $rolecapability){
3317                     //assign_capability will update rather than insert if capability exists
3318                     if (!assign_capability($capname, $rolecapability->permission,
3319                                             $rolecapability->roleid, $rolecapability->contextid, true)){
3320                          echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
3321                     }
3322                 }
3323             }
3324         // we ignore archetype key if we have cloned permissions
3325         } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
3326             assign_legacy_capabilities($capname, $capdef['archetypes']);
3327         // 'legacy' is for backward compatibility with 1.9 access.php
3328         } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
3329             assign_legacy_capabilities($capname, $capdef['legacy']);
3330         }
3331     }
3332     // Are there any capabilities that have been removed from the file
3333     // definition that we need to delete from the stored capabilities and
3334     // role assignments?
3335     capabilities_cleanup($component, $filecaps);
3337     // reset static caches
3338     $ACCESSLIB_PRIVATE->capabilities = NULL;
3340     return true;
3344 /**
3345  * Deletes cached capabilities that are no longer needed by the component.
3346  * Also unassigns these capabilities from any roles that have them.
3347  *
3348  * @global object
3349  * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
3350  * @param array $newcapdef array of the new capability definitions that will be
3351  *                     compared with the cached capabilities
3352  * @return int number of deprecated capabilities that have been removed
3353  */
3354 function capabilities_cleanup($component, $newcapdef=NULL) {
3355     global $DB;
3357     $removedcount = 0;
3359     if ($cachedcaps = get_cached_capabilities($component)) {
3360         foreach ($cachedcaps as $cachedcap) {
3361             if (empty($newcapdef) ||
3362                         array_key_exists($cachedcap->name, $newcapdef) === false) {
3364                 // Remove from capabilities cache.
3365                 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
3366                 $removedcount++;
3367                 // Delete from roles.
3368                 if ($roles = get_roles_with_capability($cachedcap->name)) {
3369                     foreach($roles as $role) {
3370                         if (!unassign_capability($cachedcap->name, $role->id)) {
3371                             print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
3372                         }
3373                     }
3374                 }
3375             } // End if.
3376         }
3377     }
3378     return $removedcount;
3383 //////////////////
3384 // UI FUNCTIONS //
3385 //////////////////
3387 /**
3388  * @param integer $contextlevel $context->context level. One of the CONTEXT_... constants.
3389  * @return string the name for this type of context.
3390  */
3391 function get_contextlevel_name($contextlevel) {
3392     static $strcontextlevels = NULL;
3393     if (is_null($strcontextlevels)) {
3394         $strcontextlevels = array(
3395             CONTEXT_SYSTEM => get_string('coresystem'),
3396             CONTEXT_USER => get_string('user'),
3397             CONTEXT_COURSECAT => get_string('category'),
3398             CONTEXT_COURSE => get_string('course'),
3399             CONTEXT_MODULE => get_string('activitymodule'),
3400             CONTEXT_BLOCK => get_string('block')
3401         );
3402     }
3403     return $strcontextlevels[$contextlevel];
3406 /**
3407  * Prints human readable context identifier.
3408  *
3409  * @global object
3410  * @param object $context the context.
3411  * @param boolean $withprefix whether to prefix the name of the context with the
3412  *      type of context, e.g. User, Course, Forum, etc.
3413  * @param boolean $short whether to user the short name of the thing. Only applies
3414  *      to course contexts
3415  * @return string the human readable context name.
3416  */
3417 function print_context_name($context, $withprefix = true, $short = false) {
3418     global $DB;
3420     $name = '';
3421     switch ($context->contextlevel) {
3423         case CONTEXT_SYSTEM:
3424             $name = get_string('coresystem');
3425             break;
3427         case CONTEXT_USER:
3428             if ($user = $DB->get_record('user', array('id'=>$context->instanceid))) {
3429                 if ($withprefix){
3430                     $name = get_string('user').': ';
3431                 }
3432                 $name .= fullname($user);
3433             }
3434             break;
3436         case CONTEXT_COURSECAT:
3437             if ($category = $DB->get_record('course_categories', array('id'=>$context->instanceid))) {
3438                 if ($withprefix){
3439                     $name = get_string('category').': ';
3440                 }
3441                 $name .=format_string($category->name);
3442             }
3443             break;
3445         case CONTEXT_COURSE:
3446             if ($context->instanceid == SITEID) {
3447                 $name = get_string('frontpage', 'admin');
3448             } else {
3449                 if ($course = $DB->get_record('course', array('id'=>$context->instanceid))) {
3450                     if ($withprefix){
3451                         $name = get_string('course').': ';
3452                     }
3453                     if ($short){
3454                         $name .= format_string($course->shortname);
3455                     } else {
3456                         $name .= format_string($course->fullname);
3457                    }
3458                 }
3459             }
3460             break;
3462         case CONTEXT_MODULE:
3463             if ($cm = $DB->get_record_sql('SELECT cm.*, md.name AS modname FROM {course_modules} cm ' .
3464                     'JOIN {modules} md ON md.id = cm.module WHERE cm.id = ?', array($context->instanceid))) {
3465                 if ($mod = $DB->get_record($cm->modname, array('id' => $cm->instance))) {
3466                         if ($withprefix){
3467                         $name = get_string('modulename', $cm->modname).': ';
3468                         }
3469                         $name .= $mod->name;
3470                     }
3471                 }
3472             break;
3474         case CONTEXT_BLOCK:
3475             if ($blockinstance = $DB->get_record('block_instances', array('id'=>$context->instanceid))) {
3476                 global $CFG;
3477                 require_once("$CFG->dirroot/blocks/moodleblock.class.php");
3478                 require_once("$CFG->dirroot/blocks/$blockinstance->blockname/block_$blockinstance->blockname.php");
3479                 $blockname = "block_$blockinstance->blockname";
3480                 if ($blockobject = new $blockname()) {
3481                     if ($withprefix){
3482                         $name = get_string('block').': ';
3483                     }
3484                     $name .= $blockobject->title;
3485                 }
3486             }
3487             break;
3489         default:
3490             print_error('unknowncontext');
3491             return false;
3492     }
3494     return $name;
3497 /**
3498  * Get a URL for a context, if there is a natural one. For example, for
3499  * CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
3500  * user profile page.
3501  *
3502  * @param object $context the context.
3503  * @return moodle_url
3504  */
3505 function get_context_url($context) {
3506     global $COURSE, $DB;
3508     switch ($context->contextlevel) {
3509         case CONTEXT_USER:
3510             if ($COURSE->id == SITEID) {
3511                 $url = new moodle_url('/user/profile.php', array('id'=>$context->instanceid));
3512             } else {
3513                 $url = new moodle_url('/user/view.php', array('id'=>$context->instanceid, 'courseid'=>$COURSE->id));
3514             }
3515             return $url;;
3517         case CONTEXT_COURSECAT: // Coursecat -> coursecat or site
3518             return new moodle_url('/course/category.php', array('id'=>$context->instanceid));
3520         case CONTEXT_COURSE: // 1 to 1 to course cat
3521             if ($context->instanceid != SITEID) {
3522                 return new moodle_url('/course/view.php', array('id'=>$context->instanceid));
3523             }
3524             break;
3526         case CONTEXT_MODULE: // 1 to 1 to course
3527             if ($modname = $DB->get_field_sql('SELECT md.name AS modname FROM {course_modules} cm ' .
3528                     'JOIN {modules} md ON md.id = cm.module WHERE cm.id = ?', array($context->instanceid))) {
3529                 return new moodle_url('/mod/' . $modname . '/view.php', array('id'=>$context->instanceid));
3530             }
3531             break;
3533         case CONTEXT_BLOCK:
3534             $parentcontexts = get_parent_contexts($context, false);
3535             $parent = reset($parentcontexts);
3536             $parent = get_context_instance_by_id($parent);
3537             return get_context_url($parent);
3538     }
3540     return new moodle_url('/');
3543 /**
3544  * Returns an array of all the known types of risk
3545  * The array keys can be used, for example as CSS class names, or in calls to
3546  * print_risk_icon. The values are the corresponding RISK_ constants.
3547  *
3548  * @return array all the known types of risk.
3549  */
3550 function get_all_risks() {
3551     return array(
3552         'riskmanagetrust' => RISK_MANAGETRUST,
3553         'riskconfig' => RISK_CONFIG,
3554         'riskxss' => RISK_XSS,
3555         'riskpersonal' => RISK_PERSONAL,
3556         'riskspam' => RISK_SPAM,
3557         'riskdataloss' => RISK_DATALOSS,
3558     );
3561 /**
3562  * Return a link to moodle docs for a given capability name
3563  *
3564  * @global object
3565  * @param object $capability a capability - a row from the mdl_capabilities table.
3566  * @return string the human-readable capability name as a link to Moodle Docs.
3567  */
3568 function get_capability_docs_link($capability) {
3569     global $CFG;
3570     $url = get_docs_url('Capabilities/' . $capability->name);
3571     return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
3574 /**
3575  * Extracts the relevant capabilities given a contextid.
3576  * All case based, example an instance of forum context.
3577  * Will fetch all forum related capabilities, while course contexts
3578  * Will fetch all capabilities
3579  *
3580  * capabilities
3581  * `name` varchar(150) NOT NULL,
3582  * `captype` varchar(50) NOT NULL,
3583  * `contextlevel` int(10) NOT NULL,
3584  * `component` varchar(100) NOT NULL,
3585  *
3586  * @global object
3587  * @global object
3588  * @param object context
3589  * @return array
3590  */
3591 function fetch_context_capabilities($context) {
3592     global $DB, $CFG;
3594     $sort = 'ORDER BY contextlevel,component,name';   // To group them sensibly for display
3596     $params = array();
3598     switch ($context->contextlevel) {
3600         case CONTEXT_SYSTEM: // all
3601             $SQL = "SELECT *
3602                       FROM {capabilities}";
3603         break;
3605         case CONTEXT_USER:
3606             $extracaps = array('moodle/grade:viewall');
3607             list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap0');
3608             $SQL = "SELECT *
3609                       FROM {capabilities}
3610                      WHERE contextlevel = ".CONTEXT_USER."
3611                            OR name $extra";
3612         break;
3614         case CONTEXT_COURSECAT: // course category context and bellow
3615             $SQL = "SELECT *
3616                       FROM {capabilities}
3617                      WHERE contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
3618         break;
3620         case CONTEXT_COURSE: // course context and bellow
3621             $SQL = "SELECT *
3622                       FROM {capabilities}
3623                      WHERE contextlevel IN (".CONTEXT_COURSE.",".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
3624         break;
3626         case CONTEXT_MODULE: // mod caps
3627             $cm = $DB->get_record('course_modules', array('id'=>$context->instanceid));
3628             $module = $DB->get_record('modules', array('id'=>$cm->module));
3630             $modfile = "$CFG->dirroot/mod/$module->name/lib.php";
3631             if (file_exists($modfile)) {
3632                 include_once($modfile);
3633                 $modfunction = $module->name.'_get_extra_capabilities';
3634                 if (function_exists($modfunction)) {
3635                     $extracaps = $modfunction();
3636                 }
3637             }
3638             if(empty($extracaps)) {
3639                 $extracaps = array();
3640             }
3642             // All modules allow viewhiddenactivities. This is so you can hide
3643             // the module then override to allow specific roles to see it.
3644             // The actual check is in course page so not module-specific
3645             $extracaps[]="moodle/course:viewhiddenactivities";
3646             list($extra, $params) = $DB->get_in_or_equal(
3647                 $extracaps, SQL_PARAMS_NAMED, 'cap0');
3648             $extra = "OR name $extra";
3650             $SQL = "SELECT *
3651                       FROM {capabilities}
3652                      WHERE (contextlevel = ".CONTEXT_MODULE."
3653                            AND component = :component)
3654                            $extra";
3655             $params['component'] = "mod_$module->name";
3656         break;
3658         case CONTEXT_BLOCK: // block caps
3659             $bi = $DB->get_record('block_instances', array('id' => $context->instanceid));
3661             $extra = '';
3662             $extracaps = block_method_result($bi->blockname, 'get_extra_capabilities');
3663             if ($extracaps) {
3664                 list($extra, $params) = $DB->get_in_or_equal($extracaps, SQL_PARAMS_NAMED, 'cap0');
3665                 $extra = "OR name $extra";
3666             }
3668             $SQL = "SELECT *
3669                       FROM {capabilities}
3670                      WHERE (contextlevel = ".CONTEXT_BLOCK."
3671                            AND component = :component)
3672                            $extra";
3673             $params['component'] = 'block_' . $bi->blockname;
3674         break;
3676         default:
3677         return false;
3678     }
3680     if (!$records = $DB->get_records_sql($SQL.' '.$sort, $params)) {
3681         $records = array();
3682     }
3684     return $records;
3688 /**
3689  * This function pulls out all the resolved capabilities (overrides and
3690  * defaults) of a role used in capability overrides in contexts at a given
3691  * context.
3692  *
3693  * @global object
3694  * @param obj $context
3695  * @param int $roleid
3696  * @param string $cap capability, optional, defaults to ''
3697  * @param bool if set to true, resolve till this level, else stop at immediate parent level
3698  * @return array
3699  */
3700 function role_context_capabilities($roleid, $context, $cap='') {
3701     global $DB;
3703     $contexts = get_parent_contexts($context);
3704     $contexts[] = $context->id;
3705     $contexts = '('.implode(',', $contexts).')';
3707     $params = array($roleid);
3709     if ($cap) {
3710         $search = " AND rc.capability = ? ";
3711         $params[] = $cap;
3712     } else {
3713         $search = '';
3714     }
3716     $sql = "SELECT rc.*
3717               FROM {role_capabilities} rc, {context} c
3718              WHERE rc.contextid in $contexts
3719                    AND rc.roleid = ?
3720                    AND rc.contextid = c.id $search
3721           ORDER BY c.contextlevel DESC, rc.capability DESC";
3723     $capabilities = array();
3725     if ($records = $DB->get_records_sql($sql, $params)) {
3726         // We are traversing via reverse order.
3727         foreach ($records as $record) {
3728             // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
3729             if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
3730                 $capabilities[$record->capability] = $record->permission;
3731             }
3732         }
3733     }
3734     return $capabilities;
3737 /**
3738  * Recursive function which, given a context, find all parent context ids,
3739  * and return the array in reverse order, i.e. parent first, then grand
3740  * parent, etc.
3741  *
3742  * @param object $context
3743  * @param bool $capability optional, defaults to false
3744  * @return array
3745  */
3746 function get_parent_contexts($context, $includeself = false) {
3748     if ($context->path == '') {
3749         return array();
3750     }
3752     $parentcontexts = substr($context->path, 1); // kill leading slash
3753     $parentcontexts = explode('/', $parentcontexts);
3754     if (!$includeself) {
3755         array_pop($parentcontexts); // and remove its own id
3756     }
3758     return array_reverse($parentcontexts);
3761 /**
3762  * Return the id of the parent of this context, or false if there is no parent (only happens if this
3763  * is the site context.)
3764  *
3765  * @param object $context
3766  * @return integer the id of the parent context.
3767  */
3768 function get_parent_contextid($context) {
3769     $parentcontexts = get_parent_contexts($context);
3770     if (count($parentcontexts) == 0) {
3771         return false;
3772     }
3773     return array_shift($parentcontexts);
3776 /**
3777  * Constructs array with contextids as first parameter and context paths,
3778  * in both cases bottom top including self.
3779  *
3780  * @param object $context
3781  * @return array
3782  */
3783 function get_context_info_list($context) {
3784     $contextids = explode('/', ltrim($context->path, '/'));
3785     $contextpaths = array();
3786     $contextids2 = $contextids;
3787     while ($contextids2) {
3788         $contextpaths[] = '/' . implode('/', $contextids2);
3789         array_pop($contextids2);
3790     }
3791     return array($contextids, $contextpaths);
3794 /**
3795  * Find course context
3796  * @param object $context - course or lower context
3797  * @return object context of the enclosing course, throws exception when related course context can not be found
3798  */
3799 function get_course_context($context) {
3800     if (empty($context->contextlevel)) {
3801         throw new coding_exception('Invalid context parameter.');
3803     } if ($context->contextlevel == CONTEXT_COURSE) {
3804         return $context;
3806     } else if ($context->contextlevel == CONTEXT_MODULE) {
3807         return get_context_instance_by_id(get_parent_contextid($context, MUST_EXIST));
3809     } else if ($context->contextlevel == CONTEXT_BLOCK) {
3810         $parentcontext = get_context_instance_by_id(get_parent_contextid($context, MUST_EXIST));
3811         if ($parentcontext->contextlevel == CONTEXT_COURSE) {
3812             return $parentcontext;
3813         } else if ($parentcontext->contextlevel == CONTEXT_MODULE) {
3814             return get_context_instance_by_id(get_parent_contextid($parentcontext, MUST_EXIST));
3815         } else {
3816             throw new coding_exception('Invalid level of block context parameter.');
3817         }
3818     }
3820     throw new coding_exception('Invalid context level of parameter.');
3823 /**
3824  * Check if context is the front page context or a context inside it
3825  *
3826  * Returns true if this context is the front page context, or a context inside it,
3827  * otherwise false.
3828  *
3829  * @param object $context a context object.
3830  * @return bool
3831  */
3832 function is_inside_frontpage($context) {
3833     $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
3834     return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
3837 /**
3838  * Runs get_records select on context table and returns the result
3839  * Does get_records_select on the context table, and returns the results ordered
3840  * by contextlevel, and then the natural sort order within each level.
3841  * for the purpose of $select, you need to know that the context table has been
3842  * aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');
3843  *
3844  * @global object
3845  * @param string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
3846  * @param array $params any parameters required by $select.
3847  * @return array the requested context records.
3848  */
3849 function get_sorted_contexts($select, $params = array()) {
3850     global $DB;
3851     if ($select) {
3852         $select = 'WHERE ' . $select;
3853     }
3854     return $DB->get_records_sql("
3855             SELECT ctx.*
3856             FROM {context} ctx
3857             LEFT JOIN {user} u ON ctx.contextlevel = " . CONTEXT_USER . " AND u.id = ctx.instanceid
3858             LEFT JOIN {course_categories} cat ON ctx.contextlevel = " . CONTEXT_COURSECAT . " AND cat.id = ctx.instanceid
3859             LEFT JOIN {course} c ON ctx.contextlevel = " . CONTEXT_COURSE . " AND c.id = ctx.instanceid
3860             LEFT JOIN {course_modules} cm ON ctx.contextlevel = " . CONTEXT_MODULE . " AND cm.id = ctx.instanceid
3861             LEFT JOIN {block_instances} bi ON ctx.contextlevel = " . CONTEXT_BLOCK . " AND bi.id = ctx.instanceid
3862             $select
3863             ORDER BY ctx.contextlevel, bi.defaultregion, COALESCE(cat.sortorder, c.sortorder, cm.section, bi.defaultweight), u.lastname, u.firstname, cm.id
3864             ", $params);
3867 /**
3868  * Recursive function which, given a context, find all its children context ids.
3869  *
3870  * When called for a course context, it will return the modules and blocks
3871  * displayed in the course page.
3872  *
3873  * For course category contexts it will return categories and courses. It will
3874  * NOT recurse into courses, nor return blocks on the category pages. If you
3875  * want to do that, call it on the returned courses.
3876  *
3877  * If called on a course context it _will_ populate the cache with the appropriate
3878  * contexts ;-)
3879  *
3880  * @param object $context.
3881  * @return array Array of child records
3882  */
3883 function get_child_contexts($context) {
3885     global $DB, $ACCESSLIB_PRIVATE;
3887     // We *MUST* populate the context_cache as the callers
3888     // will probably ask for the full record anyway soon after
3889     // soon after calling us ;-)
3891     $array = array();
3893     switch ($context->contextlevel) {
3895         case CONTEXT_BLOCK:
3896             // No children.
3897         break;
3899         case CONTEXT_MODULE:
3900             // Find
3901             // - blocks under this context path.
3902             $sql = " SELECT ctx.*
3903                        FROM {context} ctx
3904                       WHERE ctx.path LIKE ?
3905                             AND ctx.contextlevel = ".CONTEXT_BLOCK;
3906             $params = array("{$context->path}/%", $context->instanceid);
3907             $records = $DB->get_recordset_sql($sql, $params);
3908             foreach ($records as $rec) {
3909                 cache_context($rec);
3910                 $array[$rec->id] = $rec;
3911             }
3912             break;
3914         case CONTEXT_COURSE:
3915             // Find
3916             // - modules and blocks under this context path.
3917             $sql = " SELECT ctx.*
3918                        FROM {context} ctx
3919                       WHERE ctx.path LIKE ?
3920                             AND ctx.contextlevel IN (".CONTEXT_MODULE.",".CONTEXT_BLOCK.")";
3921             $params = array("{$context->path}/%", $context->instanceid);
3922             $records = $DB->get_recordset_sql($sql, $params);
3923             foreach ($records as $rec) {
3924                 cache_context($rec);
3925                 $array[$rec->id] = $rec;
3926             }
3927         break;
3929         case CONTEXT_COURSECAT:
3930             // Find
3931             // - categories
3932             // - courses
3933             $sql = " SELECT ctx.*
3934                        FROM {context} ctx
3935                       WHERE ctx.path LIKE ?
3936                             AND ctx.contextlevel IN (".CONTEXT_COURSECAT.",".CONTEXT_COURSE.")";
3937             $params = array("{$context->path}/%");
3938             $records = $DB->get_recordset_sql($sql, $params);
3939             foreach ($records as $rec) {
3940                 cache_context($rec);
3941                 $array[$rec->id] = $rec;
3942             }
3943         break;
3945         case CONTEXT_USER:
3946             // Find
3947             // - blocks under this context path.
3948             $sql = " SELECT ctx.*
3949                        FROM {context} ctx
3950                       WHERE ctx.path LIKE ?
3951                             AND ctx.contextlevel = ".CONTEXT_BLOCK;
3952             $params = array("{$context->path}/%", $context->instanceid);
3953             $records = $DB->get_recordset_sql($sql, $params);
3954             foreach ($records as $rec) {
3955                 cache_context($rec);
3956                 $array[$rec->id] = $rec;
3957             }
3958             break;
3960         case CONTEXT_SYSTEM:
3961             // Just get all the contexts except for CONTEXT_SYSTEM level
3962             // and hope we don't OOM in the process - don't cache
3963             $sql = "SELECT c.*
3964                       FROM {context} c
3965                      WHERE contextlevel != ".CONTEXT_SYSTEM;
3967             $records = $DB->get_records_sql($sql);
3968             foreach ($records as $rec) {
3969                 $array[$rec->id] = $rec;
3970             }
3971         break;
3973         default:
3974             print_error('unknowcontext', '', '', $context->contextlevel);
3975             return false;
3976     }
3977     return $array;
3981 /**
3982  * Gets a string for sql calls, searching for stuff in this context or above
3983  *
3984  * @param object $context
3985  * @return string
3986  */
3987 function get_related_contexts_string($context) {
3988     if ($parents = get_parent_contexts($context)) {
3989         return (' IN ('.$context->id.','.implode(',', $parents).')');
3990     } else {
3991         return (' ='.$context->id);
3992     }
3995 /**
3996  * Returns capability information (cached)
3997  *
3998  * @param string $capabilityname
3999  * @return object or NULL if capability not found
4000  */
4001 function get_capability_info($capabilityname) {
4002     global $ACCESSLIB_PRIVATE, $DB; // one request per page only
4004     // TODO: cache this in shared memory if available, use new $CFG->roledefrev for version check
4006     if (empty($ACCESSLIB_PRIVATE->capabilities)) {
4007         $ACCESSLIB_PRIVATE->capabilities = array();
4008         $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
4009         foreach ($caps as $cap) {
4010             $capname = $cap->name;
4011             unset($cap->id);
4012             unset($cap->name);
4013             $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
4014         }
4015     }
4017     return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : NULL;
4020 /**
4021  * Returns the human-readable, translated version of the capability.
4022  * Basically a big switch statement.
4023  *
4024  * @param string $capabilityname e.g. mod/choice:readresponses
4025  * @return string
4026  */
4027 function get_capability_string($capabilityname) {
4029     // Typical capability name is 'plugintype/pluginname:capabilityname'
4030     list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
4032     if ($type === 'moodle') {
4033         $component = 'core_role';
4034     } else if ($type === 'quizreport') {
4035         //ugly hack!!
4036         $component = 'quiz_'.$name;
4037     } else {
4038         $component = $type.'_'.$name;
4039     }
4041     $stringname = $name.':'.$capname;
4043     if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
4044         return get_string($stringname, $component);
4045     }
4047     $dir = get_component_directory($component);
4048     if (!file_exists($dir)) {
4049         // plugin broken or does not exist, do not bother with printing of debug message
4050         return $capabilityname.' ???';
4051     }
4053     // something is wrong in plugin, better print debug
4054     return get_string($stringname, $component);
4058 /**
4059  * This gets the mod/block/course/core etc strings.
4060  *
4061  * @param string $component
4062  * @param int $contextlevel
4063  * @return string|bool String is success, false if failed
4064  */
4065 function get_component_string($component, $contextlevel) {
4067     if ($component === 'moodle' or $component === 'core') {
4068         switch ($contextlevel) {
4069             case CONTEXT_SYSTEM:    return get_string('coresystem');
4070             case CONTEXT_USER:      return get_string('users');
4071             case CONTEXT_COURSECAT: return get_string('categories');
4072             case CONTEXT_COURSE:    return get_string('course');
4073             case CONTEXT_MODULE:    return get_string('activities');
4074             case CONTEXT_BLOCK:     return get_string('block');
4075             default:                print_error('unknowncontext');
4076         }
4077     }
4079     list($type, $name) = normalize_component($component);
4080     $dir = get_plugin_directory($type, $name);
4081     if (!file_exists($dir)) {
4082         // plugin not installed, bad luck, there is no way to find the name
4083         return $component.' ???';
4084     }
4086     switch ($type) {
4087         case 'quiz':         return get_string($name.':componentname', $component);// insane hack!!!
4088         case 'repository':   return get_string('repository', 'repository').': '.get_string('pluginname', $component);
4089         case 'gradeimport':  return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
4090         case 'gradeexport':  return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
4091         case 'gradereport':  return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
4092         case 'webservice':   return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
4093         case 'block':        return get_string('block').': '.get_string('pluginname', basename($component));
4094         case 'mod':
4095             if (get_string_manager()->string_exists('pluginname', $component)) {
4096                 return get_string('activity').': '.get_string('pluginname', $component);
4097             } else {
4098                 return get_string('activity').': '.get_string('modulename', $component);
4099             }
4100         default: return get_string('pluginname', $component);
4101     }
4104 /**
4105  * Gets the list of roles assigned to this context and up (parents)
4106  * from the list of roles that are visible on user profile page
4107  * and participants page.
4108  *
4109  * @param object $context
4110  * @return array
4111  */
4112 function get_profile_roles($context) {
4113     global $CFG, $DB;
4115     if (empty($CFG->profileroles)) {
4116         return array();
4117     }
4119     $allowed = explode(',', $CFG->profileroles);
4120     list($rallowed, $params) = $DB->get_in_or_equal($allowed, SQL_PARAMS_NAMED);
4122     $contextlist = get_related_contexts_string($context);
4124     $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
4125               FROM {role_assignments} ra, {role} r
4126              WHERE r.id = ra.roleid
4127                    AND ra.contextid $contextlist
4128                    AND r.id $rallowed
4129           ORDER BY r.sortorder ASC";
4131     return $DB->get_records_sql($sql, $params);
4134 /**
4135  * Gets the list of roles assigned to this context and up (parents)
4136  *
4137  * @param object $context
4138  * @return array
4139  */
4140 function get_roles_used_in_context($context) {
4141     global $DB;
4143     $contextlist = get_related_contexts_string($context);
4145     $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
4146               FROM {role_assignments} ra, {role} r
4147              WHERE r.id = ra.roleid
4148                    AND ra.contextid $contextlist
4149           ORDER BY r.sortorder ASC";
4151     return $DB->get_records_sql($sql);
4154 /**
4155  * This function is used to print roles column in user profile page.
4156  * It is using the CFG->profileroles to limit the list to only interesting roles.
4157  * (The permission tab has full details of user role assignments.)
4158  *
4159  * @param int $userid
4160  * @param int $courseid
4161  * @return string
4162  */
4163 function get_user_roles_in_course($userid, $courseid) {
4164     global $CFG, $DB,$USER;
4166     if (empty($CFG->profileroles)) {
4167         return '';
4168     }
4170     if ($courseid == SITEID) {
4171         $context = get_context_instance(CONTEXT_SYSTEM);
4172     } else {
4173         $context = get_context_instance(CONTEXT_COURSE, $courseid);
4174     }
4176     if (empty($CFG->profileroles)) {
4177         return array();
4178     }
4180     $allowed = explode(',', $CFG->profileroles);
4181     list($rallowed, $params) = $DB->get_in_or_equal($allowed, SQL_PARAMS_NAMED);
4183     $contextlist = get_related_contexts_string($context);
4185     $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
4186               FROM {role_assignments} ra, {role} r
4187              WHERE r.id = ra.roleid
4188                    AND ra.contextid $contextlist
4189                    AND r.id $rallowed
4190                    AND ra.userid = :userid
4191           ORDER BY r.sortorder ASC";
4192     $params['userid'] = $userid;
4194     $rolestring = '';
4196     if ($roles = $DB->get_records_sql($sql, $params)) {
4197         foreach ($roles as $userrole) {
4198             $rolenames[$userrole->id] = $userrole->name;
4199         }
4201         $rolenames = role_fix_names($rolenames, $context);   // Substitute aliases
4203         foreach ($rolenames as $roleid => $rolename) {
4204             $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
4205         }
4206         $rolestring = implode(',', $rolenames);
4207     }
4209     return $rolestring;
4212 /**
4213  * Checks if a user can assign users to a particular role in this context
4214  *
4215  * @global object
4216  * @param object $context
4217  * @param int $targetroleid - the id of the role you want to assign users to
4218  * @return boolean
4219  */
4220 function user_can_assign($context, $targetroleid) {
4221     global $DB;
4223     // first check if user has override capability
4224     // if not return false;
4225     if (!has_capability('moodle/role:assign', $context)) {
4226         return false;
4227     }
4228     // pull out all active roles of this user from this context(or above)
4229     if ($userroles = get_user_roles($context)) {
4230         foreach ($userroles as $userrole) {
4231             // if any in the role_allow_override table, then it's ok
4232             if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
4233                 return true;
4234             }
4235         }
4236     }
4238     return false;
4241 /**
4242  * Returns all site roles in correct sort order.
4243  *
4244  * @return array
4245  */
4246 function get_all_roles() {
4247     global $DB;
4248     return $DB->get_records('role', NULL, 'sortorder ASC');
4251 /**
4252  * Returns roles of a specified archetype
4253  * @param string $archetype
4254  * @return array of full role records
4255  */
4256 function get_archetype_roles($archetype) {
4257     global $DB;
4258     return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
4261 /**
4262  * Gets all the user roles assigned in this context, or higher contexts
4263  * this is mainly used when checking if a user can assign a role, or overriding a role
4264  * i.e. we need to know what this user holds, in order to verify against allow_assign and
4265  * allow_override tables
4266  *
4267  * @param object $context
4268  * @param int $userid
4269  * @param bool $checkparentcontexts defaults to true
4270  * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
4271  * @return array
4272  */
4273 function get_user_roles($context, $userid=0, $checkparentcontexts=true, $order='c.contextlevel DESC, r.sortorder ASC') {
4274     global $USER, $DB;
4276     if (empty($userid)) {
4277         if (empty($USER->id)) {
4278             return array();
4279         }
4280         $userid = $USER->id;
4281     }
4283     if ($checkparentcontexts) {
4284         $contextids = get_parent_contexts($context);
4285     } else {
4286         $contextids = array();
4287     }
4288     $contextids[] = $context->id;
4290     list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
4292     array_unshift($params, $userid);
4294     $sql = "SELECT ra.*, r.name, r.shortname
4295               FROM {role_assignments} ra, {role} r, {context} c
4296              WHERE ra.userid = ?
4297                    AND ra.roleid = r.id
4298                    AND ra.contextid = c.id
4299                    AND ra.contextid $contextids
4300           ORDER BY $order";
4302     return $DB->get_records_sql($sql ,$params);
4305 /**
4306  * Creates a record in the role_allow_override table
4307  *
4308  * @global object
4309  * @param int $sroleid source roleid
4310  * @param int $troleid target roleid
4311  * @return int id or false
4312  */