Merge branch 'MDL-30631' of git://github.com/kiklop74/moodle
[moodle.git] / lib / accesslib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * This file contains functions for managing user access
19  *
20  * <b>Public API vs internals</b>
21  *
22  * General users probably only care about
23  *
24  * Context handling
25  * - context_course::instance($courseid), context_module::instance($cm->id), context_coursecat::instance($catid)
26  * - context::instance_by_id($contextid)
27  * - $context->get_parent_contexts();
28  * - $context->get_child_contexts();
29  *
30  * Whether the user can do something...
31  * - has_capability()
32  * - has_any_capability()
33  * - has_all_capabilities()
34  * - require_capability()
35  * - require_login() (from moodlelib)
36  * - is_siteadmin()
37  *
38  * What courses has this user access to?
39  * - get_enrolled_users()
40  *
41  * What users can do X in this context?
42  * - get_users_by_capability()
43  *
44  * Modify roles
45  * - role_assign()
46  * - role_unassign()
47  * - role_unassign_all()
48  *
49  *
50  * Advanced - for internal use only
51  * - load_all_capabilities()
52  * - reload_all_capabilities()
53  * - has_capability_in_accessdata()
54  * - get_user_access_sitewide()
55  * - load_course_context()
56  * - load_role_access_by_context()
57  * - etc.
58  *
59  * <b>Name conventions</b>
60  *
61  * "ctx" means context
62  *
63  * <b>accessdata</b>
64  *
65  * Access control data is held in the "accessdata" array
66  * which - for the logged-in user, will be in $USER->access
67  *
68  * For other users can be generated and passed around (but may also be cached
69  * against userid in $ACCESSLIB_PRIVATE->accessdatabyuser).
70  *
71  * $accessdata is a multidimensional array, holding
72  * role assignments (RAs), role-capabilities-perm sets
73  * (role defs) and a list of courses we have loaded
74  * data for.
75  *
76  * Things are keyed on "contextpaths" (the path field of
77  * the context table) for fast walking up/down the tree.
78  * <code>
79  * $accessdata['ra'][$contextpath] = array($roleid=>$roleid)
80  *                  [$contextpath] = array($roleid=>$roleid)
81  *                  [$contextpath] = array($roleid=>$roleid)
82  * </code>
83  *
84  * Role definitions are stored like this
85  * (no cap merge is done - so it's compact)
86  *
87  * <code>
88  * $accessdata['rdef']["$contextpath:$roleid"]['mod/forum:viewpost'] = 1
89  *                                            ['mod/forum:editallpost'] = -1
90  *                                            ['mod/forum:startdiscussion'] = -1000
91  * </code>
92  *
93  * See how has_capability_in_accessdata() walks up the tree.
94  *
95  * First we only load rdef and ra down to the course level, but not below.
96  * This keeps accessdata small and compact. Below-the-course ra/rdef
97  * are loaded as needed. We keep track of which courses we have loaded ra/rdef in
98  * <code>
99  * $accessdata['loaded'] = array($courseid1=>1, $courseid2=>1)
100  * </code>
101  *
102  * <b>Stale accessdata</b>
103  *
104  * For the logged-in user, accessdata is long-lived.
105  *
106  * On each pageload we load $ACCESSLIB_PRIVATE->dirtycontexts which lists
107  * context paths affected by changes. Any check at-or-below
108  * a dirty context will trigger a transparent reload of accessdata.
109  *
110  * Changes at the system level will force the reload for everyone.
111  *
112  * <b>Default role caps</b>
113  * The default role assignment is not in the DB, so we
114  * add it manually to accessdata.
115  *
116  * This means that functions that work directly off the
117  * DB need to ensure that the default role caps
118  * are dealt with appropriately.
119  *
120  * @package    core
121  * @subpackage role
122  * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
123  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
124  */
126 defined('MOODLE_INTERNAL') || die();
128 /** No capability change */
129 define('CAP_INHERIT', 0);
130 /** Allow permission, overrides CAP_PREVENT defined in parent contexts */
131 define('CAP_ALLOW', 1);
132 /** Prevent permission, overrides CAP_ALLOW defined in parent contexts */
133 define('CAP_PREVENT', -1);
134 /** Prohibit permission, overrides everything in current and child contexts */
135 define('CAP_PROHIBIT', -1000);
137 /** System context level - only one instance in every system */
138 define('CONTEXT_SYSTEM', 10);
139 /** User context level -  one instance for each user describing what others can do to user */
140 define('CONTEXT_USER', 30);
141 /** Course category context level - one instance for each category */
142 define('CONTEXT_COURSECAT', 40);
143 /** Course context level - one instances for each course */
144 define('CONTEXT_COURSE', 50);
145 /** Course module context level - one instance for each course module */
146 define('CONTEXT_MODULE', 70);
147 /**
148  * Block context level - one instance for each block, sticky blocks are tricky
149  * because ppl think they should be able to override them at lower contexts.
150  * Any other context level instance can be parent of block context.
151  */
152 define('CONTEXT_BLOCK', 80);
154 /** Capability allow management of trusts - NOT IMPLEMENTED YET - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
155 define('RISK_MANAGETRUST', 0x0001);
156 /** Capability allows changes in system configuration - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
157 define('RISK_CONFIG',      0x0002);
158 /** Capability allows user to add scritped content - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
159 define('RISK_XSS',         0x0004);
160 /** Capability allows access to personal user information - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
161 define('RISK_PERSONAL',    0x0008);
162 /** Capability allows users to add content otehrs may see - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
163 define('RISK_SPAM',        0x0010);
164 /** capability allows mass delete of data belonging to other users - see {@link http://docs.moodle.org/dev/Hardening_new_Roles_system} */
165 define('RISK_DATALOSS',    0x0020);
167 /** rolename displays - the name as defined in the role definition */
168 define('ROLENAME_ORIGINAL', 0);
169 /** rolename displays - the name as defined by a role alias */
170 define('ROLENAME_ALIAS', 1);
171 /** rolename displays - Both, like this:  Role alias (Original) */
172 define('ROLENAME_BOTH', 2);
173 /** rolename displays - the name as defined in the role definition and the shortname in brackets */
174 define('ROLENAME_ORIGINALANDSHORT', 3);
175 /** rolename displays - the name as defined by a role alias, in raw form suitable for editing */
176 define('ROLENAME_ALIAS_RAW', 4);
177 /** rolename displays - the name is simply short role name */
178 define('ROLENAME_SHORT', 5);
180 /** maximum size of context cache - it is possible to tweak this config.php or in any script before inclusion of context.php */
181 if (!defined('CONTEXT_CACHE_MAX_SIZE')) {
182     define('CONTEXT_CACHE_MAX_SIZE', 2500);
185 /**
186  * Although this looks like a global variable, it isn't really.
187  *
188  * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
189  * It is used to cache various bits of data between function calls for performance reasons.
190  * Sadly, a PHP global variable is the only way to implement this, without rewriting everything
191  * as methods of a class, instead of functions.
192  *
193  * @private
194  * @global stdClass $ACCESSLIB_PRIVATE
195  * @name $ACCESSLIB_PRIVATE
196  */
197 global $ACCESSLIB_PRIVATE;
198 $ACCESSLIB_PRIVATE = new stdClass();
199 $ACCESSLIB_PRIVATE->dirtycontexts    = null;    // Dirty contexts cache, loaded from DB once per page
200 $ACCESSLIB_PRIVATE->accessdatabyuser = array(); // Holds the cache of $accessdata structure for users (including $USER)
201 $ACCESSLIB_PRIVATE->rolepermissions  = array(); // role permissions cache - helps a lot with mem usage
202 $ACCESSLIB_PRIVATE->capabilities     = null;    // detailed information about the capabilities
204 /**
205  * Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
206  *
207  * This method should ONLY BE USED BY UNIT TESTS. It clears all of
208  * accesslib's private caches. You need to do this before setting up test data,
209  * and also at the end of the tests.
210  *
211  * @return void
212  */
213 function accesslib_clear_all_caches_for_unit_testing() {
214     global $UNITTEST, $USER;
215     if (empty($UNITTEST->running)) {
216         throw new coding_exception('You must not call clear_all_caches outside of unit tests.');
217     }
219     accesslib_clear_all_caches(true);
221     unset($USER->access);
224 /**
225  * Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!
226  *
227  * This reset does not touch global $USER.
228  *
229  * @private
230  * @param bool $resetcontexts
231  * @return void
232  */
233 function accesslib_clear_all_caches($resetcontexts) {
234     global $ACCESSLIB_PRIVATE;
236     $ACCESSLIB_PRIVATE->dirtycontexts    = null;
237     $ACCESSLIB_PRIVATE->accessdatabyuser = array();
238     $ACCESSLIB_PRIVATE->rolepermissions  = array();
239     $ACCESSLIB_PRIVATE->capabilities     = null;
241     if ($resetcontexts) {
242         context_helper::reset_caches();
243     }
246 /**
247  * Gets the accessdata for role "sitewide" (system down to course)
248  *
249  * @private
250  * @param int $roleid
251  * @return array
252  */
253 function get_role_access($roleid) {
254     global $DB, $ACCESSLIB_PRIVATE;
256     /* Get it in 1 DB query...
257      * - relevant role caps at the root and down
258      *   to the course level - but not below
259      */
261     //TODO: MUC - this could be cached in shared memory to speed up first page loading, web crawlers, etc.
263     $accessdata = get_empty_accessdata();
265     $accessdata['ra']['/'.SYSCONTEXTID] = array((int)$roleid => (int)$roleid);
267     //
268     // Overrides for the role IN ANY CONTEXTS
269     // down to COURSE - not below -
270     //
271     $sql = "SELECT ctx.path,
272                    rc.capability, rc.permission
273               FROM {context} ctx
274               JOIN {role_capabilities} rc ON rc.contextid = ctx.id
275          LEFT JOIN {context} cctx
276                    ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
277              WHERE rc.roleid = ? AND cctx.id IS NULL";
278     $params = array($roleid);
280     // we need extra caching in CLI scripts and cron
281     $rs = $DB->get_recordset_sql($sql, $params);
282     foreach ($rs as $rd) {
283         $k = "{$rd->path}:{$roleid}";
284         $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
285     }
286     $rs->close();
288     // share the role definitions
289     foreach ($accessdata['rdef'] as $k=>$unused) {
290         if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
291             $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
292         }
293         $accessdata['rdef_count']++;
294         $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
295     }
297     return $accessdata;
300 /**
301  * Get the default guest role, this is used for guest account,
302  * search engine spiders, etc.
303  *
304  * @return stdClass role record
305  */
306 function get_guest_role() {
307     global $CFG, $DB;
309     if (empty($CFG->guestroleid)) {
310         if ($roles = $DB->get_records('role', array('archetype'=>'guest'))) {
311             $guestrole = array_shift($roles);   // Pick the first one
312             set_config('guestroleid', $guestrole->id);
313             return $guestrole;
314         } else {
315             debugging('Can not find any guest role!');
316             return false;
317         }
318     } else {
319         if ($guestrole = $DB->get_record('role', array('id'=>$CFG->guestroleid))) {
320             return $guestrole;
321         } else {
322             // somebody is messing with guest roles, remove incorrect setting and try to find a new one
323             set_config('guestroleid', '');
324             return get_guest_role();
325         }
326     }
329 /**
330  * Check whether a user has a particular capability in a given context.
331  *
332  * For example:
333  *      $context = get_context_instance(CONTEXT_MODULE, $cm->id);
334  *      has_capability('mod/forum:replypost',$context)
335  *
336  * By default checks the capabilities of the current user, but you can pass a
337  * different userid. By default will return true for admin users, but you can override that with the fourth argument.
338  *
339  * Guest and not-logged-in users can never get any dangerous capability - that is any write capability
340  * or capabilities with XSS, config or data loss risks.
341  *
342  * @param string $capability the name of the capability to check. For example mod/forum:view
343  * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
344  * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
345  * @param boolean $doanything If false, ignores effect of admin role assignment
346  * @return boolean true if the user has this capability. Otherwise false.
347  */
348 function has_capability($capability, context $context, $user = null, $doanything = true) {
349     global $USER, $CFG, $SCRIPT, $ACCESSLIB_PRIVATE;
351     if (during_initial_install()) {
352         if ($SCRIPT === "/$CFG->admin/index.php" or $SCRIPT === "/$CFG->admin/cli/install.php" or $SCRIPT === "/$CFG->admin/cli/install_database.php") {
353             // we are in an installer - roles can not work yet
354             return true;
355         } else {
356             return false;
357         }
358     }
360     if (strpos($capability, 'moodle/legacy:') === 0) {
361         throw new coding_exception('Legacy capabilities can not be used any more!');
362     }
364     if (!is_bool($doanything)) {
365         throw new coding_exception('Capability parameter "doanything" is wierd, only true or false is allowed. This has to be fixed in code.');
366     }
368     // capability must exist
369     if (!$capinfo = get_capability_info($capability)) {
370         debugging('Capability "'.$capability.'" was not found! This has to be fixed in code.');
371         return false;
372     }
374     if (!isset($USER->id)) {
375         // should never happen
376         $USER->id = 0;
377     }
379     // make sure there is a real user specified
380     if ($user === null) {
381         $userid = $USER->id;
382     } else {
383         $userid = is_object($user) ? $user->id : $user;
384     }
386     // make sure forcelogin cuts off not-logged-in users if enabled
387     if (!empty($CFG->forcelogin) and $userid == 0) {
388         return false;
389     }
391     // make sure the guest account and not-logged-in users never get any risky caps no matter what the actual settings are.
392     if (($capinfo->captype === 'write') or ($capinfo->riskbitmask & (RISK_XSS | RISK_CONFIG | RISK_DATALOSS))) {
393         if (isguestuser($userid) or $userid == 0) {
394             return false;
395         }
396     }
398     // somehow make sure the user is not deleted and actually exists
399     if ($userid != 0) {
400         if ($userid == $USER->id and isset($USER->deleted)) {
401             // this prevents one query per page, it is a bit of cheating,
402             // but hopefully session is terminated properly once user is deleted
403             if ($USER->deleted) {
404                 return false;
405             }
406         } else {
407             if (!context_user::instance($userid, IGNORE_MISSING)) {
408                 // no user context == invalid userid
409                 return false;
410             }
411         }
412     }
414     // context path/depth must be valid
415     if (empty($context->path) or $context->depth == 0) {
416         // this should not happen often, each upgrade tries to rebuild the context paths
417         debugging('Context id '.$context->id.' does not have valid path, please use build_context_path()');
418         if (is_siteadmin($userid)) {
419             return true;
420         } else {
421             return false;
422         }
423     }
425     // Find out if user is admin - it is not possible to override the doanything in any way
426     // and it is not possible to switch to admin role either.
427     if ($doanything) {
428         if (is_siteadmin($userid)) {
429             if ($userid != $USER->id) {
430                 return true;
431             }
432             // make sure switchrole is not used in this context
433             if (empty($USER->access['rsw'])) {
434                 return true;
435             }
436             $parts = explode('/', trim($context->path, '/'));
437             $path = '';
438             $switched = false;
439             foreach ($parts as $part) {
440                 $path .= '/' . $part;
441                 if (!empty($USER->access['rsw'][$path])) {
442                     $switched = true;
443                     break;
444                 }
445             }
446             if (!$switched) {
447                 return true;
448             }
449             //ok, admin switched role in this context, let's use normal access control rules
450         }
451     }
453     // Careful check for staleness...
454     $context->reload_if_dirty();
456     if ($USER->id == $userid) {
457         if (!isset($USER->access)) {
458             load_all_capabilities();
459         }
460         $access =& $USER->access;
462     } else {
463         // make sure user accessdata is really loaded
464         get_user_accessdata($userid, true);
465         $access =& $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
466     }
469     // Load accessdata for below-the-course context if necessary,
470     // all contexts at and above all courses are already loaded
471     if ($context->contextlevel != CONTEXT_COURSE and $coursecontext = $context->get_course_context(false)) {
472         load_course_context($userid, $coursecontext, $access);
473     }
475     return has_capability_in_accessdata($capability, $context, $access);
478 /**
479  * Check if the user has any one of several capabilities from a list.
480  *
481  * This is just a utility method that calls has_capability in a loop. Try to put
482  * the capabilities that most users are likely to have first in the list for best
483  * performance.
484  *
485  * @see has_capability()
486  * @param array $capabilities an array of capability names.
487  * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
488  * @param integer $userid A user id. By default (null) checks the permissions of the current user.
489  * @param boolean $doanything If false, ignore effect of admin role assignment
490  * @return boolean true if the user has any of these capabilities. Otherwise false.
491  */
492 function has_any_capability(array $capabilities, context $context, $userid = null, $doanything = true) {
493     foreach ($capabilities as $capability) {
494         if (has_capability($capability, $context, $userid, $doanything)) {
495             return true;
496         }
497     }
498     return false;
501 /**
502  * Check if the user has all the capabilities in a list.
503  *
504  * This is just a utility method that calls has_capability in a loop. Try to put
505  * the capabilities that fewest users are likely to have first in the list for best
506  * performance.
507  *
508  * @see has_capability()
509  * @param array $capabilities an array of capability names.
510  * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
511  * @param integer $userid A user id. By default (null) checks the permissions of the current user.
512  * @param boolean $doanything If false, ignore effect of admin role assignment
513  * @return boolean true if the user has all of these capabilities. Otherwise false.
514  */
515 function has_all_capabilities(array $capabilities, context $context, $userid = null, $doanything = true) {
516     foreach ($capabilities as $capability) {
517         if (!has_capability($capability, $context, $userid, $doanything)) {
518             return false;
519         }
520     }
521     return true;
524 /**
525  * Check if the user is an admin at the site level.
526  *
527  * Please note that use of proper capabilities is always encouraged,
528  * this function is supposed to be used from core or for temporary hacks.
529  *
530  * @param  int|stdClass  $user_or_id user id or user object
531  * @return bool true if user is one of the administrators, false otherwise
532  */
533 function is_siteadmin($user_or_id = null) {
534     global $CFG, $USER;
536     if ($user_or_id === null) {
537         $user_or_id = $USER;
538     }
540     if (empty($user_or_id)) {
541         return false;
542     }
543     if (!empty($user_or_id->id)) {
544         $userid = $user_or_id->id;
545     } else {
546         $userid = $user_or_id;
547     }
549     $siteadmins = explode(',', $CFG->siteadmins);
550     return in_array($userid, $siteadmins);
553 /**
554  * Returns true if user has at least one role assign
555  * of 'coursecontact' role (is potentially listed in some course descriptions).
556  *
557  * @param int $userid
558  * @return bool
559  */
560 function has_coursecontact_role($userid) {
561     global $DB, $CFG;
563     if (empty($CFG->coursecontact)) {
564         return false;
565     }
566     $sql = "SELECT 1
567               FROM {role_assignments}
568              WHERE userid = :userid AND roleid IN ($CFG->coursecontact)";
569     return $DB->record_exists_sql($sql, array('userid'=>$userid));
572 /**
573  * Does the user have a capability to do something?
574  *
575  * Walk the accessdata array and return true/false.
576  * Deals with prohibits, role switching, aggregating
577  * capabilities, etc.
578  *
579  * The main feature of here is being FAST and with no
580  * side effects.
581  *
582  * Notes:
583  *
584  * Switch Role merges with default role
585  * ------------------------------------
586  * If you are a teacher in course X, you have at least
587  * teacher-in-X + defaultloggedinuser-sitewide. So in the
588  * course you'll have techer+defaultloggedinuser.
589  * We try to mimic that in switchrole.
590  *
591  * Permission evaluation
592  * ---------------------
593  * Originally there was an extremely complicated way
594  * to determine the user access that dealt with
595  * "locality" or role assignments and role overrides.
596  * Now we simply evaluate access for each role separately
597  * and then verify if user has at least one role with allow
598  * and at the same time no role with prohibit.
599  *
600  * @private
601  * @param string $capability
602  * @param context $context
603  * @param array $accessdata
604  * @return bool
605  */
606 function has_capability_in_accessdata($capability, context $context, array &$accessdata) {
607     global $CFG;
609     // Build $paths as a list of current + all parent "paths" with order bottom-to-top
610     $path = $context->path;
611     $paths = array($path);
612     while($path = rtrim($path, '0123456789')) {
613         $path = rtrim($path, '/');
614         if ($path === '') {
615             break;
616         }
617         $paths[] = $path;
618     }
620     $roles = array();
621     $switchedrole = false;
623     // Find out if role switched
624     if (!empty($accessdata['rsw'])) {
625         // From the bottom up...
626         foreach ($paths as $path) {
627             if (isset($accessdata['rsw'][$path])) {
628                 // Found a switchrole assignment - check for that role _plus_ the default user role
629                 $roles = array($accessdata['rsw'][$path]=>null, $CFG->defaultuserroleid=>null);
630                 $switchedrole = true;
631                 break;
632             }
633         }
634     }
636     if (!$switchedrole) {
637         // get all users roles in this context and above
638         foreach ($paths as $path) {
639             if (isset($accessdata['ra'][$path])) {
640                 foreach ($accessdata['ra'][$path] as $roleid) {
641                     $roles[$roleid] = null;
642                 }
643             }
644         }
645     }
647     // Now find out what access is given to each role, going bottom-->up direction
648     $allowed = false;
649     foreach ($roles as $roleid => $ignored) {
650         foreach ($paths as $path) {
651             if (isset($accessdata['rdef']["{$path}:$roleid"][$capability])) {
652                 $perm = (int)$accessdata['rdef']["{$path}:$roleid"][$capability];
653                 if ($perm === CAP_PROHIBIT) {
654                     // any CAP_PROHIBIT found means no permission for the user
655                     return false;
656                 }
657                 if (is_null($roles[$roleid])) {
658                     $roles[$roleid] = $perm;
659                 }
660             }
661         }
662         // CAP_ALLOW in any role means the user has a permission, we continue only to detect prohibits
663         $allowed = ($allowed or $roles[$roleid] === CAP_ALLOW);
664     }
666     return $allowed;
669 /**
670  * A convenience function that tests has_capability, and displays an error if
671  * the user does not have that capability.
672  *
673  * NOTE before Moodle 2.0, this function attempted to make an appropriate
674  * require_login call before checking the capability. This is no longer the case.
675  * You must call require_login (or one of its variants) if you want to check the
676  * user is logged in, before you call this function.
677  *
678  * @see has_capability()
679  *
680  * @param string $capability the name of the capability to check. For example mod/forum:view
681  * @param context $context the context to check the capability in. You normally get this with {@link get_context_instance}.
682  * @param int $userid A user id. By default (null) checks the permissions of the current user.
683  * @param bool $doanything If false, ignore effect of admin role assignment
684  * @param string $errormessage The error string to to user. Defaults to 'nopermissions'.
685  * @param string $stringfile The language file to load the error string from. Defaults to 'error'.
686  * @return void terminates with an error if the user does not have the given capability.
687  */
688 function require_capability($capability, context $context, $userid = null, $doanything = true,
689                             $errormessage = 'nopermissions', $stringfile = '') {
690     if (!has_capability($capability, $context, $userid, $doanything)) {
691         throw new required_capability_exception($context, $capability, $errormessage, $stringfile);
692     }
695 /**
696  * Return a nested array showing role assignments
697  * all relevant role capabilities for the user at
698  * site/course_category/course levels
699  *
700  * We do _not_ delve deeper than courses because the number of
701  * overrides at the module/block levels can be HUGE.
702  *
703  * [ra]   => [/path][roleid]=roleid
704  * [rdef] => [/path:roleid][capability]=permission
705  *
706  * @private
707  * @param int $userid - the id of the user
708  * @return array access info array
709  */
710 function get_user_access_sitewide($userid) {
711     global $CFG, $DB, $ACCESSLIB_PRIVATE;
713     /* Get in a few cheap DB queries...
714      * - role assignments
715      * - relevant role caps
716      *   - above and within this user's RAs
717      *   - below this user's RAs - limited to course level
718      */
720     // raparents collects paths & roles we need to walk up the parenthood to build the minimal rdef
721     $raparents = array();
722     $accessdata = get_empty_accessdata();
724     // start with the default role
725     if (!empty($CFG->defaultuserroleid)) {
726         $syscontext = context_system::instance();
727         $accessdata['ra'][$syscontext->path][(int)$CFG->defaultuserroleid] = (int)$CFG->defaultuserroleid;
728         $raparents[$CFG->defaultuserroleid][$syscontext->path] = $syscontext->path;
729     }
731     // load the "default frontpage role"
732     if (!empty($CFG->defaultfrontpageroleid)) {
733         $frontpagecontext = context_course::instance(get_site()->id);
734         if ($frontpagecontext->path) {
735             $accessdata['ra'][$frontpagecontext->path][(int)$CFG->defaultfrontpageroleid] = (int)$CFG->defaultfrontpageroleid;
736             $raparents[$CFG->defaultfrontpageroleid][$frontpagecontext->path] = $frontpagecontext->path;
737         }
738     }
740     // preload every assigned role at and above course context
741     $sql = "SELECT ctx.path, ra.roleid
742               FROM {role_assignments} ra
743               JOIN {context} ctx ON ctx.id = ra.contextid
744          LEFT JOIN {context} cctx
745                    ON (cctx.contextlevel = ".CONTEXT_COURSE." AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
746              WHERE ra.userid = :userid AND cctx.id IS NULL";
749     $params = array('userid'=>$userid);
750     $rs = $DB->get_recordset_sql($sql, $params);
751     foreach ($rs as $ra) {
752         // RAs leafs are arrays to support multi-role assignments...
753         $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
754         $raparents[$ra->roleid][$ra->path] = $ra->path;
755     }
756     $rs->close();
758     if (empty($raparents)) {
759         return $accessdata;
760     }
762     // now get overrides of interesting roles in all interesting child contexts
763     // hopefully we will not run out of SQL limits here,
764     // users would have to have very many roles above course context...
765     $sqls = array();
766     $params = array();
768     static $cp = 0;
769     foreach ($raparents as $roleid=>$paths) {
770         $cp++;
771         list($paths, $rparams) = $DB->get_in_or_equal($paths, SQL_PARAMS_NAMED, 'p'.$cp.'_');
772         $params = array_merge($params, $rparams);
773         $params['r'.$cp] = $roleid;
774         $sqls[] = "(SELECT ctx.path, rc.roleid, rc.capability, rc.permission
775                      FROM {role_capabilities} rc
776                      JOIN {context} ctx
777                           ON (ctx.id = rc.contextid)
778                 LEFT JOIN {context} cctx
779                           ON (cctx.contextlevel = ".CONTEXT_COURSE."
780                               AND ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'").")
781                      JOIN {context} pctx
782                           ON (pctx.path $paths
783                               AND (ctx.id = pctx.id
784                                    OR ctx.path LIKE ".$DB->sql_concat('pctx.path',"'/%'")."
785                                    OR pctx.path LIKE ".$DB->sql_concat('ctx.path',"'/%'")."))
786                     WHERE rc.roleid = :r{$cp}
787                           AND cctx.id IS NULL)";
788     }
790     // fixed capability order is necessary for rdef dedupe
791     $rs = $DB->get_recordset_sql(implode("\nUNION\n", $sqls). "ORDER BY capability", $params);
793     foreach ($rs as $rd) {
794         $k = $rd->path.':'.$rd->roleid;
795         $accessdata['rdef'][$k][$rd->capability] = (int)$rd->permission;
796     }
797     $rs->close();
799     // share the role definitions
800     foreach ($accessdata['rdef'] as $k=>$unused) {
801         if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
802             $ACCESSLIB_PRIVATE->rolepermissions[$k] = $accessdata['rdef'][$k];
803         }
804         $accessdata['rdef_count']++;
805         $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
806     }
808     return $accessdata;
811 /**
812  * Add to the access ctrl array the data needed by a user for a given course.
813  *
814  * This function injects all course related access info into the accessdata array.
815  *
816  * @private
817  * @param int $userid the id of the user
818  * @param context_course $coursecontext course context
819  * @param array $accessdata accessdata array (modified)
820  * @return void modifies $accessdata parameter
821  */
822 function load_course_context($userid, context_course $coursecontext, &$accessdata) {
823     global $DB, $CFG, $ACCESSLIB_PRIVATE;
825     if (empty($coursecontext->path)) {
826         // weird, this should not happen
827         return;
828     }
830     if (isset($accessdata['loaded'][$coursecontext->instanceid])) {
831         // already loaded, great!
832         return;
833     }
835     $roles = array();
837     if (empty($userid)) {
838         if (!empty($CFG->notloggedinroleid)) {
839             $roles[$CFG->notloggedinroleid] = $CFG->notloggedinroleid;
840         }
842     } else if (isguestuser($userid)) {
843         if ($guestrole = get_guest_role()) {
844             $roles[$guestrole->id] = $guestrole->id;
845         }
847     } else {
848         // Interesting role assignments at, above and below the course context
849         list($parentsaself, $params) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
850         $params['userid'] = $userid;
851         $params['children'] = $coursecontext->path."/%";
852         $sql = "SELECT ra.*, ctx.path
853                   FROM {role_assignments} ra
854                   JOIN {context} ctx ON ra.contextid = ctx.id
855                  WHERE ra.userid = :userid AND (ctx.id $parentsaself OR ctx.path LIKE :children)";
856         $rs = $DB->get_recordset_sql($sql, $params);
858         // add missing role definitions
859         foreach ($rs as $ra) {
860             $accessdata['ra'][$ra->path][(int)$ra->roleid] = (int)$ra->roleid;
861             $roles[$ra->roleid] = $ra->roleid;
862         }
863         $rs->close();
865         // add the "default frontpage role" when on the frontpage
866         if (!empty($CFG->defaultfrontpageroleid)) {
867             $frontpagecontext = context_course::instance(get_site()->id);
868             if ($frontpagecontext->id == $coursecontext->id) {
869                 $roles[$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
870             }
871         }
873         // do not forget the default role
874         if (!empty($CFG->defaultuserroleid)) {
875             $roles[$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
876         }
877     }
879     if (!$roles) {
880         // weird, default roles must be missing...
881         $accessdata['loaded'][$coursecontext->instanceid] = 1;
882         return;
883     }
885     // now get overrides of interesting roles in all interesting contexts (this course + children + parents)
886     $params = array('c'=>$coursecontext->id);
887     list($parentsaself, $rparams) = $DB->get_in_or_equal($coursecontext->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
888     $params = array_merge($params, $rparams);
889     list($roleids, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED, 'r_');
890     $params = array_merge($params, $rparams);
892     $sql = "SELECT ctx.path, rc.roleid, rc.capability, rc.permission
893                  FROM {role_capabilities} rc
894                  JOIN {context} ctx
895                       ON (ctx.id = rc.contextid)
896                  JOIN {context} cctx
897                       ON (cctx.id = :c
898                           AND (ctx.id $parentsaself OR ctx.path LIKE ".$DB->sql_concat('cctx.path',"'/%'")."))
899                 WHERE rc.roleid $roleids
900              ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
901     $rs = $DB->get_recordset_sql($sql, $params);
903     $newrdefs = array();
904     foreach ($rs as $rd) {
905         $k = $rd->path.':'.$rd->roleid;
906         if (isset($accessdata['rdef'][$k])) {
907             continue;
908         }
909         $newrdefs[$k][$rd->capability] = (int)$rd->permission;
910     }
911     $rs->close();
913     // share new role definitions
914     foreach ($newrdefs as $k=>$unused) {
915         if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
916             $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
917         }
918         $accessdata['rdef_count']++;
919         $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
920     }
922     $accessdata['loaded'][$coursecontext->instanceid] = 1;
924     // we want to deduplicate the USER->access from time to time, this looks like a good place,
925     // because we have to do it before the end of session
926     dedupe_user_access();
929 /**
930  * Add to the access ctrl array the data needed by a role for a given context.
931  *
932  * The data is added in the rdef key.
933  * This role-centric function is useful for role_switching
934  * and temporary course roles.
935  *
936  * @private
937  * @param int $roleid the id of the user
938  * @param context $context needs path!
939  * @param array $accessdata accessdata array (is modified)
940  * @return array
941  */
942 function load_role_access_by_context($roleid, context $context, &$accessdata) {
943     global $DB, $ACCESSLIB_PRIVATE;
945     /* Get the relevant rolecaps into rdef
946      * - relevant role caps
947      *   - at ctx and above
948      *   - below this ctx
949      */
951     if (empty($context->path)) {
952         // weird, this should not happen
953         return;
954     }
956     list($parentsaself, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'pc_');
957     $params['roleid'] = $roleid;
958     $params['childpath'] = $context->path.'/%';
960     $sql = "SELECT ctx.path, rc.capability, rc.permission
961               FROM {role_capabilities} rc
962               JOIN {context} ctx ON (rc.contextid = ctx.id)
963              WHERE rc.roleid = :roleid AND (ctx.id $parentsaself OR ctx.path LIKE :childpath)
964           ORDER BY rc.capability"; // fixed capability order is necessary for rdef dedupe
965     $rs = $DB->get_recordset_sql($sql, $params);
967     $newrdefs = array();
968     foreach ($rs as $rd) {
969         $k = $rd->path.':'.$roleid;
970         if (isset($accessdata['rdef'][$k])) {
971             continue;
972         }
973         $newrdefs[$k][$rd->capability] = (int)$rd->permission;
974     }
975     $rs->close();
977     // share new role definitions
978     foreach ($newrdefs as $k=>$unused) {
979         if (!isset($ACCESSLIB_PRIVATE->rolepermissions[$k])) {
980             $ACCESSLIB_PRIVATE->rolepermissions[$k] = $newrdefs[$k];
981         }
982         $accessdata['rdef_count']++;
983         $accessdata['rdef'][$k] =& $ACCESSLIB_PRIVATE->rolepermissions[$k];
984     }
987 /**
988  * Returns empty accessdata structure.
989  *
990  * @private
991  * @return array empt accessdata
992  */
993 function get_empty_accessdata() {
994     $accessdata               = array(); // named list
995     $accessdata['ra']         = array();
996     $accessdata['rdef']       = array();
997     $accessdata['rdef_count'] = 0;       // this bloody hack is necessary because count($array) is slooooowwww in PHP
998     $accessdata['rdef_lcc']   = 0;       // rdef_count during the last compression
999     $accessdata['loaded']     = array(); // loaded course contexts
1000     $accessdata['time']       = time();
1002     return $accessdata;
1005 /**
1006  * Get accessdata for a given user.
1007  *
1008  * @private
1009  * @param int $userid
1010  * @param bool $preloadonly true means do not return access array
1011  * @return array accessdata
1012  */
1013 function get_user_accessdata($userid, $preloadonly=false) {
1014     global $CFG, $ACCESSLIB_PRIVATE, $USER;
1016     if (!empty($USER->acces['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
1017         // share rdef from USER session with rolepermissions cache in order to conserve memory
1018         foreach($USER->acces['rdef'] as $k=>$v) {
1019             $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->acces['rdef'][$k];
1020         }
1021         $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->acces;
1022     }
1024     if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
1025         if (empty($userid)) {
1026             if (!empty($CFG->notloggedinroleid)) {
1027                 $accessdata = get_role_access($CFG->notloggedinroleid);
1028             } else {
1029                 // weird
1030                 return get_empty_accessdata();
1031             }
1033         } else if (isguestuser($userid)) {
1034             if ($guestrole = get_guest_role()) {
1035                 $accessdata = get_role_access($guestrole->id);
1036             } else {
1037                 //weird
1038                 return get_empty_accessdata();
1039             }
1041         } else {
1042             $accessdata = get_user_access_sitewide($userid); // includes default role and frontpage role
1043         }
1045         $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
1046     }
1048     if ($preloadonly) {
1049         return;
1050     } else {
1051         return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
1052     }
1055 /**
1056  * Try to minimise the size of $USER->access by eliminating duplicate override storage,
1057  * this function looks for contexts with the same overrides and shares them.
1058  *
1059  * @private
1060  * @return void
1061  */
1062 function dedupe_user_access() {
1063     global $USER;
1065     if (CLI_SCRIPT) {
1066         // no session in CLI --> no compression necessary
1067         return;
1068     }
1070     if (empty($USER->access['rdef_count'])) {
1071         // weird, this should not happen
1072         return;
1073     }
1075     // the rdef is growing only, we never remove stuff from it, the rdef_lcc helps us to detect new stuff in rdef
1076     if ($USER->access['rdef_count'] - $USER->access['rdef_lcc'] > 10) {
1077         // do not compress after each change, wait till there is more stuff to be done
1078         return;
1079     }
1081     $hashmap = array();
1082     foreach ($USER->access['rdef'] as $k=>$def) {
1083         $hash = sha1(serialize($def));
1084         if (isset($hashmap[$hash])) {
1085             $USER->access['rdef'][$k] =& $hashmap[$hash];
1086         } else {
1087             $hashmap[$hash] =& $USER->access['rdef'][$k];
1088         }
1089     }
1091     $USER->access['rdef_lcc'] = $USER->access['rdef_count'];
1094 /**
1095  * A convenience function to completely load all the capabilities
1096  * for the current user. It is called from has_capability() and functions change permissions.
1097  *
1098  * Call it only _after_ you've setup $USER and called check_enrolment_plugins();
1099  * @see check_enrolment_plugins()
1100  *
1101  * @private
1102  * @return void
1103  */
1104 function load_all_capabilities() {
1105     global $USER;
1107     // roles not installed yet - we are in the middle of installation
1108     if (during_initial_install()) {
1109         return;
1110     }
1112     if (!isset($USER->id)) {
1113         // this should not happen
1114         $USER->id = 0;
1115     }
1117     unset($USER->access);
1118     $USER->access = get_user_accessdata($USER->id);
1120     // deduplicate the overrides to minimize session size
1121     dedupe_user_access();
1123     // Clear to force a refresh
1124     unset($USER->mycourses);
1126     // init/reset internal enrol caches - active course enrolments and temp access
1127     $USER->enrol = array('enrolled'=>array(), 'tempguest'=>array());
1130 /**
1131  * A convenience function to completely reload all the capabilities
1132  * for the current user when roles have been updated in a relevant
1133  * context -- but PRESERVING switchroles and loginas.
1134  * This function resets all accesslib and context caches.
1135  *
1136  * That is - completely transparent to the user.
1137  *
1138  * Note: reloads $USER->access completely.
1139  *
1140  * @private
1141  * @return void
1142  */
1143 function reload_all_capabilities() {
1144     global $USER, $DB, $ACCESSLIB_PRIVATE;
1146     // copy switchroles
1147     $sw = array();
1148     if (isset($USER->access['rsw'])) {
1149         $sw = $USER->access['rsw'];
1150     }
1152     accesslib_clear_all_caches(true);
1153     unset($USER->access);
1154     $ACCESSLIB_PRIVATE->dirtycontexts = array(); // prevent dirty flags refetching on this page
1156     load_all_capabilities();
1158     foreach ($sw as $path => $roleid) {
1159         if ($record = $DB->get_record('context', array('path'=>$path))) {
1160             $context = context::instance_by_id($record->id);
1161             role_switch($roleid, $context);
1162         }
1163     }
1166 /**
1167  * Adds a temp role to current USER->access array.
1168  *
1169  * Useful for the "temporary guest" access we grant to logged-in users.
1170  * @since 2.2
1171  *
1172  * @param context_course $coursecontext
1173  * @param int $roleid
1174  * @return void
1175  */
1176 function load_temp_course_role(context_course $coursecontext, $roleid) {
1177     global $USER, $SITE;
1179     if (empty($roleid)) {
1180         debugging('invalid role specified in load_temp_course_role()');
1181         return;
1182     }
1184     if ($coursecontext->instanceid == $SITE->id) {
1185         debugging('Can not use temp roles on the frontpage');
1186         return;
1187     }
1189     if (!isset($USER->access)) {
1190         load_all_capabilities();
1191     }
1193     $coursecontext->reload_if_dirty();
1195     if (isset($USER->access['ra'][$coursecontext->path][$roleid])) {
1196         return;
1197     }
1199     // load course stuff first
1200     load_course_context($USER->id, $coursecontext, $USER->access);
1202     $USER->access['ra'][$coursecontext->path][(int)$roleid] = (int)$roleid;
1204     load_role_access_by_context($roleid, $coursecontext, $USER->access);
1207 /**
1208  * Removes any extra guest roles from current USER->access array.
1209  * @since 2.2
1210  *
1211  * @param context_course $coursecontext
1212  * @return void
1213  */
1214 function remove_temp_course_roles(context_course $coursecontext) {
1215     global $DB, $USER, $SITE;
1217     if ($coursecontext->instanceid == $SITE->id) {
1218         debugging('Can not use temp roles on the frontpage');
1219         return;
1220     }
1222     if (empty($USER->access['ra'][$coursecontext->path])) {
1223         //no roles here, weird
1224         return;
1225     }
1227     $sql = "SELECT DISTINCT ra.roleid AS id
1228               FROM {role_assignments} ra
1229              WHERE ra.contextid = :contextid AND ra.userid = :userid";
1230     $ras = $DB->get_records_sql($sql, array('contextid'=>$coursecontext->id, 'userid'=>$USER->id));
1232     $USER->access['ra'][$coursecontext->path] = array();
1233     foreach($ras as $r) {
1234         $USER->access['ra'][$coursecontext->path][(int)$r->id] = (int)$r->id;
1235     }
1238 /**
1239  * Returns array of all role archetypes.
1240  *
1241  * @return array
1242  */
1243 function get_role_archetypes() {
1244     return array(
1245         'manager'        => 'manager',
1246         'coursecreator'  => 'coursecreator',
1247         'editingteacher' => 'editingteacher',
1248         'teacher'        => 'teacher',
1249         'student'        => 'student',
1250         'guest'          => 'guest',
1251         'user'           => 'user',
1252         'frontpage'      => 'frontpage'
1253     );
1256 /**
1257  * Assign the defaults found in this capability definition to roles that have
1258  * the corresponding legacy capabilities assigned to them.
1259  *
1260  * @param string $capability
1261  * @param array $legacyperms an array in the format (example):
1262  *                      'guest' => CAP_PREVENT,
1263  *                      'student' => CAP_ALLOW,
1264  *                      'teacher' => CAP_ALLOW,
1265  *                      'editingteacher' => CAP_ALLOW,
1266  *                      'coursecreator' => CAP_ALLOW,
1267  *                      'manager' => CAP_ALLOW
1268  * @return boolean success or failure.
1269  */
1270 function assign_legacy_capabilities($capability, $legacyperms) {
1272     $archetypes = get_role_archetypes();
1274     foreach ($legacyperms as $type => $perm) {
1276         $systemcontext = context_system::instance();
1277         if ($type === 'admin') {
1278             debugging('Legacy type admin in access.php was renamed to manager, please update the code.');
1279             $type = 'manager';
1280         }
1282         if (!array_key_exists($type, $archetypes)) {
1283             print_error('invalidlegacy', '', '', $type);
1284         }
1286         if ($roles = get_archetype_roles($type)) {
1287             foreach ($roles as $role) {
1288                 // Assign a site level capability.
1289                 if (!assign_capability($capability, $perm, $role->id, $systemcontext->id)) {
1290                     return false;
1291                 }
1292             }
1293         }
1294     }
1295     return true;
1298 /**
1299  * Verify capability risks.
1300  *
1301  * @param object $capability a capability - a row from the capabilities table.
1302  * @return boolean whether this capability is safe - that is, whether people with the
1303  *      safeoverrides capability should be allowed to change it.
1304  */
1305 function is_safe_capability($capability) {
1306     return !((RISK_DATALOSS | RISK_MANAGETRUST | RISK_CONFIG | RISK_XSS | RISK_PERSONAL) & $capability->riskbitmask);
1309 /**
1310  * Get the local override (if any) for a given capability in a role in a context
1311  *
1312  * @param int $roleid
1313  * @param int $contextid
1314  * @param string $capability
1315  * @return stdClass local capability override
1316  */
1317 function get_local_override($roleid, $contextid, $capability) {
1318     global $DB;
1319     return $DB->get_record('role_capabilities', array('roleid'=>$roleid, 'capability'=>$capability, 'contextid'=>$contextid));
1322 /**
1323  * Returns context instance plus related course and cm instances
1324  *
1325  * @param int $contextid
1326  * @return array of ($context, $course, $cm)
1327  */
1328 function get_context_info_array($contextid) {
1329     global $DB;
1331     $context = context::instance_by_id($contextid, MUST_EXIST);
1332     $course  = null;
1333     $cm      = null;
1335     if ($context->contextlevel == CONTEXT_COURSE) {
1336         $course = $DB->get_record('course', array('id'=>$context->instanceid), '*', MUST_EXIST);
1338     } else if ($context->contextlevel == CONTEXT_MODULE) {
1339         $cm = get_coursemodule_from_id('', $context->instanceid, 0, false, MUST_EXIST);
1340         $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1342     } else if ($context->contextlevel == CONTEXT_BLOCK) {
1343         $parent = $context->get_parent_context();
1345         if ($parent->contextlevel == CONTEXT_COURSE) {
1346             $course = $DB->get_record('course', array('id'=>$parent->instanceid), '*', MUST_EXIST);
1347         } else if ($parent->contextlevel == CONTEXT_MODULE) {
1348             $cm = get_coursemodule_from_id('', $parent->instanceid, 0, false, MUST_EXIST);
1349             $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST);
1350         }
1351     }
1353     return array($context, $course, $cm);
1356 /**
1357  * Function that creates a role
1358  *
1359  * @param string $name role name
1360  * @param string $shortname role short name
1361  * @param string $description role description
1362  * @param string $archetype
1363  * @return int id or dml_exception
1364  */
1365 function create_role($name, $shortname, $description, $archetype = '') {
1366     global $DB;
1368     if (strpos($archetype, 'moodle/legacy:') !== false) {
1369         throw new coding_exception('Use new role archetype parameter in create_role() instead of old legacy capabilities.');
1370     }
1372     // verify role archetype actually exists
1373     $archetypes = get_role_archetypes();
1374     if (empty($archetypes[$archetype])) {
1375         $archetype = '';
1376     }
1378     // Insert the role record.
1379     $role = new stdClass();
1380     $role->name        = $name;
1381     $role->shortname   = $shortname;
1382     $role->description = $description;
1383     $role->archetype   = $archetype;
1385     //find free sortorder number
1386     $role->sortorder = $DB->get_field('role', 'MAX(sortorder) + 1', array());
1387     if (empty($role->sortorder)) {
1388         $role->sortorder = 1;
1389     }
1390     $id = $DB->insert_record('role', $role);
1392     return $id;
1395 /**
1396  * Function that deletes a role and cleanups up after it
1397  *
1398  * @param int $roleid id of role to delete
1399  * @return bool always true
1400  */
1401 function delete_role($roleid) {
1402     global $DB;
1404     // first unssign all users
1405     role_unassign_all(array('roleid'=>$roleid));
1407     // cleanup all references to this role, ignore errors
1408     $DB->delete_records('role_capabilities',   array('roleid'=>$roleid));
1409     $DB->delete_records('role_allow_assign',   array('roleid'=>$roleid));
1410     $DB->delete_records('role_allow_assign',   array('allowassign'=>$roleid));
1411     $DB->delete_records('role_allow_override', array('roleid'=>$roleid));
1412     $DB->delete_records('role_allow_override', array('allowoverride'=>$roleid));
1413     $DB->delete_records('role_names',          array('roleid'=>$roleid));
1414     $DB->delete_records('role_context_levels', array('roleid'=>$roleid));
1416     // finally delete the role itself
1417     // get this before the name is gone for logging
1418     $rolename = $DB->get_field('role', 'name', array('id'=>$roleid));
1420     $DB->delete_records('role', array('id'=>$roleid));
1422     add_to_log(SITEID, 'role', 'delete', 'admin/roles/action=delete&roleid='.$roleid, $rolename, '');
1424     return true;
1427 /**
1428  * Function to write context specific overrides, or default capabilities.
1429  *
1430  * NOTE: use $context->mark_dirty() after this
1431  *
1432  * @param string $capability string name
1433  * @param int $permission CAP_ constants
1434  * @param int $roleid role id
1435  * @param int|context $contextid context id
1436  * @param bool $overwrite
1437  * @return bool always true or exception
1438  */
1439 function assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false) {
1440     global $USER, $DB;
1442     if ($contextid instanceof context) {
1443         $context = $contextid;
1444     } else {
1445         $context = context::instance_by_id($contextid);
1446     }
1448     if (empty($permission) || $permission == CAP_INHERIT) { // if permission is not set
1449         unassign_capability($capability, $roleid, $context->id);
1450         return true;
1451     }
1453     $existing = $DB->get_record('role_capabilities', array('contextid'=>$context->id, 'roleid'=>$roleid, 'capability'=>$capability));
1455     if ($existing and !$overwrite) {   // We want to keep whatever is there already
1456         return true;
1457     }
1459     $cap = new stdClass();
1460     $cap->contextid    = $context->id;
1461     $cap->roleid       = $roleid;
1462     $cap->capability   = $capability;
1463     $cap->permission   = $permission;
1464     $cap->timemodified = time();
1465     $cap->modifierid   = empty($USER->id) ? 0 : $USER->id;
1467     if ($existing) {
1468         $cap->id = $existing->id;
1469         $DB->update_record('role_capabilities', $cap);
1470     } else {
1471         if ($DB->record_exists('context', array('id'=>$context->id))) {
1472             $DB->insert_record('role_capabilities', $cap);
1473         }
1474     }
1475     return true;
1478 /**
1479  * Unassign a capability from a role.
1480  *
1481  * NOTE: use $context->mark_dirty() after this
1482  *
1483  * @param string $capability the name of the capability
1484  * @param int $roleid the role id
1485  * @param int|context $contextid null means all contexts
1486  * @return boolean true or exception
1487  */
1488 function unassign_capability($capability, $roleid, $contextid = null) {
1489     global $DB;
1491     if (!empty($contextid)) {
1492         if ($contextid instanceof context) {
1493             $context = $contextid;
1494         } else {
1495             $context = context::instance_by_id($contextid);
1496         }
1497         // delete from context rel, if this is the last override in this context
1498         $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid, 'contextid'=>$context->id));
1499     } else {
1500         $DB->delete_records('role_capabilities', array('capability'=>$capability, 'roleid'=>$roleid));
1501     }
1502     return true;
1505 /**
1506  * Get the roles that have a given capability assigned to it
1507  *
1508  * This function does not resolve the actual permission of the capability.
1509  * It just checks for permissions and overrides.
1510  * Use get_roles_with_cap_in_context() if resolution is required.
1511  *
1512  * @param string $capability - capability name (string)
1513  * @param string $permission - optional, the permission defined for this capability
1514  *                      either CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT. Defaults to null which means any.
1515  * @param stdClass $context, null means any
1516  * @return array of role records
1517  */
1518 function get_roles_with_capability($capability, $permission = null, $context = null) {
1519     global $DB;
1521     if ($context) {
1522         $contexts = $context->get_parent_context_ids(true);
1523         list($insql, $params) = $DB->get_in_or_equal($contexts, SQL_PARAMS_NAMED, 'ctx');
1524         $contextsql = "AND rc.contextid $insql";
1525     } else {
1526         $params = array();
1527         $contextsql = '';
1528     }
1530     if ($permission) {
1531         $permissionsql = " AND rc.permission = :permission";
1532         $params['permission'] = $permission;
1533     } else {
1534         $permissionsql = '';
1535     }
1537     $sql = "SELECT r.*
1538               FROM {role} r
1539              WHERE r.id IN (SELECT rc.roleid
1540                               FROM {role_capabilities} rc
1541                              WHERE rc.capability = :capname
1542                                    $contextsql
1543                                    $permissionsql)";
1544     $params['capname'] = $capability;
1547     return $DB->get_records_sql($sql, $params);
1550 /**
1551  * This function makes a role-assignment (a role for a user in a particular context)
1552  *
1553  * @param int $roleid the role of the id
1554  * @param int $userid userid
1555  * @param int|context $contextid id of the context
1556  * @param string $component example 'enrol_ldap', defaults to '' which means manual assignment,
1557  * @param int $itemid id of enrolment/auth plugin
1558  * @param string $timemodified defaults to current time
1559  * @return int new/existing id of the assignment
1560  */
1561 function role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '') {
1562     global $USER, $DB;
1564     // first of all detect if somebody is using old style parameters
1565     if ($contextid === 0 or is_numeric($component)) {
1566         throw new coding_exception('Invalid call to role_assign(), code needs to be updated to use new order of parameters');
1567     }
1569     // now validate all parameters
1570     if (empty($roleid)) {
1571         throw new coding_exception('Invalid call to role_assign(), roleid can not be empty');
1572     }
1574     if (empty($userid)) {
1575         throw new coding_exception('Invalid call to role_assign(), userid can not be empty');
1576     }
1578     if ($itemid) {
1579         if (strpos($component, '_') === false) {
1580             throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as"enrol_" when itemid specified', 'component:'.$component);
1581         }
1582     } else {
1583         $itemid = 0;
1584         if ($component !== '' and strpos($component, '_') === false) {
1585             throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1586         }
1587     }
1589     if (!$DB->record_exists('user', array('id'=>$userid, 'deleted'=>0))) {
1590         throw new coding_exception('User ID does not exist or is deleted!', 'userid:'.$userid);
1591     }
1593     if ($contextid instanceof context) {
1594         $context = $contextid;
1595     } else {
1596         $context = context::instance_by_id($contextid, MUST_EXIST);
1597     }
1599     if (!$timemodified) {
1600         $timemodified = time();
1601     }
1603 /// Check for existing entry
1604     $ras = $DB->get_records('role_assignments', array('roleid'=>$roleid, 'contextid'=>$context->id, 'userid'=>$userid, 'component'=>$component, 'itemid'=>$itemid), 'id');
1606     if ($ras) {
1607         // role already assigned - this should not happen
1608         if (count($ras) > 1) {
1609             // very weird - remove all duplicates!
1610             $ra = array_shift($ras);
1611             foreach ($ras as $r) {
1612                 $DB->delete_records('role_assignments', array('id'=>$r->id));
1613             }
1614         } else {
1615             $ra = reset($ras);
1616         }
1618         // actually there is no need to update, reset anything or trigger any event, so just return
1619         return $ra->id;
1620     }
1622     // Create a new entry
1623     $ra = new stdClass();
1624     $ra->roleid       = $roleid;
1625     $ra->contextid    = $context->id;
1626     $ra->userid       = $userid;
1627     $ra->component    = $component;
1628     $ra->itemid       = $itemid;
1629     $ra->timemodified = $timemodified;
1630     $ra->modifierid   = empty($USER->id) ? 0 : $USER->id;
1632     $ra->id = $DB->insert_record('role_assignments', $ra);
1634     // mark context as dirty - again expensive, but needed
1635     $context->mark_dirty();
1637     if (!empty($USER->id) && $USER->id == $userid) {
1638         // If the user is the current user, then do full reload of capabilities too.
1639         reload_all_capabilities();
1640     }
1642     events_trigger('role_assigned', $ra);
1644     return $ra->id;
1647 /**
1648  * Removes one role assignment
1649  *
1650  * @param int $roleid
1651  * @param int  $userid
1652  * @param int|context  $contextid
1653  * @param string $component
1654  * @param int  $itemid
1655  * @return void
1656  */
1657 function role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0) {
1658     // first make sure the params make sense
1659     if ($roleid == 0 or $userid == 0 or $contextid == 0) {
1660         throw new coding_exception('Invalid call to role_unassign(), please use role_unassign_all() when removing multiple role assignments');
1661     }
1663     if ($itemid) {
1664         if (strpos($component, '_') === false) {
1665             throw new coding_exception('Invalid call to role_assign(), component must start with plugin type such as "enrol_" when itemid specified', 'component:'.$component);
1666         }
1667     } else {
1668         $itemid = 0;
1669         if ($component !== '' and strpos($component, '_') === false) {
1670             throw new coding_exception('Invalid call to role_assign(), invalid component string', 'component:'.$component);
1671         }
1672     }
1674     role_unassign_all(array('roleid'=>$roleid, 'userid'=>$userid, 'contextid'=>$contextid, 'component'=>$component, 'itemid'=>$itemid), false, false);
1677 /**
1678  * Removes multiple role assignments, parameters may contain:
1679  *   'roleid', 'userid', 'contextid', 'component', 'enrolid'.
1680  *
1681  * @param array $params role assignment parameters
1682  * @param bool $subcontexts unassign in subcontexts too
1683  * @param bool $includemanual include manual role assignments too
1684  * @return void
1685  */
1686 function role_unassign_all(array $params, $subcontexts = false, $includemanual = false) {
1687     global $USER, $CFG, $DB;
1689     if (!$params) {
1690         throw new coding_exception('Missing parameters in role_unsassign_all() call');
1691     }
1693     $allowed = array('roleid', 'userid', 'contextid', 'component', 'itemid');
1694     foreach ($params as $key=>$value) {
1695         if (!in_array($key, $allowed)) {
1696             throw new coding_exception('Unknown role_unsassign_all() parameter key', 'key:'.$key);
1697         }
1698     }
1700     if (isset($params['component']) and $params['component'] !== '' and strpos($params['component'], '_') === false) {
1701         throw new coding_exception('Invalid component paramter in role_unsassign_all() call', 'component:'.$params['component']);
1702     }
1704     if ($includemanual) {
1705         if (!isset($params['component']) or $params['component'] === '') {
1706             throw new coding_exception('include manual parameter requires component parameter in role_unsassign_all() call');
1707         }
1708     }
1710     if ($subcontexts) {
1711         if (empty($params['contextid'])) {
1712             throw new coding_exception('subcontexts paramtere requires component parameter in role_unsassign_all() call');
1713         }
1714     }
1716     $ras = $DB->get_records('role_assignments', $params);
1717     foreach($ras as $ra) {
1718         $DB->delete_records('role_assignments', array('id'=>$ra->id));
1719         if ($context = context::instance_by_id($ra->contextid, IGNORE_MISSING)) {
1720             // this is a bit expensive but necessary
1721             $context->mark_dirty();
1722             /// If the user is the current user, then do full reload of capabilities too.
1723             if (!empty($USER->id) && $USER->id == $ra->userid) {
1724                 reload_all_capabilities();
1725             }
1726         }
1727         events_trigger('role_unassigned', $ra);
1728     }
1729     unset($ras);
1731     // process subcontexts
1732     if ($subcontexts and $context = context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1733         if ($params['contextid'] instanceof context) {
1734             $context = $params['contextid'];
1735         } else {
1736             $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1737         }
1739         if ($context) {
1740             $contexts = $context->get_child_contexts();
1741             $mparams = $params;
1742             foreach($contexts as $context) {
1743                 $mparams['contextid'] = $context->id;
1744                 $ras = $DB->get_records('role_assignments', $mparams);
1745                 foreach($ras as $ra) {
1746                     $DB->delete_records('role_assignments', array('id'=>$ra->id));
1747                     // this is a bit expensive but necessary
1748                     $context->mark_dirty();
1749                     /// If the user is the current user, then do full reload of capabilities too.
1750                     if (!empty($USER->id) && $USER->id == $ra->userid) {
1751                         reload_all_capabilities();
1752                     }
1753                     events_trigger('role_unassigned', $ra);
1754                 }
1755             }
1756         }
1757     }
1759     // do this once more for all manual role assignments
1760     if ($includemanual) {
1761         $params['component'] = '';
1762         role_unassign_all($params, $subcontexts, false);
1763     }
1766 /**
1767  * Determines if a user is currently logged in
1768  *
1769  * @return bool
1770  */
1771 function isloggedin() {
1772     global $USER;
1774     return (!empty($USER->id));
1777 /**
1778  * Determines if a user is logged in as real guest user with username 'guest'.
1779  *
1780  * @param int|object $user mixed user object or id, $USER if not specified
1781  * @return bool true if user is the real guest user, false if not logged in or other user
1782  */
1783 function isguestuser($user = null) {
1784     global $USER, $DB, $CFG;
1786     // make sure we have the user id cached in config table, because we are going to use it a lot
1787     if (empty($CFG->siteguest)) {
1788         if (!$guestid = $DB->get_field('user', 'id', array('username'=>'guest', 'mnethostid'=>$CFG->mnet_localhost_id))) {
1789             // guest does not exist yet, weird
1790             return false;
1791         }
1792         set_config('siteguest', $guestid);
1793     }
1794     if ($user === null) {
1795         $user = $USER;
1796     }
1798     if ($user === null) {
1799         // happens when setting the $USER
1800         return false;
1802     } else if (is_numeric($user)) {
1803         return ($CFG->siteguest == $user);
1805     } else if (is_object($user)) {
1806         if (empty($user->id)) {
1807             return false; // not logged in means is not be guest
1808         } else {
1809             return ($CFG->siteguest == $user->id);
1810         }
1812     } else {
1813         throw new coding_exception('Invalid user parameter supplied for isguestuser() function!');
1814     }
1817 /**
1818  * Does user have a (temporary or real) guest access to course?
1819  *
1820  * @param context $context
1821  * @param stdClass|int $user
1822  * @return bool
1823  */
1824 function is_guest(context $context, $user = null) {
1825     global $USER;
1827     // first find the course context
1828     $coursecontext = $context->get_course_context();
1830     // make sure there is a real user specified
1831     if ($user === null) {
1832         $userid = isset($USER->id) ? $USER->id : 0;
1833     } else {
1834         $userid = is_object($user) ? $user->id : $user;
1835     }
1837     if (isguestuser($userid)) {
1838         // can not inspect or be enrolled
1839         return true;
1840     }
1842     if (has_capability('moodle/course:view', $coursecontext, $user)) {
1843         // viewing users appear out of nowhere, they are neither guests nor participants
1844         return false;
1845     }
1847     // consider only real active enrolments here
1848     if (is_enrolled($coursecontext, $user, '', true)) {
1849         return false;
1850     }
1852     return true;
1855 /**
1856  * Returns true if the user has moodle/course:view capability in the course,
1857  * this is intended for admins, managers (aka small admins), inspectors, etc.
1858  *
1859  * @param context $context
1860  * @param int|stdClass $user, if null $USER is used
1861  * @param string $withcapability extra capability name
1862  * @return bool
1863  */
1864 function is_viewing(context $context, $user = null, $withcapability = '') {
1865     // first find the course context
1866     $coursecontext = $context->get_course_context();
1868     if (isguestuser($user)) {
1869         // can not inspect
1870         return false;
1871     }
1873     if (!has_capability('moodle/course:view', $coursecontext, $user)) {
1874         // admins are allowed to inspect courses
1875         return false;
1876     }
1878     if ($withcapability and !has_capability($withcapability, $context, $user)) {
1879         // site admins always have the capability, but the enrolment above blocks
1880         return false;
1881     }
1883     return true;
1886 /**
1887  * Returns true if user is enrolled (is participating) in course
1888  * this is intended for students and teachers.
1889  *
1890  * Since 2.2 the result for active enrolments and current user are cached.
1891  *
1892  * @param context $context
1893  * @param int|stdClass $user, if null $USER is used, otherwise user object or id expected
1894  * @param string $withcapability extra capability name
1895  * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1896  * @return bool
1897  */
1898 function is_enrolled(context $context, $user = null, $withcapability = '', $onlyactive = false) {
1899     global $USER, $DB;
1901     // first find the course context
1902     $coursecontext = $context->get_course_context();
1904     // make sure there is a real user specified
1905     if ($user === null) {
1906         $userid = isset($USER->id) ? $USER->id : 0;
1907     } else {
1908         $userid = is_object($user) ? $user->id : $user;
1909     }
1911     if (empty($userid)) {
1912         // not-logged-in!
1913         return false;
1914     } else if (isguestuser($userid)) {
1915         // guest account can not be enrolled anywhere
1916         return false;
1917     }
1919     if ($coursecontext->instanceid == SITEID) {
1920         // everybody participates on frontpage
1921     } else {
1922         // try cached info first - the enrolled flag is set only when active enrolment present
1923         if ($USER->id == $userid) {
1924             $coursecontext->reload_if_dirty();
1925             if (isset($USER->enrol['enrolled'][$coursecontext->instanceid])) {
1926                 if ($USER->enrol['enrolled'][$coursecontext->instanceid] > time()) {
1927                     return true;
1928                 }
1929             }
1930         }
1932         if ($onlyactive) {
1933             // look for active enrolments only
1934             $until = enrol_get_enrolment_end($coursecontext->instanceid, $userid);
1936             if ($until === false) {
1937                 return false;
1938             }
1940             if ($USER->id == $userid) {
1941                 if ($until == 0) {
1942                     $until = ENROL_MAX_TIMESTAMP;
1943                 }
1944                 $USER->enrol['enrolled'][$coursecontext->instanceid] = $until;
1945                 if (isset($USER->enrol['tempguest'][$coursecontext->instanceid])) {
1946                     unset($USER->enrol['tempguest'][$coursecontext->instanceid]);
1947                     remove_temp_course_roles($coursecontext);
1948                 }
1949             }
1951         } else {
1952             // any enrolment is good for us here, even outdated, disabled or inactive
1953             $sql = "SELECT 'x'
1954                       FROM {user_enrolments} ue
1955                       JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
1956                       JOIN {user} u ON u.id = ue.userid
1957                      WHERE ue.userid = :userid AND u.deleted = 0";
1958             $params = array('userid'=>$userid, 'courseid'=>$coursecontext->instanceid);
1959             if (!$DB->record_exists_sql($sql, $params)) {
1960                 return false;
1961             }
1962         }
1963     }
1965     if ($withcapability and !has_capability($withcapability, $context, $userid)) {
1966         return false;
1967     }
1969     return true;
1972 /**
1973  * Returns true if the user is able to access the course.
1974  *
1975  * This function is in no way, shape, or form a substitute for require_login.
1976  * It should only be used in circumstances where it is not possible to call require_login
1977  * such as the navigation.
1978  *
1979  * This function checks many of the methods of access to a course such as the view
1980  * capability, enrollments, and guest access. It also makes use of the cache
1981  * generated by require_login for guest access.
1982  *
1983  * The flags within the $USER object that are used here should NEVER be used outside
1984  * of this function can_access_course and require_login. Doing so WILL break future
1985  * versions.
1986  *
1987  * @param stdClass $course record
1988  * @param stdClass|int|null $user user record or id, current user if null
1989  * @param string $withcapability Check for this capability as well.
1990  * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
1991  * @return boolean Returns true if the user is able to access the course
1992  */
1993 function can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false) {
1994     global $DB, $USER;
1996     // this function originally accepted $coursecontext parameter
1997     if ($course instanceof context) {
1998         if ($course instanceof context_course) {
1999             debugging('deprecated context parameter, please use $course record');
2000             $coursecontext = $course;
2001             $course = $DB->get_record('course', array('id'=>$coursecontext->instanceid));
2002         } else {
2003             debugging('Invalid context parameter, please use $course record');
2004             return false;
2005         }
2006     } else {
2007         $coursecontext = context_course::instance($course->id);
2008     }
2010     if (!isset($USER->id)) {
2011         // should never happen
2012         $USER->id = 0;
2013     }
2015     // make sure there is a user specified
2016     if ($user === null) {
2017         $userid = $USER->id;
2018     } else {
2019         $userid = is_object($user) ? $user->id : $user;
2020     }
2021     unset($user);
2023     if ($withcapability and !has_capability($withcapability, $coursecontext, $userid)) {
2024         return false;
2025     }
2027     if ($userid == $USER->id) {
2028         if (!empty($USER->access['rsw'][$coursecontext->path])) {
2029             // the fact that somebody switched role means they can access the course no matter to what role they switched
2030             return true;
2031         }
2032     }
2034     if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext, $userid)) {
2035         return false;
2036     }
2038     if (is_viewing($coursecontext, $userid)) {
2039         return true;
2040     }
2042     if ($userid != $USER->id) {
2043         // for performance reasons we do not verify temporary guest access for other users, sorry...
2044         return is_enrolled($coursecontext, $userid, '', $onlyactive);
2045     }
2047     // === from here we deal only with $USER ===
2049     $coursecontext->reload_if_dirty();
2051     if (isset($USER->enrol['enrolled'][$course->id])) {
2052         if ($USER->enrol['enrolled'][$course->id] > time()) {
2053             return true;
2054         }
2055     }
2056     if (isset($USER->enrol['tempguest'][$course->id])) {
2057         if ($USER->enrol['tempguest'][$course->id] > time()) {
2058             return true;
2059         }
2060     }
2062     if (is_enrolled($coursecontext, $USER, '', $onlyactive)) {
2063         return true;
2064     }
2066     // if not enrolled try to gain temporary guest access
2067     $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
2068     $enrols = enrol_get_plugins(true);
2069     foreach($instances as $instance) {
2070         if (!isset($enrols[$instance->enrol])) {
2071             continue;
2072         }
2073         // Get a duration for the guest access, a timestamp in the future, 0 (always) or false.
2074         $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2075         if ($until !== false and $until > time()) {
2076             $USER->enrol['tempguest'][$course->id] = $until;
2077             return true;
2078         }
2079     }
2080     if (isset($USER->enrol['tempguest'][$course->id])) {
2081         unset($USER->enrol['tempguest'][$course->id]);
2082         remove_temp_course_roles($coursecontext);
2083     }
2085     return false;
2088 /**
2089  * Returns array with sql code and parameters returning all ids
2090  * of users enrolled into course.
2091  *
2092  * This function is using 'eu[0-9]+_' prefix for table names and parameters.
2093  *
2094  * @param context $context
2095  * @param string $withcapability
2096  * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2097  * @param bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
2098  * @return array list($sql, $params)
2099  */
2100 function get_enrolled_sql(context $context, $withcapability = '', $groupid = 0, $onlyactive = false) {
2101     global $DB, $CFG;
2103     // use unique prefix just in case somebody makes some SQL magic with the result
2104     static $i = 0;
2105     $i++;
2106     $prefix = 'eu'.$i.'_';
2108     // first find the course context
2109     $coursecontext = $context->get_course_context();
2111     $isfrontpage = ($coursecontext->instanceid == SITEID);
2113     $joins  = array();
2114     $wheres = array();
2115     $params = array();
2117     list($contextids, $contextpaths) = get_context_info_list($context);
2119     // get all relevant capability info for all roles
2120     if ($withcapability) {
2121         list($incontexts, $cparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'ctx');
2122         $cparams['cap'] = $withcapability;
2124         $defs = array();
2125         $sql = "SELECT rc.id, rc.roleid, rc.permission, ctx.path
2126                   FROM {role_capabilities} rc
2127                   JOIN {context} ctx on rc.contextid = ctx.id
2128                  WHERE rc.contextid $incontexts AND rc.capability = :cap";
2129         $rcs = $DB->get_records_sql($sql, $cparams);
2130         foreach ($rcs as $rc) {
2131             $defs[$rc->path][$rc->roleid] = $rc->permission;
2132         }
2134         $access = array();
2135         if (!empty($defs)) {
2136             foreach ($contextpaths as $path) {
2137                 if (empty($defs[$path])) {
2138                     continue;
2139                 }
2140                 foreach($defs[$path] as $roleid => $perm) {
2141                     if ($perm == CAP_PROHIBIT) {
2142                         $access[$roleid] = CAP_PROHIBIT;
2143                         continue;
2144                     }
2145                     if (!isset($access[$roleid])) {
2146                         $access[$roleid] = (int)$perm;
2147                     }
2148                 }
2149             }
2150         }
2152         unset($defs);
2154         // make lists of roles that are needed and prohibited
2155         $needed     = array(); // one of these is enough
2156         $prohibited = array(); // must not have any of these
2157         foreach ($access as $roleid => $perm) {
2158             if ($perm == CAP_PROHIBIT) {
2159                 unset($needed[$roleid]);
2160                 $prohibited[$roleid] = true;
2161             } else if ($perm == CAP_ALLOW and empty($prohibited[$roleid])) {
2162                 $needed[$roleid] = true;
2163             }
2164         }
2166         $defaultuserroleid      = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
2167         $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
2169         $nobody = false;
2171         if ($isfrontpage) {
2172             if (!empty($prohibited[$defaultuserroleid]) or !empty($prohibited[$defaultfrontpageroleid])) {
2173                 $nobody = true;
2174             } else if (!empty($needed[$defaultuserroleid]) or !empty($needed[$defaultfrontpageroleid])) {
2175                 // everybody not having prohibit has the capability
2176                 $needed = array();
2177             } else if (empty($needed)) {
2178                 $nobody = true;
2179             }
2180         } else {
2181             if (!empty($prohibited[$defaultuserroleid])) {
2182                 $nobody = true;
2183             } else if (!empty($needed[$defaultuserroleid])) {
2184                 // everybody not having prohibit has the capability
2185                 $needed = array();
2186             } else if (empty($needed)) {
2187                 $nobody = true;
2188             }
2189         }
2191         if ($nobody) {
2192             // nobody can match so return some SQL that does not return any results
2193             $wheres[] = "1 = 2";
2195         } else {
2197             if ($needed) {
2198                 $ctxids = implode(',', $contextids);
2199                 $roleids = implode(',', array_keys($needed));
2200                 $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))";
2201             }
2203             if ($prohibited) {
2204                 $ctxids = implode(',', $contextids);
2205                 $roleids = implode(',', array_keys($prohibited));
2206                 $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))";
2207                 $wheres[] = "{$prefix}ra4.id IS NULL";
2208             }
2210             if ($groupid) {
2211                 $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2212                 $params["{$prefix}gmid"] = $groupid;
2213             }
2214         }
2216     } else {
2217         if ($groupid) {
2218             $joins[] = "JOIN {groups_members} {$prefix}gm ON ({$prefix}gm.userid = {$prefix}u.id AND {$prefix}gm.groupid = :{$prefix}gmid)";
2219             $params["{$prefix}gmid"] = $groupid;
2220         }
2221     }
2223     $wheres[] = "{$prefix}u.deleted = 0 AND {$prefix}u.id <> :{$prefix}guestid";
2224     $params["{$prefix}guestid"] = $CFG->siteguest;
2226     if ($isfrontpage) {
2227         // all users are "enrolled" on the frontpage
2228     } else {
2229         $joins[] = "JOIN {user_enrolments} {$prefix}ue ON {$prefix}ue.userid = {$prefix}u.id";
2230         $joins[] = "JOIN {enrol} {$prefix}e ON ({$prefix}e.id = {$prefix}ue.enrolid AND {$prefix}e.courseid = :{$prefix}courseid)";
2231         $params[$prefix.'courseid'] = $coursecontext->instanceid;
2233         if ($onlyactive) {
2234             $wheres[] = "{$prefix}ue.status = :{$prefix}active AND {$prefix}e.status = :{$prefix}enabled";
2235             $wheres[] = "{$prefix}ue.timestart < :{$prefix}now1 AND ({$prefix}ue.timeend = 0 OR {$prefix}ue.timeend > :{$prefix}now2)";
2236             $now = round(time(), -2); // rounding helps caching in DB
2237             $params = array_merge($params, array($prefix.'enabled'=>ENROL_INSTANCE_ENABLED,
2238                                                  $prefix.'active'=>ENROL_USER_ACTIVE,
2239                                                  $prefix.'now1'=>$now, $prefix.'now2'=>$now));
2240         }
2241     }
2243     $joins = implode("\n", $joins);
2244     $wheres = "WHERE ".implode(" AND ", $wheres);
2246     $sql = "SELECT DISTINCT {$prefix}u.id
2247               FROM {user} {$prefix}u
2248             $joins
2249            $wheres";
2251     return array($sql, $params);
2254 /**
2255  * Returns list of users enrolled into course.
2256  *
2257  * @param context $context
2258  * @param string $withcapability
2259  * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2260  * @param string $userfields requested user record fields
2261  * @param string $orderby
2262  * @param int $limitfrom return a subset of records, starting at this point (optional, required if $limitnum is set).
2263  * @param int $limitnum return a subset comprising this many records (optional, required if $limitfrom is set).
2264  * @return array of user records
2265  */
2266 function get_enrolled_users(context $context, $withcapability = '', $groupid = 0, $userfields = 'u.*', $orderby = '', $limitfrom = 0, $limitnum = 0) {
2267     global $DB;
2269     list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2270     $sql = "SELECT $userfields
2271               FROM {user} u
2272               JOIN ($esql) je ON je.id = u.id
2273              WHERE u.deleted = 0";
2275     if ($orderby) {
2276         $sql = "$sql ORDER BY $orderby";
2277     } else {
2278         $sql = "$sql ORDER BY u.lastname ASC, u.firstname ASC";
2279     }
2281     return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
2284 /**
2285  * Counts list of users enrolled into course (as per above function)
2286  *
2287  * @param context $context
2288  * @param string $withcapability
2289  * @param int $groupid 0 means ignore groups, any other value limits the result by group id
2290  * @return array of user records
2291  */
2292 function count_enrolled_users(context $context, $withcapability = '', $groupid = 0) {
2293     global $DB;
2295     list($esql, $params) = get_enrolled_sql($context, $withcapability, $groupid);
2296     $sql = "SELECT count(u.id)
2297               FROM {user} u
2298               JOIN ($esql) je ON je.id = u.id
2299              WHERE u.deleted = 0";
2301     return $DB->count_records_sql($sql, $params);
2304 /**
2305  * Loads the capability definitions for the component (from file).
2306  *
2307  * Loads the capability definitions for the component (from file). If no
2308  * capabilities are defined for the component, we simply return an empty array.
2309  *
2310  * @param string $component full plugin name, examples: 'moodle', 'mod_forum'
2311  * @return array array of capabilities
2312  */
2313 function load_capability_def($component) {
2314     $defpath = get_component_directory($component).'/db/access.php';
2316     $capabilities = array();
2317     if (file_exists($defpath)) {
2318         require($defpath);
2319         if (!empty(${$component.'_capabilities'})) {
2320             // BC capability array name
2321             // since 2.0 we prefer $capabilities instead - it is easier to use and matches db/* files
2322             debugging('componentname_capabilities array is deprecated, please use $capabilities array only in access.php files');
2323             $capabilities = ${$component.'_capabilities'};
2324         }
2325     }
2327     return $capabilities;
2330 /**
2331  * Gets the capabilities that have been cached in the database for this component.
2332  *
2333  * @param string $component - examples: 'moodle', 'mod_forum'
2334  * @return array array of capabilities
2335  */
2336 function get_cached_capabilities($component = 'moodle') {
2337     global $DB;
2338     return $DB->get_records('capabilities', array('component'=>$component));
2341 /**
2342  * Returns default capabilities for given role archetype.
2343  *
2344  * @param string $archetype role archetype
2345  * @return array
2346  */
2347 function get_default_capabilities($archetype) {
2348     global $DB;
2350     if (!$archetype) {
2351         return array();
2352     }
2354     $alldefs = array();
2355     $defaults = array();
2356     $components = array();
2357     $allcaps = $DB->get_records('capabilities');
2359     foreach ($allcaps as $cap) {
2360         if (!in_array($cap->component, $components)) {
2361             $components[] = $cap->component;
2362             $alldefs = array_merge($alldefs, load_capability_def($cap->component));
2363         }
2364     }
2365     foreach($alldefs as $name=>$def) {
2366         // Use array 'archetypes if available. Only if not specified, use 'legacy'.
2367         if (isset($def['archetypes'])) {
2368             if (isset($def['archetypes'][$archetype])) {
2369                 $defaults[$name] = $def['archetypes'][$archetype];
2370             }
2371         // 'legacy' is for backward compatibility with 1.9 access.php
2372         } else {
2373             if (isset($def['legacy'][$archetype])) {
2374                 $defaults[$name] = $def['legacy'][$archetype];
2375             }
2376         }
2377     }
2379     return $defaults;
2382 /**
2383  * Reset role capabilities to default according to selected role archetype.
2384  * If no archetype selected, removes all capabilities.
2385  *
2386  * @param int $roleid
2387  * @return void
2388  */
2389 function reset_role_capabilities($roleid) {
2390     global $DB;
2392     $role = $DB->get_record('role', array('id'=>$roleid), '*', MUST_EXIST);
2393     $defaultcaps = get_default_capabilities($role->archetype);
2395     $systemcontext = context_system::instance();
2397     $DB->delete_records('role_capabilities', array('roleid'=>$roleid));
2399     foreach($defaultcaps as $cap=>$permission) {
2400         assign_capability($cap, $permission, $roleid, $systemcontext->id);
2401     }
2404 /**
2405  * Updates the capabilities table with the component capability definitions.
2406  * If no parameters are given, the function updates the core moodle
2407  * capabilities.
2408  *
2409  * Note that the absence of the db/access.php capabilities definition file
2410  * will cause any stored capabilities for the component to be removed from
2411  * the database.
2412  *
2413  * @param string $component examples: 'moodle', 'mod/forum', 'block/quiz_results'
2414  * @return boolean true if success, exception in case of any problems
2415  */
2416 function update_capabilities($component = 'moodle') {
2417     global $DB, $OUTPUT;
2419     $storedcaps = array();
2421     $filecaps = load_capability_def($component);
2422     foreach($filecaps as $capname=>$unused) {
2423         if (!preg_match('|^[a-z]+/[a-z_0-9]+:[a-z_0-9]+$|', $capname)) {
2424             debugging("Coding problem: Invalid capability name '$capname', use 'clonepermissionsfrom' field for migration.");
2425         }
2426     }
2428     $cachedcaps = get_cached_capabilities($component);
2429     if ($cachedcaps) {
2430         foreach ($cachedcaps as $cachedcap) {
2431             array_push($storedcaps, $cachedcap->name);
2432             // update risk bitmasks and context levels in existing capabilities if needed
2433             if (array_key_exists($cachedcap->name, $filecaps)) {
2434                 if (!array_key_exists('riskbitmask', $filecaps[$cachedcap->name])) {
2435                     $filecaps[$cachedcap->name]['riskbitmask'] = 0; // no risk if not specified
2436                 }
2437                 if ($cachedcap->captype != $filecaps[$cachedcap->name]['captype']) {
2438                     $updatecap = new stdClass();
2439                     $updatecap->id = $cachedcap->id;
2440                     $updatecap->captype = $filecaps[$cachedcap->name]['captype'];
2441                     $DB->update_record('capabilities', $updatecap);
2442                 }
2443                 if ($cachedcap->riskbitmask != $filecaps[$cachedcap->name]['riskbitmask']) {
2444                     $updatecap = new stdClass();
2445                     $updatecap->id = $cachedcap->id;
2446                     $updatecap->riskbitmask = $filecaps[$cachedcap->name]['riskbitmask'];
2447                     $DB->update_record('capabilities', $updatecap);
2448                 }
2450                 if (!array_key_exists('contextlevel', $filecaps[$cachedcap->name])) {
2451                     $filecaps[$cachedcap->name]['contextlevel'] = 0; // no context level defined
2452                 }
2453                 if ($cachedcap->contextlevel != $filecaps[$cachedcap->name]['contextlevel']) {
2454                     $updatecap = new stdClass();
2455                     $updatecap->id = $cachedcap->id;
2456                     $updatecap->contextlevel = $filecaps[$cachedcap->name]['contextlevel'];
2457                     $DB->update_record('capabilities', $updatecap);
2458                 }
2459             }
2460         }
2461     }
2463     // Are there new capabilities in the file definition?
2464     $newcaps = array();
2466     foreach ($filecaps as $filecap => $def) {
2467         if (!$storedcaps ||
2468                 ($storedcaps && in_array($filecap, $storedcaps) === false)) {
2469             if (!array_key_exists('riskbitmask', $def)) {
2470                 $def['riskbitmask'] = 0; // no risk if not specified
2471             }
2472             $newcaps[$filecap] = $def;
2473         }
2474     }
2475     // Add new capabilities to the stored definition.
2476     foreach ($newcaps as $capname => $capdef) {
2477         $capability = new stdClass();
2478         $capability->name         = $capname;
2479         $capability->captype      = $capdef['captype'];
2480         $capability->contextlevel = $capdef['contextlevel'];
2481         $capability->component    = $component;
2482         $capability->riskbitmask  = $capdef['riskbitmask'];
2484         $DB->insert_record('capabilities', $capability, false);
2486         if (isset($capdef['clonepermissionsfrom']) && in_array($capdef['clonepermissionsfrom'], $storedcaps)){
2487             if ($rolecapabilities = $DB->get_records('role_capabilities', array('capability'=>$capdef['clonepermissionsfrom']))){
2488                 foreach ($rolecapabilities as $rolecapability){
2489                     //assign_capability will update rather than insert if capability exists
2490                     if (!assign_capability($capname, $rolecapability->permission,
2491                                             $rolecapability->roleid, $rolecapability->contextid, true)){
2492                          echo $OUTPUT->notification('Could not clone capabilities for '.$capname);
2493                     }
2494                 }
2495             }
2496         // we ignore archetype key if we have cloned permissions
2497         } else if (isset($capdef['archetypes']) && is_array($capdef['archetypes'])) {
2498             assign_legacy_capabilities($capname, $capdef['archetypes']);
2499         // 'legacy' is for backward compatibility with 1.9 access.php
2500         } else if (isset($capdef['legacy']) && is_array($capdef['legacy'])) {
2501             assign_legacy_capabilities($capname, $capdef['legacy']);
2502         }
2503     }
2504     // Are there any capabilities that have been removed from the file
2505     // definition that we need to delete from the stored capabilities and
2506     // role assignments?
2507     capabilities_cleanup($component, $filecaps);
2509     // reset static caches
2510     accesslib_clear_all_caches(false);
2512     return true;
2515 /**
2516  * Deletes cached capabilities that are no longer needed by the component.
2517  * Also unassigns these capabilities from any roles that have them.
2518  *
2519  * @param string $component examples: 'moodle', 'mod_forum', 'block_quiz_results'
2520  * @param array $newcapdef array of the new capability definitions that will be
2521  *                     compared with the cached capabilities
2522  * @return int number of deprecated capabilities that have been removed
2523  */
2524 function capabilities_cleanup($component, $newcapdef = null) {
2525     global $DB;
2527     $removedcount = 0;
2529     if ($cachedcaps = get_cached_capabilities($component)) {
2530         foreach ($cachedcaps as $cachedcap) {
2531             if (empty($newcapdef) ||
2532                         array_key_exists($cachedcap->name, $newcapdef) === false) {
2534                 // Remove from capabilities cache.
2535                 $DB->delete_records('capabilities', array('name'=>$cachedcap->name));
2536                 $removedcount++;
2537                 // Delete from roles.
2538                 if ($roles = get_roles_with_capability($cachedcap->name)) {
2539                     foreach($roles as $role) {
2540                         if (!unassign_capability($cachedcap->name, $role->id)) {
2541                             print_error('cannotunassigncap', 'error', '', (object)array('cap'=>$cachedcap->name, 'role'=>$role->name));
2542                         }
2543                     }
2544                 }
2545             } // End if.
2546         }
2547     }
2548     return $removedcount;
2551 /**
2552  * Returns an array of all the known types of risk
2553  * The array keys can be used, for example as CSS class names, or in calls to
2554  * print_risk_icon. The values are the corresponding RISK_ constants.
2555  *
2556  * @return array all the known types of risk.
2557  */
2558 function get_all_risks() {
2559     return array(
2560         'riskmanagetrust' => RISK_MANAGETRUST,
2561         'riskconfig'      => RISK_CONFIG,
2562         'riskxss'         => RISK_XSS,
2563         'riskpersonal'    => RISK_PERSONAL,
2564         'riskspam'        => RISK_SPAM,
2565         'riskdataloss'    => RISK_DATALOSS,
2566     );
2569 /**
2570  * Return a link to moodle docs for a given capability name
2571  *
2572  * @param object $capability a capability - a row from the mdl_capabilities table.
2573  * @return string the human-readable capability name as a link to Moodle Docs.
2574  */
2575 function get_capability_docs_link($capability) {
2576     $url = get_docs_url('Capabilities/' . $capability->name);
2577     return '<a onclick="this.target=\'docspopup\'" href="' . $url . '">' . get_capability_string($capability->name) . '</a>';
2580 /**
2581  * This function pulls out all the resolved capabilities (overrides and
2582  * defaults) of a role used in capability overrides in contexts at a given
2583  * context.
2584  *
2585  * @param context $context
2586  * @param int $roleid
2587  * @param string $cap capability, optional, defaults to ''
2588  * @return array of capabilities
2589  */
2590 function role_context_capabilities($roleid, context $context, $cap = '') {
2591     global $DB;
2593     $contexts = $context->get_parent_context_ids(true);
2594     $contexts = '('.implode(',', $contexts).')';
2596     $params = array($roleid);
2598     if ($cap) {
2599         $search = " AND rc.capability = ? ";
2600         $params[] = $cap;
2601     } else {
2602         $search = '';
2603     }
2605     $sql = "SELECT rc.*
2606               FROM {role_capabilities} rc, {context} c
2607              WHERE rc.contextid in $contexts
2608                    AND rc.roleid = ?
2609                    AND rc.contextid = c.id $search
2610           ORDER BY c.contextlevel DESC, rc.capability DESC";
2612     $capabilities = array();
2614     if ($records = $DB->get_records_sql($sql, $params)) {
2615         // We are traversing via reverse order.
2616         foreach ($records as $record) {
2617             // If not set yet (i.e. inherit or not set at all), or currently we have a prohibit
2618             if (!isset($capabilities[$record->capability]) || $record->permission<-500) {
2619                 $capabilities[$record->capability] = $record->permission;
2620             }
2621         }
2622     }
2623     return $capabilities;
2626 /**
2627  * Constructs array with contextids as first parameter and context paths,
2628  * in both cases bottom top including self.
2629  *
2630  * @private
2631  * @param context $context
2632  * @return array
2633  */
2634 function get_context_info_list(context $context) {
2635     $contextids = explode('/', ltrim($context->path, '/'));
2636     $contextpaths = array();
2637     $contextids2 = $contextids;
2638     while ($contextids2) {
2639         $contextpaths[] = '/' . implode('/', $contextids2);
2640         array_pop($contextids2);
2641     }
2642     return array($contextids, $contextpaths);
2645 /**
2646  * Check if context is the front page context or a context inside it
2647  *
2648  * Returns true if this context is the front page context, or a context inside it,
2649  * otherwise false.
2650  *
2651  * @param context $context a context object.
2652  * @return bool
2653  */
2654 function is_inside_frontpage(context $context) {
2655     $frontpagecontext = context_course::instance(SITEID);
2656     return strpos($context->path . '/', $frontpagecontext->path . '/') === 0;
2659 /**
2660  * Returns capability information (cached)
2661  *
2662  * @param string $capabilityname
2663  * @return object or null if capability not found
2664  */
2665 function get_capability_info($capabilityname) {
2666     global $ACCESSLIB_PRIVATE, $DB; // one request per page only
2668     //TODO: MUC - this could be cached in shared memory, it would eliminate 1 query per page
2670     if (empty($ACCESSLIB_PRIVATE->capabilities)) {
2671         $ACCESSLIB_PRIVATE->capabilities = array();
2672         $caps = $DB->get_records('capabilities', array(), 'id, name, captype, riskbitmask');
2673         foreach ($caps as $cap) {
2674             $capname = $cap->name;
2675             unset($cap->id);
2676             unset($cap->name);
2677             $cap->riskbitmask = (int)$cap->riskbitmask;
2678             $ACCESSLIB_PRIVATE->capabilities[$capname] = $cap;
2679         }
2680     }
2682     return isset($ACCESSLIB_PRIVATE->capabilities[$capabilityname]) ? $ACCESSLIB_PRIVATE->capabilities[$capabilityname] : null;
2685 /**
2686  * Returns the human-readable, translated version of the capability.
2687  * Basically a big switch statement.
2688  *
2689  * @param string $capabilityname e.g. mod/choice:readresponses
2690  * @return string
2691  */
2692 function get_capability_string($capabilityname) {
2694     // Typical capability name is 'plugintype/pluginname:capabilityname'
2695     list($type, $name, $capname) = preg_split('|[/:]|', $capabilityname);
2697     if ($type === 'moodle') {
2698         $component = 'core_role';
2699     } else if ($type === 'quizreport') {
2700         //ugly hack!!
2701         $component = 'quiz_'.$name;
2702     } else {
2703         $component = $type.'_'.$name;
2704     }
2706     $stringname = $name.':'.$capname;
2708     if ($component === 'core_role' or get_string_manager()->string_exists($stringname, $component)) {
2709         return get_string($stringname, $component);
2710     }
2712     $dir = get_component_directory($component);
2713     if (!file_exists($dir)) {
2714         // plugin broken or does not exist, do not bother with printing of debug message
2715         return $capabilityname.' ???';
2716     }
2718     // something is wrong in plugin, better print debug
2719     return get_string($stringname, $component);
2722 /**
2723  * This gets the mod/block/course/core etc strings.
2724  *
2725  * @param string $component
2726  * @param int $contextlevel
2727  * @return string|bool String is success, false if failed
2728  */
2729 function get_component_string($component, $contextlevel) {
2731     if ($component === 'moodle' or $component === 'core') {
2732         switch ($contextlevel) {
2733             // TODO: this should probably use context level names instead
2734             case CONTEXT_SYSTEM:    return get_string('coresystem');
2735             case CONTEXT_USER:      return get_string('users');
2736             case CONTEXT_COURSECAT: return get_string('categories');
2737             case CONTEXT_COURSE:    return get_string('course');
2738             case CONTEXT_MODULE:    return get_string('activities');
2739             case CONTEXT_BLOCK:     return get_string('block');
2740             default:                print_error('unknowncontext');
2741         }
2742     }
2744     list($type, $name) = normalize_component($component);
2745     $dir = get_plugin_directory($type, $name);
2746     if (!file_exists($dir)) {
2747         // plugin not installed, bad luck, there is no way to find the name
2748         return $component.' ???';
2749     }
2751     switch ($type) {
2752         // TODO: this is really hacky, anyway it should be probably moved to lib/pluginlib.php
2753         case 'quiz':         return get_string($name.':componentname', $component);// insane hack!!!
2754         case 'repository':   return get_string('repository', 'repository').': '.get_string('pluginname', $component);
2755         case 'gradeimport':  return get_string('gradeimport', 'grades').': '.get_string('pluginname', $component);
2756         case 'gradeexport':  return get_string('gradeexport', 'grades').': '.get_string('pluginname', $component);
2757         case 'gradereport':  return get_string('gradereport', 'grades').': '.get_string('pluginname', $component);
2758         case 'webservice':   return get_string('webservice', 'webservice').': '.get_string('pluginname', $component);
2759         case 'block':        return get_string('block').': '.get_string('pluginname', basename($component));
2760         case 'mod':
2761             if (get_string_manager()->string_exists('pluginname', $component)) {
2762                 return get_string('activity').': '.get_string('pluginname', $component);
2763             } else {
2764                 return get_string('activity').': '.get_string('modulename', $component);
2765             }
2766         default: return get_string('pluginname', $component);
2767     }
2770 /**
2771  * Gets the list of roles assigned to this context and up (parents)
2772  * from the list of roles that are visible on user profile page
2773  * and participants page.
2774  *
2775  * @param context $context
2776  * @return array
2777  */
2778 function get_profile_roles(context $context) {
2779     global $CFG, $DB;
2781     if (empty($CFG->profileroles)) {
2782         return array();
2783     }
2785     list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2786     list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2787     $params = array_merge($params, $cparams);
2789     $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2790               FROM {role_assignments} ra, {role} r
2791              WHERE r.id = ra.roleid
2792                    AND ra.contextid $contextlist
2793                    AND r.id $rallowed
2794           ORDER BY r.sortorder ASC";
2796     return $DB->get_records_sql($sql, $params);
2799 /**
2800  * Gets the list of roles assigned to this context and up (parents)
2801  *
2802  * @param context $context
2803  * @return array
2804  */
2805 function get_roles_used_in_context(context $context) {
2806     global $DB;
2808     list($contextlist, $params) = $DB->get_in_or_equal($context->get_parent_context_ids(true));
2810     $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2811               FROM {role_assignments} ra, {role} r
2812              WHERE r.id = ra.roleid
2813                    AND ra.contextid $contextlist
2814           ORDER BY r.sortorder ASC";
2816     return $DB->get_records_sql($sql, $params);
2819 /**
2820  * This function is used to print roles column in user profile page.
2821  * It is using the CFG->profileroles to limit the list to only interesting roles.
2822  * (The permission tab has full details of user role assignments.)
2823  *
2824  * @param int $userid
2825  * @param int $courseid
2826  * @return string
2827  */
2828 function get_user_roles_in_course($userid, $courseid) {
2829     global $CFG, $DB;
2831     if (empty($CFG->profileroles)) {
2832         return '';
2833     }
2835     if ($courseid == SITEID) {
2836         $context = context_system::instance();
2837     } else {
2838         $context = context_course::instance($courseid);
2839     }
2841     if (empty($CFG->profileroles)) {
2842         return array();
2843     }
2845     list($rallowed, $params) = $DB->get_in_or_equal(explode(',', $CFG->profileroles), SQL_PARAMS_NAMED, 'a');
2846     list($contextlist, $cparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'p');
2847     $params = array_merge($params, $cparams);
2849     $sql = "SELECT DISTINCT r.id, r.name, r.shortname, r.sortorder
2850               FROM {role_assignments} ra, {role} r
2851              WHERE r.id = ra.roleid
2852                    AND ra.contextid $contextlist
2853                    AND r.id $rallowed
2854                    AND ra.userid = :userid
2855           ORDER BY r.sortorder ASC";
2856     $params['userid'] = $userid;
2858     $rolestring = '';
2860     if ($roles = $DB->get_records_sql($sql, $params)) {
2861         foreach ($roles as $userrole) {
2862             $rolenames[$userrole->id] = $userrole->name;
2863         }
2865         $rolenames = role_fix_names($rolenames, $context);   // Substitute aliases
2867         foreach ($rolenames as $roleid => $rolename) {
2868             $rolenames[$roleid] = '<a href="'.$CFG->wwwroot.'/user/index.php?contextid='.$context->id.'&amp;roleid='.$roleid.'">'.$rolename.'</a>';
2869         }
2870         $rolestring = implode(',', $rolenames);
2871     }
2873     return $rolestring;
2876 /**
2877  * Checks if a user can assign users to a particular role in this context
2878  *
2879  * @param context $context
2880  * @param int $targetroleid - the id of the role you want to assign users to
2881  * @return boolean
2882  */
2883 function user_can_assign(context $context, $targetroleid) {
2884     global $DB;
2886     // first check if user has override capability
2887     // if not return false;
2888     if (!has_capability('moodle/role:assign', $context)) {
2889         return false;
2890     }
2891     // pull out all active roles of this user from this context(or above)
2892     if ($userroles = get_user_roles($context)) {
2893         foreach ($userroles as $userrole) {
2894             // if any in the role_allow_override table, then it's ok
2895             if ($DB->get_record('role_allow_assign', array('roleid'=>$userrole->roleid, 'allowassign'=>$targetroleid))) {
2896                 return true;
2897             }
2898         }
2899     }
2901     return false;
2904 /**
2905  * Returns all site roles in correct sort order.
2906  *
2907  * @return array
2908  */
2909 function get_all_roles() {
2910     global $DB;
2911     return $DB->get_records('role', null, 'sortorder ASC');
2914 /**
2915  * Returns roles of a specified archetype
2916  *
2917  * @param string $archetype
2918  * @return array of full role records
2919  */
2920 function get_archetype_roles($archetype) {
2921     global $DB;
2922     return $DB->get_records('role', array('archetype'=>$archetype), 'sortorder ASC');
2925 /**
2926  * Gets all the user roles assigned in this context, or higher contexts
2927  * this is mainly used when checking if a user can assign a role, or overriding a role
2928  * i.e. we need to know what this user holds, in order to verify against allow_assign and
2929  * allow_override tables
2930  *
2931  * @param context $context
2932  * @param int $userid
2933  * @param bool $checkparentcontexts defaults to true
2934  * @param string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
2935  * @return array
2936  */
2937 function get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC') {
2938     global $USER, $DB;
2940     if (empty($userid)) {
2941         if (empty($USER->id)) {
2942             return array();
2943         }
2944         $userid = $USER->id;
2945     }
2947     if ($checkparentcontexts) {
2948         $contextids = $context->get_parent_context_ids();
2949     } else {
2950         $contextids = array();
2951     }
2952     $contextids[] = $context->id;
2954     list($contextids, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_QM);
2956     array_unshift($params, $userid);
2958     $sql = "SELECT ra.*, r.name, r.shortname
2959               FROM {role_assignments} ra, {role} r, {context} c
2960              WHERE ra.userid = ?
2961                    AND ra.roleid = r.id
2962                    AND ra.contextid = c.id
2963                    AND ra.contextid $contextids
2964           ORDER BY $order";
2966     return $DB->get_records_sql($sql ,$params);
2969 /**
2970  * Creates a record in the role_allow_override table
2971  *
2972  * @param int $sroleid source roleid
2973  * @param int $troleid target roleid
2974  * @return void
2975  */
2976 function allow_override($sroleid, $troleid) {
2977     global $DB;
2979     $record = new stdClass();
2980     $record->roleid        = $sroleid;
2981     $record->allowoverride = $troleid;
2982     $DB->insert_record('role_allow_override', $record);
2985 /**
2986  * Creates a record in the role_allow_assign table
2987  *
2988  * @param int $fromroleid source roleid
2989  * @param int $targetroleid target roleid
2990  * @return void
2991  */
2992 function allow_assign($fromroleid, $targetroleid) {
2993     global $DB;
2995     $record = new stdClass();
2996     $record->roleid      = $fromroleid;
2997     $record->allowassign = $targetroleid;
2998     $DB->insert_record('role_allow_assign', $record);
3001 /**
3002  * Creates a record in the role_allow_switch table
3003  *
3004  * @param int $fromroleid source roleid
3005  * @param int $targetroleid target roleid
3006  * @return void
3007  */
3008 function allow_switch($fromroleid, $targetroleid) {
3009     global $DB;
3011     $record = new stdClass();
3012     $record->roleid      = $fromroleid;
3013     $record->allowswitch = $targetroleid;
3014     $DB->insert_record('role_allow_switch', $record);
3017 /**
3018  * Gets a list of roles that this user can assign in this context
3019  *
3020  * @param context $context the context.
3021  * @param int $rolenamedisplay the type of role name to display. One of the
3022  *      ROLENAME_X constants. Default ROLENAME_ALIAS.
3023  * @param bool $withusercounts if true, count the number of users with each role.
3024  * @param integer|object $user A user id or object. By default (null) checks the permissions of the current user.
3025  * @return array if $withusercounts is false, then an array $roleid => $rolename.
3026  *      if $withusercounts is true, returns a list of three arrays,
3027  *      $rolenames, $rolecounts, and $nameswithcounts.
3028  */
3029 function get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null) {
3030     global $USER, $DB;
3032     // make sure there is a real user specified
3033     if ($user === null) {
3034         $userid = isset($USER->id) ? $USER->id : 0;
3035     } else {
3036         $userid = is_object($user) ? $user->id : $user;
3037     }
3039     if (!has_capability('moodle/role:assign', $context, $userid)) {
3040         if ($withusercounts) {
3041             return array(array(), array(), array());
3042         } else {
3043             return array();
3044         }
3045     }
3047     $parents = $context->get_parent_context_ids(true);
3048     $contexts = implode(',' , $parents);
3050     $params = array();
3051     $extrafields = '';
3052     if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT or $rolenamedisplay == ROLENAME_SHORT) {
3053         $extrafields .= ', r.shortname';
3054     }
3056     if ($withusercounts) {
3057         $extrafields = ', (SELECT count(u.id)
3058                              FROM {role_assignments} cra JOIN {user} u ON cra.userid = u.id
3059                             WHERE cra.roleid = r.id AND cra.contextid = :conid AND u.deleted = 0
3060                           ) AS usercount';
3061         $params['conid'] = $context->id;
3062     }
3064     if (is_siteadmin($userid)) {
3065         // show all roles allowed in this context to admins
3066         $assignrestriction = "";
3067     } else {
3068         $assignrestriction = "JOIN (SELECT DISTINCT raa.allowassign AS id
3069                                       FROM {role_allow_assign} raa
3070                                       JOIN {role_assignments} ra ON ra.roleid = raa.roleid
3071                                      WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3072                                    ) ar ON ar.id = r.id";
3073         $params['userid'] = $userid;
3074     }
3075     $params['contextlevel'] = $context->contextlevel;
3076     $sql = "SELECT r.id, r.name $extrafields
3077               FROM {role} r
3078               $assignrestriction
3079               JOIN {role_context_levels} rcl ON r.id = rcl.roleid
3080              WHERE rcl.contextlevel = :contextlevel
3081           ORDER BY r.sortorder ASC";
3082     $roles = $DB->get_records_sql($sql, $params);
3084     $rolenames = array();
3085     foreach ($roles as $role) {
3086         if ($rolenamedisplay == ROLENAME_SHORT) {
3087             $rolenames[$role->id] = $role->shortname;
3088             continue;
3089         }
3090         $rolenames[$role->id] = $role->name;
3091         if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3092             $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3093         }
3094     }
3095     if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT and $rolenamedisplay != ROLENAME_SHORT) {
3096         $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3097     }
3099     if (!$withusercounts) {
3100         return $rolenames;
3101     }
3103     $rolecounts = array();
3104     $nameswithcounts = array();
3105     foreach ($roles as $role) {
3106         $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->usercount . ')';
3107         $rolecounts[$role->id] = $roles[$role->id]->usercount;
3108     }
3109     return array($rolenames, $rolecounts, $nameswithcounts);
3112 /**
3113  * Gets a list of roles that this user can switch to in a context
3114  *
3115  * Gets a list of roles that this user can switch to in a context, for the switchrole menu.
3116  * This function just process the contents of the role_allow_switch table. You also need to
3117  * test the moodle/role:switchroles to see if the user is allowed to switch in the first place.
3118  *
3119  * @param context $context a context.
3120  * @return array an array $roleid => $rolename.
3121  */
3122 function get_switchable_roles(context $context) {
3123     global $USER, $DB;
3125     $params = array();
3126     $extrajoins = '';
3127     $extrawhere = '';
3128     if (!is_siteadmin()) {
3129         // Admins are allowed to switch to any role with.
3130         // Others are subject to the additional constraint that the switch-to role must be allowed by
3131         // 'role_allow_switch' for some role they have assigned in this context or any parent.
3132         $parents = $context->get_parent_context_ids(true);
3133         $contexts = implode(',' , $parents);
3135         $extrajoins = "JOIN {role_allow_switch} ras ON ras.allowswitch = rc.roleid
3136         JOIN {role_assignments} ra ON ra.roleid = ras.roleid";
3137         $extrawhere = "WHERE ra.userid = :userid AND ra.contextid IN ($contexts)";
3138         $params['userid'] = $USER->id;
3139     }
3141     $query = "
3142         SELECT r.id, r.name
3143           FROM (SELECT DISTINCT rc.roleid
3144                   FROM {role_capabilities} rc
3145                   $extrajoins
3146                   $extrawhere) idlist
3147           JOIN {role} r ON r.id = idlist.roleid
3148       ORDER BY r.sortorder";
3150     $rolenames = $DB->get_records_sql_menu($query, $params);
3151     return role_fix_names($rolenames, $context, ROLENAME_ALIAS);
3154 /**
3155  * Gets a list of roles that this user can override in this context.
3156  *
3157  * @param context $context the context.
3158  * @param int $rolenamedisplay the type of role name to display. One of the
3159  *      ROLENAME_X constants. Default ROLENAME_ALIAS.
3160  * @param bool $withcounts if true, count the number of overrides that are set for each role.
3161  * @return array if $withcounts is false, then an array $roleid => $rolename.
3162  *      if $withusercounts is true, returns a list of three arrays,
3163  *      $rolenames, $rolecounts, and $nameswithcounts.
3164  */
3165 function get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false) {
3166     global $USER, $DB;
3168     if (!has_any_capability(array('moodle/role:safeoverride', 'moodle/role:override'), $context)) {
3169         if ($withcounts) {
3170             return array(array(), array(), array());
3171         } else {
3172             return array();
3173         }
3174     }
3176     $parents = $context->get_parent_context_ids(true);
3177     $contexts = implode(',' , $parents);
3179     $params = array();
3180     $extrafields = '';
3181     if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3182         $extrafields .= ', ro.shortname';
3183     }
3185     $params['userid'] = $USER->id;
3186     if ($withcounts) {
3187         $extrafields = ', (SELECT COUNT(rc.id) FROM {role_capabilities} rc
3188                 WHERE rc.roleid = ro.id AND rc.contextid = :conid) AS overridecount';
3189         $params['conid'] = $context->id;
3190     }
3192     if (is_siteadmin()) {
3193         // show all roles to admins
3194         $roles = $DB->get_records_sql("
3195             SELECT ro.id, ro.name$extrafields
3196               FROM {role} ro
3197           ORDER BY ro.sortorder ASC", $params);
3199     } else {
3200         $roles = $DB->get_records_sql("
3201             SELECT ro.id, ro.name$extrafields
3202               FROM {role} ro
3203               JOIN (SELECT DISTINCT r.id
3204                       FROM {role} r
3205                       JOIN {role_allow_override} rao ON r.id = rao.allowoverride
3206                       JOIN {role_assignments} ra ON rao.roleid = ra.roleid
3207                      WHERE ra.userid = :userid AND ra.contextid IN ($contexts)
3208                    ) inline_view ON ro.id = inline_view.id
3209           ORDER BY ro.sortorder ASC", $params);
3210     }
3212     $rolenames = array();
3213     foreach ($roles as $role) {
3214         $rolenames[$role->id] = $role->name;
3215         if ($rolenamedisplay == ROLENAME_ORIGINALANDSHORT) {
3216             $rolenames[$role->id] .= ' (' . $role->shortname . ')';
3217         }
3218     }
3219     if ($rolenamedisplay != ROLENAME_ORIGINALANDSHORT) {
3220         $rolenames = role_fix_names($rolenames, $context, $rolenamedisplay);
3221     }
3223     if (!$withcounts) {
3224         return $rolenames;
3227     $rolecounts = array();
3228     $nameswithcounts = array();
3229     foreach ($roles as $role) {
3230         $nameswithcounts[$role->id] = $rolenames[$role->id] . ' (' . $roles[$role->id]->overridecount . ')';
3231         $rolecounts[$role->id] = $roles[$role->id]->overridecount;
3232     }
3233     return array($rolenames, $rolecounts, $nameswithcounts);
3236 /**
3237  * Create a role menu suitable for default role selection in enrol plugins.
3238  * @param context $context
3239  * @param int $addroleid current or default role - always added to list
3240  * @return array roleid=>localised role name
3241  */
3242 function get_default_enrol_roles(context $context, $addroleid = null) {
3243     global $DB;
3245     $params = array('contextlevel'=>CONTEXT_COURSE);
3246     if ($addroleid) {
3247         $addrole = "OR r.id = :addroleid";
3248         $params['addroleid'] = $addroleid;
3249     } else {
3250         $addrole = "";
3251     }
3252     $sql = "SELECT r.id, r.name
3253               FROM {role} r
3254          LEFT JOIN {role_context_levels} rcl ON (rcl.roleid = r.id AND rcl.contextlevel = :contextlevel)
3255              WHERE rcl.id IS NOT NULL $addrole
3256           ORDER BY sortorder DESC";
3258     $roles = $DB->get_records_sql_menu($sql, $params);
3259     $roles = role_fix_names($roles, $context, ROLENAME_BOTH);
3261     return $roles;
3264 /**
3265  * Return context levels where this role is assignable.
3266  * @param integer $roleid the id of a role.
3267  * @return array list of the context levels at which this role may be assigned.
3268  */
3269 function get_role_contextlevels($roleid) {
3270     global $DB;
3271     return $DB->get_records_menu('role_context_levels', array('roleid' => $roleid),
3272             'contextlevel', 'id,contextlevel');
3275 /**
3276  * Return roles suitable for assignment at the specified context level.
3277  *
3278  * NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()
3279  *
3280  * @param integer $contextlevel a contextlevel.
3281  * @return array list of role ids that are assignable at this context level.
3282  */
3283 function get_roles_for_contextlevels($contextlevel) {
3284     global $DB;
3285     return $DB->get_records_menu('role_context_levels', array('contextlevel' => $contextlevel),
3286             '', 'id,roleid');
3289 /**
3290  * Returns default context levels where roles can be assigned.
3291  *
3292  * @param string $rolearchetype one of the role archetypes - that is, one of the keys
3293  *      from the array returned by get_role_archetypes();
3294  * @return array list of the context levels at which this type of role may be assigned by default.
3295  */
3296 function get_default_contextlevels($rolearchetype) {
3297     static $defaults = array(
3298         'manager'        => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT, CONTEXT_COURSE),
3299         'coursecreator'  => array(CONTEXT_SYSTEM, CONTEXT_COURSECAT),
3300         'editingteacher' => array(CONTEXT_COURSE, CONTEXT_MODULE),
3301         'teacher'        => array(CONTEXT_COURSE, CONTEXT_MODULE),
3302         'student'        => array(CONTEXT_COURSE, CONTEXT_MODULE),
3303         'guest'          => array(),
3304         'user'           => array(),
3305         'frontpage'      => array());
3307     if (isset($defaults[$rolearchetype])) {
3308         return $defaults[$rolearchetype];
3309     } else {
3310         return array();
3311     }
3314 /**
3315  * Set the context levels at which a particular role can be assigned.
3316  * Throws exceptions in case of error.
3317  *
3318  * @param integer $roleid the id of a role.
3319  * @param array $contextlevels the context levels at which this role should be assignable,
3320  *      duplicate levels are removed.
3321  * @return void
3322  */
3323 function set_role_contextlevels($roleid, array $contextlevels) {
3324     global $DB;
3325     $DB->delete_records('role_context_levels', array('roleid' => $roleid));
3326     $rcl = new stdClass();
3327     $rcl->roleid = $roleid;
3328     $contextlevels = array_unique($contextlevels);
3329     foreach ($contextlevels as $level) {
3330         $rcl->contextlevel = $level;
3331         $DB->insert_record('role_context_levels', $rcl, false, true);
3332     }
3335 /**
3336  * Who has this capability in this context?
3337  *
3338  * This can be a very expensive call - use sparingly and keep
3339  * the results if you are going to need them again soon.
3340  *
3341  * Note if $fields is empty this function attempts to get u.*
3342  * which can get rather large - and has a serious perf impact
3343  * on some DBs.
3344  *
3345  * @param context $context
3346  * @param string|array $capability - capability name(s)
3347  * @param string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
3348  * @param string $sort - the sort order. Default is lastaccess time.
3349  * @param mixed $limitfrom - number of records to skip (offset)
3350  * @param mixed $limitnum - number of records to fetch
3351  * @param string|array $groups - single group or array of groups - only return
3352  *               users who are in one of these group(s).
3353  * @param string|array $exceptions - list of users to exclude, comma separated or array
3354  * @param bool $doanything_ignored not used any more, admin accounts are never returned
3355  * @param bool $view_ignored - use get_enrolled_sql() instead
3356  * @param bool $useviewallgroups if $groups is set the return users who
3357  *               have capability both $capability and moodle/site:accessallgroups
3358  *               in this context, as well as users who have $capability and who are
3359  *               in $groups.
3360  * @return mixed
3361  */
3362 function get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',
3363                                  $groups = '', $exceptions = '', $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false) {
3364     global $CFG, $DB;
3366     $defaultuserroleid      = isset($CFG->defaultuserroleid) ? $CFG->defaultuserroleid : 0;
3367     $defaultfrontpageroleid = isset($CFG->defaultfrontpageroleid) ? $CFG->defaultfrontpageroleid : 0;
3369     $ctxids = trim($context->path, '/');
3370     $ctxids = str_replace('/', ',', $ctxids);
3372     // Context is the frontpage
3373     $iscoursepage = false; // coursepage other than fp
3374     $isfrontpage = false;
3375     if ($context->contextlevel == CONTEXT_COURSE) {
3376         if ($context->instanceid == SITEID) {
3377             $isfrontpage = true;
3378         } else {
3379             $iscoursepage = true;
3380         }
3381     }
3382     $isfrontpage = ($isfrontpage || is_inside_frontpage($context));
3384     $caps = (array)$capability;
3386     // construct list of context paths bottom-->top
3387     list($contextids, $paths) = get_context_info_list($context);
3389     // we need to find out all roles that have these capabilities either in definition or in overrides
3390     $defs = array();
3391     list($incontexts, $params) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED, 'con');
3392     list($incaps, $params2) = $DB->get_in_or_equal($caps, SQL_PARAMS_NAMED, 'cap');
3393     $params = array_merge($params, $params2);
3394     $sql = "SELECT rc.id, rc.roleid, rc.permission, rc.capability, ctx.path
3395               FROM {role_capabilities} rc
3396               JOIN {context} ctx on rc.contextid = ctx.id
3397              WHERE rc.contextid $incontexts AND rc.capability $incaps";
3399     $rcs = $DB->get_records_sql($sql, $params);
3400     foreach ($rcs as $rc) {
3401         $defs[$rc->capability][$rc->path][$rc->roleid] = $rc->permission;
3402     }
3404     // go through the permissions bottom-->top direction to evaluate the current permission,
3405     // first one wins (prohibit is an exception that always wins)
3406     $access = array();
3407     foreach ($caps as $cap) {
3408         foreach ($paths as $path) {
3409             if (empty($defs[$cap][$path])) {
3410                 continue;
3411             }
3412             foreach($defs[$cap][$path] as $roleid => $perm) {
3413                 if ($perm == CAP_PROHIBIT) {
3414                     $access[$cap][$roleid] = CAP_PROHIBIT;
3415                     continue;
3416                 }
3417                 if (!isset($access[$cap][$roleid])) {
3418                     $access[$cap][$roleid] = (int)$perm;
3419                 }
3420             }
3421         }
3422     }
3424     // make lists of roles that are needed and prohibited in this context
3425     $needed = array(); // one of these is enough
3426     $prohibited = array(); // must not have any of these
3427     foreach ($caps as $cap) {
3428         if (empty($access[$cap])) {
3429             continue;
3430         }
3431         foreach ($access[$cap] as $roleid => $perm) {
3432             if ($perm == CAP_PROHIBIT) {
3433                 unset($needed[$cap][$roleid]);
3434                 $prohibited[$cap][$roleid] = true;
3435             } else if ($perm == CAP_ALLOW and empty($prohibited[$cap][$roleid])) {
3436                 $needed[$cap][$roleid] = true;
3437             }
3438         }
3439         if (empty($needed[$cap]) or !empty($prohibited[$cap][$defaultuserroleid])) {
3440             // easy, nobody has the permission
3441             unset($needed[$cap]);
3442             unset($prohibited[$cap]);
3443         } else if ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid])) {
3444             // everybody is disqualified on the frontapge
3445             unset($needed[$cap]);
3446             unset($prohibited[$cap]);
3447         }
3448         if (empty($prohibited[$cap])) {
3449             unset($prohibited[$cap]);
3450         }
3451     }
3453     if (empty($needed)) {
3454         // there can not be anybody if no roles match this request
3455         return array();
3456     }
3458     if (empty($prohibited)) {
3459         // we can compact the needed roles
3460         $n = array();
3461         foreach ($needed as $cap) {
3462             foreach ($cap as $roleid=>$unused) {
3463                 $n[$roleid] = true;
3464             }
3465         }
3466         $needed = array('any'=>$n);
3467         unset($n);
3468     }
3470     /// ***** Set up default fields ******
3471     if (empty($fields)) {
3472         if ($iscoursepage) {
3473             $fields = 'u.*, ul.timeaccess AS lastaccess';
3474         } else {
3475             $fields = 'u.*';
3476         }
3477     } else {
3478         if (debugging('', DEBUG_DEVELOPER) && strpos($fields, 'u.*') === false && strpos($fields, 'u.id') === false) {
3479             debugging('u.id must be included in the list of fields passed to get_users_by_capability().', DEBUG_DEVELOPER);
3480         }
3481     }
3483     /// Set up default sort
3484     if (empty($sort)) { // default to course lastaccess or just lastaccess
3485         if ($iscoursepage) {
3486             $sort = 'ul.timeaccess';
3487         } else {
3488             $sort = 'u.lastaccess';
3489         }
3490     }
3492     // Prepare query clauses
3493     $wherecond = array();
3494     $params    = array();
3495     $joins     = array();
3497     // User lastaccess JOIN
3498     if ((strpos($sort, 'ul.timeaccess') === false) and (strpos($fields, 'ul.timeaccess') === false)) {
3499          // user_lastaccess is not required MDL-13810
3500     } else {
3501         if ($iscoursepage) {
3502             $joins[] = "LEFT OUTER JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = {$context->instanceid})";
3503         } else {
3504             throw new coding_exception('Invalid sort in get_users_by_capability(), ul.timeaccess allowed only for course contexts.');
3505         }
3506     }
3508     /// We never return deleted users or guest account.
3509     $wherecond[] = "u.deleted = 0 AND u.id <> :guestid";
3510     $params['guestid'] = $CFG->siteguest;
3512     /// Groups
3513     if ($groups) {
3514         $groups = (array)$groups;
3515         list($grouptest, $grpparams) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grp');
3516         $grouptest = "u.id IN (SELECT userid FROM {groups_members} gm WHERE gm.groupid $grouptest)";
3517         $params = array_merge($params, $grpparams);
3519         if ($useviewallgroups) {
3520             $viewallgroupsusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id, u.id', '', '', '', '', $exceptions);
3521             if (!empty($viewallgroupsusers)) {
3522                 $wherecond[] =  "($grouptest OR u.id IN (" . implode(',', array_keys($viewallgroupsusers)) . '))';
3523             } else {
3524                 $wherecond[] =  "($grouptest)";
3525             }
3526         } else {
3527             $wherecond[] =  "($grouptest)";
3528         }
3529     }
3531     /// User exceptions
3532     if (!empty($exceptions)) {
3533         $exceptions = (array)$exceptions;
3534         list($exsql, $exparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'exc', false);
3535         $params = array_merge($params, $exparams);
3536         $wherecond[] = "u.id $exsql";
3537     }
3539     // now add the needed and prohibited roles conditions as joins
3540     if (!empty($needed['any'])) {
3541         // simple case - there are no prohibits involved
3542         if (!empty($needed['any'][$defaultuserroleid]) or ($isfrontpage and !empty($needed['any'][$defaultfrontpageroleid]))) {
3543             // everybody
3544         } else {
3545             $joins[] = "JOIN (SELECT DISTINCT userid
3546                                 FROM {role_assignments}
3547                                WHERE contextid IN ($ctxids)
3548                                      AND roleid IN (".implode(',', array_keys($needed['any'])) .")
3549                              ) ra ON ra.userid = u.id";
3550         }
3551     } else {
3552         $unions = array();
3553         $everybody = false;
3554         foreach ($needed as $cap=>$unused) {
3555             if (empty($prohibited[$cap])) {
3556                 if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3557                     $everybody = true;
3558                     break;
3559                 } else {
3560                     $unions[] = "SELECT userid
3561                                    FROM {role_assignments}
3562                                   WHERE contextid IN ($ctxids)
3563                                         AND roleid IN (".implode(',', array_keys($needed[$cap])) .")";
3564                 }
3565             } else {
3566                 if (!empty($prohibited[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($prohibited[$cap][$defaultfrontpageroleid]))) {
3567                     // nobody can have this cap because it is prevented in default roles
3568                     continue;
3570                 } else if (!empty($needed[$cap][$defaultuserroleid]) or ($isfrontpage and !empty($needed[$cap][$defaultfrontpageroleid]))) {
3571                     // everybody except the prohibitted - hiding does not matter
3572                     $unions[] = "SELECT id AS userid
3573                                    FROM {user}
3574                                   WHERE id NOT IN (SELECT userid
3575                                                      FROM {role_assignments}
3576                                                     WHERE contextid IN ($ctxids)
3577                                                           AND roleid IN (".implode(',', array_keys($prohibited[$cap])) ."))";
3579                 } else {
3580                     $unions[] = "SELECT userid
3581                                    FROM {role_assignments}
3582                                   WHERE contextid IN ($ctxids)
3583                                         AND roleid IN (".implode(',', array_keys($needed[$cap])) .")
3584                                         AND roleid NOT IN (".implode(',', array_keys($prohibited[$cap])) .")";
3585                 }
3586             }
3587         }
3588         if (!$everybody) {
3589             if ($unions) {
3590                 $joins[] = "JOIN (SELECT DISTINCT userid FROM ( ".implode(' UNION ', $unions)." ) us) ra ON ra.userid = u.id";
3591             } else {
3592                 // only prohibits found - nobody can be matched
3593                 $wherecond[] = "1 = 2";
3594             }
3595         }
3596     }
3598     // Collect WHERE conditions and needed joins
3599     $where = implode(' AND ', $wherecond);
3600     if ($where !== '') {
3601         $where = 'WHERE ' . $where;
3602     }
3603     $joins = implode("\n", $joins);
3605     /// Ok, let's get the users!
3606     $sql = "SELECT $fields
3607               FROM {user} u
3608             $joins
3609             $where
3610           ORDER BY $sort";
3612     return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
3615 /**
3616  * Re-sort a users array based on a sorting policy
3617  *
3618  * Will re-sort a $users results array (from get_users_by_capability(), usually)
3619  * based on a sorting policy. This is to support the odd practice of
3620  * sorting teachers by 'authority', where authority was "lowest id of the role
3621  * assignment".
3622  *
3623  * Will execute 1 database query. Only suitable for small numbers of users, as it
3624  * uses an u.id IN() clause.
3625  *
3626  * Notes about the sorting criteria.
3627  *
3628  * As a default, we cannot rely on role.sortorder because then
3629  * admins/coursecreators will always win. That is why the sane
3630  * rule "is locality matters most", with sortorder as 2nd
3631  * consideration.
3632  *
3633  * If you want role.sortorder, use the 'sortorder' policy, and
3634  * name explicitly what roles you want to cover. It's probably
3635  * a good idea to see what roles have the capabilities you want
3636  * (array_diff() them against roiles that have 'can-do-anything'
3637  * to weed out admin-ish roles. Or fetch a list of roles from
3638  * variables like $CFG->coursecontact .
3639  *
3640  * @param array $users Users array, keyed on userid
3641  * @param context $context
3642  * @param array $roles ids of the roles to include, optional
3643  * @param string $sortpolicy defaults to locality, more about
3644  * @return array sorted copy of the array
3645  */
3646 function sort_by_roleassignment_authority($users, context $context, $roles = array(), $sortpolicy = 'locality') {
3647     global $DB;
3649     $userswhere = ' ra.userid IN (' . implode(',',array_keys($users)) . ')';
3650     $contextwhere = 'AND ra.contextid IN ('.str_replace('/', ',',substr($context->path, 1)).')';
3651     if (empty($roles)) {
3652         $roleswhere = '';
3653     } else {
3654         $role