Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.
/lib/ -> accesslib.php (source)

Differences Between: [Versions 310 and 403] [Versions 311 and 403] [Versions 39 and 403] [Versions 400 and 403] [Versions 401 and 403] [Versions 402 and 403]

This file contains functions for managing user access <b>Public API vs internals</b>

Copyright: 1999 onwards Martin Dougiamas http://dougiamas.com
License: http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
File Size: 5179 lines (189 kb)
Included or required:0 times
Referenced: 0 times
Includes or requires: 0 files

Defines 112 functions

  accesslib_clear_all_caches_for_unit_testing()
  accesslib_clear_all_caches()
  accesslib_reset_role_cache()
  accesslib_clear_role_cache()
  get_role_access()
  get_role_definitions()
  get_role_definitions_uncached()
  get_guest_role()
  has_capability()
  has_any_capability()
  has_all_capabilities()
  guess_if_creator_will_have_course_capability()
  is_siteadmin()
  has_coursecontact_role()
  has_capability_in_accessdata()
  require_capability()
  require_all_capabilities()
  get_user_roles_sitewide_accessdata()
  get_empty_accessdata()
  get_user_accessdata()
  load_all_capabilities()
  reload_all_capabilities()
  load_temp_course_role()
  remove_temp_course_roles()
  get_role_archetypes()
  assign_legacy_capabilities()
  is_safe_capability()
  get_local_override()
  get_context_info_array()
  create_role()
  delete_role()
  assign_capability()
  unassign_capability()
  get_roles_with_capability()
  role_assign()
  role_unassign()
  role_unassign_all()
  mark_user_dirty()
  isloggedin()
  isguestuser()
  is_guest()
  is_viewing()
  can_access_course()
  load_capability_def()
  get_cached_capabilities()
  get_default_capabilities()
  get_default_role_archetype_allows()
  reset_role_capabilities()
  update_capabilities()
  capabilities_cleanup()
  get_all_risks()
  get_capability_docs_link()
  role_context_capabilities()
  get_context_info_list()
  is_inside_frontpage()
  get_capability_info()
  get_deprecated_capability_info()
  get_all_capabilities()
  get_capability_string()
  get_component_string()
  get_profile_roles()
  get_roles_used_in_context()
  get_user_roles_in_course()
  user_can_assign()
  get_all_roles()
  get_archetype_roles()
  get_users_roles()
  get_user_roles()
  get_user_roles_with_special()
  core_role_set_override_allowed()
  core_role_set_assign_allowed()
  core_role_set_switch_allowed()
  core_role_set_view_allowed()
  get_assignable_roles()
  get_switchable_roles()
  get_viewable_roles()
  get_overridable_roles()
  get_default_enrol_roles()
  get_role_contextlevels()
  get_roles_for_contextlevels()
  get_default_contextlevels()
  set_role_contextlevels()
  get_with_capability_join()
  get_users_by_capability()
  sort_by_roleassignment_authority()
  get_role_users()
  count_role_users()
  get_user_capability_contexts()
  get_user_capability_course()
  role_switch()
  is_role_switched()
  get_roles_with_override_on_context()
  get_capabilities_from_role_on_context()
  get_users_from_role_on_context()
  user_has_role_assignment()
  role_get_name()
  role_get_description()
  role_get_names()
  role_fix_names()
  component_level_changed()
  fix_role_sortorder()
  switch_roles()
  role_cap_duplicate()
  get_roles_with_cap_in_context()
  get_roles_with_caps_in_context()
  get_role_names_with_caps_in_context()
  prohibit_is_removable()
  role_change_permission()
  get_sorted_contexts()
  extract_suspended_users()
  get_suspended_userids()
  get_with_capability_sql()

Functions that are not part of a class:

accesslib_clear_all_caches_for_unit_testing()   X-Ref
Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS

This method should ONLY BE USED BY UNIT TESTS. It clears all of
accesslib's private caches. You need to do this before setting up test data,
and also at the end of the tests.

return: void

accesslib_clear_all_caches($resetcontexts)   X-Ref
Clears accesslib's private caches. ONLY BE USED FROM THIS LIBRARY FILE!

This reset does not touch global $USER.

param: bool $resetcontexts
return: void

accesslib_reset_role_cache()   X-Ref
Full reset of accesslib's private role cache. ONLY TO BE USED FROM THIS LIBRARY FILE!

This reset does not touch global $USER.

Note: Only use this when the roles that need a refresh are unknown.

return: void

accesslib_clear_role_cache($roles)   X-Ref
Clears accesslib's private cache of a specific role or roles. ONLY BE USED FROM THIS LIBRARY FILE!

This reset does not touch global $USER.

param: int|array $roles
return: void

get_role_access($roleid)   X-Ref
Role is assigned at system context.

param: int $roleid
return: array

get_role_definitions(array $roleids)   X-Ref
Fetch raw "site wide" role definitions.
Even MUC static acceleration cache appears a bit slow for this.
Important as can be hit hundreds of times per page.

param: array $roleids List of role ids to fetch definitions for.
return: array Complete definition for each requested role.

get_role_definitions_uncached(array $roleids)   X-Ref
Query raw "site wide" role definitions.

param: array $roleids List of role ids to fetch definitions for.
return: array Complete definition for each requested role.

get_guest_role()   X-Ref
Get the default guest role, this is used for guest account,
search engine spiders, etc.

return: stdClass role record

has_capability($capability, context $context, $user = null, $doanything = true)   X-Ref
Check whether a user has a particular capability in a given context.

For example:
$context = context_module::instance($cm->id);
has_capability('mod/forum:replypost', $context)

By default checks the capabilities of the current user, but you can pass a
different userid. By default will return true for admin users, but you can override that with the fourth argument.

Guest and not-logged-in users can never get any dangerous capability - that is any write capability
or capabilities with XSS, config or data loss risks.

param: string $capability the name of the capability to check. For example mod/forum:view
param: context $context the context to check the capability in. You normally get this with instance method of a context class.
param: integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
param: boolean $doanything If false, ignores effect of admin role assignment
return: boolean true if the user has this capability. Otherwise false.

has_any_capability(array $capabilities, context $context, $user = null, $doanything = true)   X-Ref
Check if the user has any one of several capabilities from a list.

This is just a utility method that calls has_capability in a loop. Try to put
the capabilities that most users are likely to have first in the list for best
performance.

param: array $capabilities an array of capability names.
param: context $context the context to check the capability in. You normally get this with instance method of a context class.
param: integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
param: boolean $doanything If false, ignore effect of admin role assignment
return: boolean true if the user has any of these capabilities. Otherwise false.

has_all_capabilities(array $capabilities, context $context, $user = null, $doanything = true)   X-Ref
Check if the user has all the capabilities in a list.

This is just a utility method that calls has_capability in a loop. Try to put
the capabilities that fewest users are likely to have first in the list for best
performance.

param: array $capabilities an array of capability names.
param: context $context the context to check the capability in. You normally get this with instance method of a context class.
param: integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
param: boolean $doanything If false, ignore effect of admin role assignment
return: boolean true if the user has all of these capabilities. Otherwise false.

guess_if_creator_will_have_course_capability($capability, context $context, $user = null)   X-Ref
Is course creator going to have capability in a new course?

This is intended to be used in enrolment plugins before or during course creation,
do not use after the course is fully created.

param: string $capability the name of the capability to check.
param: context $context course or category context where is course going to be created
param: integer|stdClass $user A user id or object. By default (null) checks the permissions of the current user.
return: boolean true if the user will have this capability.

is_siteadmin($user_or_id = null)   X-Ref
Check if the user is an admin at the site level.

Please note that use of proper capabilities is always encouraged,
this function is supposed to be used from core or for temporary hacks.

param: int|stdClass  $user_or_id user id or user object
return: bool true if user is one of the administrators, false otherwise

has_coursecontact_role($userid)   X-Ref
Returns true if user has at least one role assign
of 'coursecontact' role (is potentially listed in some course descriptions).

param: int $userid
return: bool

has_capability_in_accessdata($capability, context $context, array &$accessdata)   X-Ref
Does the user have a capability to do something?

Walk the accessdata array and return true/false.
Deals with prohibits, role switching, aggregating
capabilities, etc.

The main feature of here is being FAST and with no
side effects.

Notes:

Switch Role merges with default role
------------------------------------
If you are a teacher in course X, you have at least
teacher-in-X + defaultloggedinuser-sitewide. So in the
course you'll have techer+defaultloggedinuser.
We try to mimic that in switchrole.

Permission evaluation
---------------------
Originally there was an extremely complicated way
to determine the user access that dealt with
"locality" or role assignments and role overrides.
Now we simply evaluate access for each role separately
and then verify if user has at least one role with allow
and at the same time no role with prohibit.

param: string $capability
param: context $context
param: array $accessdata
return: bool

require_capability($capability, context $context, $userid = null, $doanything = true,$errormessage = 'nopermissions', $stringfile = '')   X-Ref
A convenience function that tests has_capability, and displays an error if
the user does not have that capability.

NOTE before Moodle 2.0, this function attempted to make an appropriate
require_login call before checking the capability. This is no longer the case.
You must call require_login (or one of its variants) if you want to check the
user is logged in, before you call this function.

param: string $capability the name of the capability to check. For example mod/forum:view
param: context $context the context to check the capability in. You normally get this with context_xxxx::instance().
param: int $userid A user id. By default (null) checks the permissions of the current user.
param: bool $doanything If false, ignore effect of admin role assignment
param: string $errormessage The error string to to user. Defaults to 'nopermissions'.
param: string $stringfile The language file to load the error string from. Defaults to 'error'.
return: void terminates with an error if the user does not have the given capability.

require_all_capabilities(array $capabilities, context $context, $userid = null, $doanything = true,$errormessage = 'nopermissions', $stringfile = '')   X-Ref
A convenience function that tests has_capability for a list of capabilities, and displays an error if
the user does not have that capability.

This is just a utility method that calls has_capability in a loop. Try to put
the capabilities that fewest users are likely to have first in the list for best
performance.

param: array $capabilities an array of capability names.
param: context $context the context to check the capability in. You normally get this with context_xxxx::instance().
param: int $userid A user id. By default (null) checks the permissions of the current user.
param: bool $doanything If false, ignore effect of admin role assignment
param: string $errormessage The error string to to user. Defaults to 'nopermissions'.
param: string $stringfile The language file to load the error string from. Defaults to 'error'.
return: void terminates with an error if the user does not have the given capability.

get_user_roles_sitewide_accessdata($userid)   X-Ref
Return a nested array showing all role assignments for the user.
[ra] => [contextpath][roleid] = roleid

param: int $userid - the id of the user
return: array access info array

get_empty_accessdata()   X-Ref
Returns empty accessdata structure.

return: array empt accessdata

get_user_accessdata($userid, $preloadonly=false)   X-Ref
Get accessdata for a given user.

param: int $userid
param: bool $preloadonly true means do not return access array
return: array accessdata

load_all_capabilities()   X-Ref
A convenience function to completely load all the capabilities
for the current user. It is called from has_capability() and functions change permissions.

Call it only _after_ you've setup $USER and called check_enrolment_plugins();
return: void

reload_all_capabilities()   X-Ref
A convenience function to completely reload all the capabilities
for the current user when roles have been updated in a relevant
context -- but PRESERVING switchroles and loginas.
This function resets all accesslib and context caches.

That is - completely transparent to the user.

Note: reloads $USER->access completely.

return: void

load_temp_course_role(context_course $coursecontext, $roleid)   X-Ref
Adds a temp role to current USER->access array.

Useful for the "temporary guest" access we grant to logged-in users.
This is useful for enrol plugins only.

param: context_course $coursecontext
param: int $roleid
return: void

remove_temp_course_roles(context_course $coursecontext)   X-Ref
Removes any extra guest roles from current USER->access array.
This is useful for enrol plugins only.

param: context_course $coursecontext
return: void

get_role_archetypes()   X-Ref
Returns array of all role archetypes.

return: array

assign_legacy_capabilities($capability, $legacyperms)   X-Ref
Assign the defaults found in this capability definition to roles that have
the corresponding legacy capabilities assigned to them.

param: string $capability
param: array $legacyperms an array in the format (example):
return: boolean success or failure.

is_safe_capability($capability)   X-Ref
Verify capability risks.

param: stdClass $capability a capability - a row from the capabilities table.
return: boolean whether this capability is safe - that is, whether people with the

get_local_override($roleid, $contextid, $capability)   X-Ref
Get the local override (if any) for a given capability in a role in a context

param: int $roleid
param: int $contextid
param: string $capability
return: stdClass local capability override

get_context_info_array($contextid)   X-Ref
Returns context instance plus related course and cm instances

param: int $contextid
return: array of ($context, $course, $cm)

create_role($name, $shortname, $description, $archetype = '')   X-Ref
Function that creates a role

param: string $name role name
param: string $shortname role short name
param: string $description role description
param: string $archetype
return: int id or dml_exception

delete_role($roleid)   X-Ref
Function that deletes a role and cleanups up after it

param: int $roleid id of role to delete
return: bool always true

assign_capability($capability, $permission, $roleid, $contextid, $overwrite = false, array $performancehints = [])   X-Ref
Function to write context specific overrides, or default capabilities.

The $performancehints array can currently contain two values intended to make this faster when
this function is being called in a loop, if you have already checked certain details:
'contextexists' - if we already know the contextid exists in context table
ASSIGN_HINT_NO_EXISTING - if we already know there is no entry in role_capabilities matching
contextid, roleid, and capability

param: string $capability string name
param: int $permission CAP_ constants
param: int $roleid role id
param: int|context $contextid context id
param: bool $overwrite
param: string[] $performancehints Performance hints - leave blank unless needed
return: bool always true or exception

unassign_capability($capability, $roleid, $contextid = null)   X-Ref
Unassign a capability from a role.

param: string $capability the name of the capability
param: int $roleid the role id
param: int|context $contextid null means all contexts
return: boolean true or exception

get_roles_with_capability($capability, $permission = null, $context = null)   X-Ref
Get the roles that have a given capability assigned to it

This function does not resolve the actual permission of the capability.
It just checks for permissions and overrides.
Use get_roles_with_cap_in_context() if resolution is required.

param: string $capability capability name (string)
param: string $permission optional, the permission defined for this capability
param: context|null $context null means any
return: array of role records

role_assign($roleid, $userid, $contextid, $component = '', $itemid = 0, $timemodified = '')   X-Ref
This function makes a role-assignment (a role for a user in a particular context)

param: int $roleid the role of the id
param: int $userid userid
param: int|context $contextid id of the context
param: string $component example 'enrol_ldap', defaults to '' which means manual assignment,
param: int $itemid id of enrolment/auth plugin
param: string $timemodified defaults to current time
return: int new/existing id of the assignment

role_unassign($roleid, $userid, $contextid, $component = '', $itemid = 0)   X-Ref
Removes one role assignment

param: int $roleid
param: int  $userid
param: int  $contextid
param: string $component
param: int  $itemid
return: void

role_unassign_all(array $params, $subcontexts = false, $includemanual = false)   X-Ref
Removes multiple role assignments, parameters may contain:
'roleid', 'userid', 'contextid', 'component', 'enrolid'.

param: array $params role assignment parameters
param: bool $subcontexts unassign in subcontexts too
param: bool $includemanual include manual role assignments too
return: void

mark_user_dirty($userid)   X-Ref
Mark a user as dirty (with timestamp) so as to force reloading of the user session.

param: int $userid
return: void

isloggedin()   X-Ref
Determines if a user is currently logged in

return: bool

isguestuser($user = null)   X-Ref
Determines if a user is logged in as real guest user with username 'guest'.

param: int|object $user mixed user object or id, $USER if not specified
return: bool true if user is the real guest user, false if not logged in or other user

is_guest(context $context, $user = null)   X-Ref
Does user have a (temporary or real) guest access to course?

param: context $context
param: stdClass|int $user
return: bool

is_viewing(context $context, $user = null, $withcapability = '')   X-Ref
Returns true if the user has moodle/course:view capability in the course,
this is intended for admins, managers (aka small admins), inspectors, etc.

param: context $context
param: int|stdClass $user if null $USER is used
param: string $withcapability extra capability name
return: bool

can_access_course(stdClass $course, $user = null, $withcapability = '', $onlyactive = false)   X-Ref
Returns true if the user is able to access the course.

This function is in no way, shape, or form a substitute for require_login.
It should only be used in circumstances where it is not possible to call require_login
such as the navigation.

This function checks many of the methods of access to a course such as the view
capability, enrollments, and guest access. It also makes use of the cache
generated by require_login for guest access.

The flags within the $USER object that are used here should NEVER be used outside
of this function can_access_course and require_login. Doing so WILL break future
versions.

param: stdClass $course record
param: stdClass|int|null $user user record or id, current user if null
param: string $withcapability Check for this capability as well.
param: bool $onlyactive consider only active enrolments in enabled plugins and time restrictions
return: boolean Returns true if the user is able to access the course

load_capability_def($component)   X-Ref
Loads the capability definitions for the component (from file).

Loads the capability definitions for the component (from file). If no
capabilities are defined for the component, we simply return an empty array.

param: string $component full plugin name, examples: 'moodle', 'mod_forum'
return: array array of capabilities

get_cached_capabilities($component = 'moodle')   X-Ref
Gets the capabilities that have been cached in the database for this component.

param: string $component - examples: 'moodle', 'mod_forum'
return: array array of capabilities

get_default_capabilities($archetype)   X-Ref
Returns default capabilities for given role archetype.

param: string $archetype role archetype
return: array

get_default_role_archetype_allows($type, $archetype)   X-Ref
Return default roles that can be assigned, overridden or switched
by give role archetype.

param: string $type  assign|override|switch|view
param: string $archetype
return: array of role ids

reset_role_capabilities($roleid)   X-Ref
Reset role capabilities to default according to selected role archetype.
If no archetype selected, removes all capabilities.

This applies to capabilities that are assigned to the role (that you could
edit in the 'define roles' interface), and not to any capability overrides
in different locations.

param: int $roleid ID of role to reset capabilities for

update_capabilities($component = 'moodle')   X-Ref
Updates the capabilities table with the component capability definitions.
If no parameters are given, the function updates the core moodle
capabilities.

Note that the absence of the db/access.php capabilities definition file
will cause any stored capabilities for the component to be removed from
the database.

param: string $component examples: 'moodle', 'mod_forum', 'block_activity_results'
return: boolean true if success, exception in case of any problems

capabilities_cleanup($component, $newcapdef = null)   X-Ref
Deletes cached capabilities that are no longer needed by the component.
Also unassigns these capabilities from any roles that have them.
NOTE: this function is called from lib/db/upgrade.php

param: string $component examples: 'moodle', 'mod_forum', 'block_activity_results'
param: array $newcapdef array of the new capability definitions that will be
return: int number of deprecated capabilities that have been removed

get_all_risks()   X-Ref
Returns an array of all the known types of risk
The array keys can be used, for example as CSS class names, or in calls to
print_risk_icon. The values are the corresponding RISK_ constants.

return: array all the known types of risk.

get_capability_docs_link($capability)   X-Ref
Return a link to moodle docs for a given capability name

param: stdClass $capability a capability - a row from the mdl_capabilities table.
return: string the human-readable capability name as a link to Moodle Docs.

role_context_capabilities($roleid, context $context, $cap = '')   X-Ref
This function pulls out all the resolved capabilities (overrides and
defaults) of a role used in capability overrides in contexts at a given
context.

param: int $roleid
param: context $context
param: string $cap capability, optional, defaults to ''
return: array Array of capabilities

get_context_info_list(context $context)   X-Ref
Constructs array with contextids as first parameter and context paths,
in both cases bottom top including self.

param: context $context
return: array

is_inside_frontpage(context $context)   X-Ref
Check if context is the front page context or a context inside it

Returns true if this context is the front page context, or a context inside it,
otherwise false.

param: context $context a context object.
return: bool

get_capability_info($capabilityname)   X-Ref
Returns capability information (cached)

param: string $capabilityname
return: stdClass or null if capability not found

get_deprecated_capability_info($capabilityname)   X-Ref
Returns deprecation info for this particular capabilty (cached)

Do not use this function except in the get_capability_info

param: string $capabilityname
return: stdClass|null with deprecation message and potential replacement if not null

get_all_capabilities()   X-Ref
Returns all capabilitiy records, preferably from MUC and not database.

return: array All capability records indexed by capability name

get_capability_string($capabilityname)   X-Ref
Returns the human-readable, translated version of the capability.
Basically a big switch statement.

param: string $capabilityname e.g. mod/choice:readresponses
return: string

get_component_string($component, $contextlevel)   X-Ref
This gets the mod/block/course/core etc strings.

param: string $component
param: int $contextlevel
return: string|bool String is success, false if failed

get_profile_roles(context $context)   X-Ref
Gets the list of roles assigned to this context and up (parents)
from the aggregation of:
a) the list of roles that are visible on user profile page and participants page (profileroles setting) and;
b) if applicable, those roles that are assigned in the context.

param: context $context
return: array

get_roles_used_in_context(context $context, $includeparents = true)   X-Ref
Gets the list of roles assigned to this context and up (parents)

param: context $context
param: boolean $includeparents, false means without parents.
return: array

get_user_roles_in_course($userid, $courseid)   X-Ref
This function is used to print roles column in user profile page.
It is using the CFG->profileroles to limit the list to only interesting roles.
(The permission tab has full details of user role assignments.)

param: int $userid
param: int $courseid
return: string

user_can_assign(context $context, $targetroleid)   X-Ref
Checks if a user can assign users to a particular role in this context

param: context $context
param: int $targetroleid - the id of the role you want to assign users to
return: boolean

get_all_roles(context $context = null)   X-Ref
Returns all site roles in correct sort order.

Note: this method does not localise role names or descriptions,
use role_get_names() if you need role names.

param: context $context optional context for course role name aliases
return: array of role records with optional coursealias property

get_archetype_roles($archetype)   X-Ref
Returns roles of a specified archetype

param: string $archetype
return: array of full role records

get_users_roles(context $context, $userids = [], $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC')   X-Ref
Gets all the user roles assigned in this context, or higher contexts for a list of users.

If you try using the combination $userids = [], $checkparentcontexts = true then this is likely
to cause an out-of-memory error on large Moodle sites, so this combination is deprecated and
outputs a warning, even though it is the default.

param: context $context
param: array $userids. An empty list means fetch all role assignments for the context.
param: bool $checkparentcontexts defaults to true
param: string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
return: array

get_user_roles(context $context, $userid = 0, $checkparentcontexts = true, $order = 'c.contextlevel DESC, r.sortorder ASC')   X-Ref
Gets all the user roles assigned in this context, or higher contexts
this is mainly used when checking if a user can assign a role, or overriding a role
i.e. we need to know what this user holds, in order to verify against allow_assign and
allow_override tables

param: context $context
param: int $userid
param: bool $checkparentcontexts defaults to true
param: string $order defaults to 'c.contextlevel DESC, r.sortorder ASC'
return: array

get_user_roles_with_special(context $context, $userid = 0)   X-Ref
Like get_user_roles, but adds in the authenticated user role, and the front
page roles, if applicable.

param: context $context the context.
param: int $userid optional. Defaults to $USER->id
return: array of objects with fields ->userid, ->contextid and ->roleid.

core_role_set_override_allowed($fromroleid, $targetroleid)   X-Ref
Creates a record in the role_allow_override table

param: int $fromroleid source roleid
param: int $targetroleid target roleid
return: void

core_role_set_assign_allowed($fromroleid, $targetroleid)   X-Ref
Creates a record in the role_allow_assign table

param: int $fromroleid source roleid
param: int $targetroleid target roleid
return: void

core_role_set_switch_allowed($fromroleid, $targetroleid)   X-Ref
Creates a record in the role_allow_switch table

param: int $fromroleid source roleid
param: int $targetroleid target roleid
return: void

core_role_set_view_allowed($fromroleid, $targetroleid)   X-Ref
Creates a record in the role_allow_view table

param: int $fromroleid source roleid
param: int $targetroleid target roleid
return: void

get_assignable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withusercounts = false, $user = null)   X-Ref
Gets a list of roles that this user can assign in this context

param: context $context the context.
param: int $rolenamedisplay the type of role name to display. One of the
param: bool $withusercounts if true, count the number of users with each role.
param: integer|object $user A user id or object. By default (null) checks the permissions of the current user.
return: array if $withusercounts is false, then an array $roleid => $rolename.

get_switchable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS)   X-Ref
Gets a list of roles that this user can switch to in a context

Gets a list of roles that this user can switch to in a context, for the switchrole menu.
This function just process the contents of the role_allow_switch table. You also need to
test the moodle/role:switchroles to see if the user is allowed to switch in the first place.

param: context $context a context.
param: int $rolenamedisplay the type of role name to display. One of the
return: array an array $roleid => $rolename.

get_viewable_roles(context $context, $userid = null, $rolenamedisplay = ROLENAME_ALIAS)   X-Ref
Gets a list of roles that this user can view in a context

param: context $context a context.
param: int $userid id of user.
param: int $rolenamedisplay the type of role name to display. One of the
return: array an array $roleid => $rolename.

get_overridable_roles(context $context, $rolenamedisplay = ROLENAME_ALIAS, $withcounts = false)   X-Ref
Gets a list of roles that this user can override in this context.

param: context $context the context.
param: int $rolenamedisplay the type of role name to display. One of the
param: bool $withcounts if true, count the number of overrides that are set for each role.
return: array if $withcounts is false, then an array $roleid => $rolename.

get_default_enrol_roles(context $context, $addroleid = null)   X-Ref
Create a role menu suitable for default role selection in enrol plugins.

param: context $context
param: int $addroleid current or default role - always added to list
return: array roleid=>localised role name

get_role_contextlevels($roleid)   X-Ref
Return context levels where this role is assignable.

param: integer $roleid the id of a role.
return: array list of the context levels at which this role may be assigned.

get_roles_for_contextlevels($contextlevel)   X-Ref
Return roles suitable for assignment at the specified context level.

NOTE: this function name looks like a typo, should be probably get_roles_for_contextlevel()

param: integer $contextlevel a contextlevel.
return: array list of role ids that are assignable at this context level.

get_default_contextlevels($rolearchetype)   X-Ref
Returns default context levels where roles can be assigned.

param: string $rolearchetype one of the role archetypes - that is, one of the keys
return: array list of the context levels at which this type of role may be assigned by default.

set_role_contextlevels($roleid, array $contextlevels)   X-Ref
Set the context levels at which a particular role can be assigned.
Throws exceptions in case of error.

param: integer $roleid the id of a role.
param: array $contextlevels the context levels at which this role should be assignable,
return: void

get_with_capability_join(context $context, $capability, $useridcolumn)   X-Ref
Gets sql joins for finding users with capability in the given context.

param: context $context Context for the join.
param: string|array $capability Capability name or array of names.
param: string $useridcolumn e.g. 'u.id'.
return: \core\dml\sql_join Contains joins, wheres, params.

get_users_by_capability(context $context, $capability, $fields = '', $sort = '', $limitfrom = '', $limitnum = '',$groups = '', $exceptions = '', $notuseddoanything = null, $notusedview = null, $useviewallgroups = false)   X-Ref
Who has this capability in this context?

This can be a very expensive call - use sparingly and keep
the results if you are going to need them again soon.

Note if $fields is empty this function attempts to get u.*
which can get rather large - and has a serious perf impact
on some DBs.

param: context $context
param: string|array $capability - capability name(s)
param: string $fields - fields to be pulled. The user table is aliased to 'u'. u.id MUST be included.
param: string $sort - the sort order. Default is lastaccess time.
param: mixed $limitfrom - number of records to skip (offset)
param: mixed $limitnum - number of records to fetch
param: string|array $groups - single group or array of groups - only return
param: string|array $exceptions - list of users to exclude, comma separated or array
param: bool $notuseddoanything not used any more, admin accounts are never returned
param: bool $notusedview - use get_enrolled_sql() instead
param: bool $useviewallgroups if $groups is set the return users who
return: array of user records

sort_by_roleassignment_authority($users, context $context, $roles = array()   X-Ref
Re-sort a users array based on a sorting policy

Will re-sort a $users results array (from get_users_by_capability(), usually)
based on a sorting policy. This is to support the odd practice of
sorting teachers by 'authority', where authority was "lowest id of the role
assignment".

Will execute 1 database query. Only suitable for small numbers of users, as it
uses an u.id IN() clause.

Notes about the sorting criteria.

As a default, we cannot rely on role.sortorder because then
admins/coursecreators will always win. That is why the sane
rule "is locality matters most", with sortorder as 2nd
consideration.

If you want role.sortorder, use the 'sortorder' policy, and
name explicitly what roles you want to cover. It's probably
a good idea to see what roles have the capabilities you want
(array_diff() them against roiles that have 'can-do-anything'
to weed out admin-ish roles. Or fetch a list of roles from
variables like $CFG->coursecontact .

param: array $users Users array, keyed on userid
param: context $context
param: array $roles ids of the roles to include, optional
param: string $sortpolicy defaults to locality, more about
return: array sorted copy of the array

get_role_users($roleid, context $context, $parent = false, $fields = '',$sort = null, $all = true, $group = '',$limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()   X-Ref
Gets all the users assigned this role in this context or higher

Note that moodle is based on capabilities and it is usually better
to check permissions than to check role ids as the capabilities
system is more flexible. If you really need, you can to use this
function but consider has_capability() as a possible substitute.

All $sort fields are added into $fields if not present there yet.

If $roleid is an array or is empty (all roles) you need to set $fields
(and $sort by extension) params according to it, as the first field
returned by the database should be unique (ra.id is the best candidate).

param: int|array $roleid (can also be an array of ints!)
param: context $context
param: bool $parent if true, get list of users assigned in higher context too
param: string $fields fields from user (u.) , role assignment (ra) or role (r.)
param: string $sort sort from user (u.) , role assignment (ra.) or role (r.).
param: bool $all true means all, false means limit to enrolled users
param: string $group defaults to ''
param: mixed $limitfrom defaults to ''
param: mixed $limitnum defaults to ''
param: string $extrawheretest defaults to ''
param: array $whereorsortparams any paramter values used by $sort or $extrawheretest.
return: array

count_role_users($roleid, context $context, $parent = false)   X-Ref
Counts all the users assigned this role in this context or higher

param: int|array $roleid either int or an array of ints
param: context $context
param: bool $parent if true, get list of users assigned in higher context too
return: int Returns the result count

get_user_capability_contexts(string $capability, bool $getcategories, $userid = null, $doanything = true,$coursefieldsexceptid = '', $categoryfieldsexceptid = '', $courseorderby = '',$categoryorderby = '', $limit = 0)   X-Ref
This function gets the list of course and course category contexts that this user has a particular capability in.

It is now reasonably efficient, but bear in mind that if there are users who have the capability
everywhere, it may return an array of all contexts.

param: string $capability Capability in question
param: int $userid User ID or null for current user
param: bool $getcategories Wether to return also course_categories
param: bool $doanything True if 'doanything' is permitted (default)
param: string $coursefieldsexceptid Leave blank if you only need 'id' in the course records;
param: string $categoryfieldsexceptid Leave blank if you only need 'id' in the course records;
param: string $courseorderby If set, use a comma-separated list of fields from course
param: string $categoryorderby If set, use a comma-separated list of fields from course_category
param: int $limit Limit the number of courses to return on success. Zero equals all entries.
return: array Array of categories and courses.

get_user_capability_course($capability, $userid = null, $doanything = true, $fieldsexceptid = '',$orderby = '', $limit = 0)   X-Ref
This function gets the list of courses that this user has a particular capability in.

It is now reasonably efficient, but bear in mind that if there are users who have the capability
everywhere, it may return an array of all courses.

param: string $capability Capability in question
param: int $userid User ID or null for current user
param: bool $doanything True if 'doanything' is permitted (default)
param: string $fieldsexceptid Leave blank if you only need 'id' in the course records;
param: string $orderby If set, use a comma-separated list of fields from course
param: int $limit Limit the number of courses to return on success. Zero equals all entries.
return: array|bool Array of courses, if none found false is returned.

role_switch($roleid, context $context)   X-Ref
Switches the current user to another role for the current session and only
in the given context.

The caller *must* check
- that this op is allowed
- that the requested role can be switched to in this context (use get_switchable_roles)
- that the requested role is NOT $CFG->defaultuserroleid

To "unswitch" pass 0 as the roleid.

This function *will* modify $USER->access - beware

param: integer $roleid the role to switch to.
param: context $context the context in which to perform the switch.
return: bool success or failure.

is_role_switched($courseid)   X-Ref
Checks if the user has switched roles within the given course.

Note: You can only switch roles within the course, hence it takes a course id
rather than a context. On that note Petr volunteered to implement this across
all other contexts, all requests for this should be forwarded to him ;)

param: int $courseid The id of the course to check
return: bool True if the user has switched roles within the course.

get_roles_with_override_on_context(context $context)   X-Ref
Get any role that has an override on exact context

param: context $context The context to check
return: array An array of roles

get_capabilities_from_role_on_context($role, context $context)   X-Ref
Get all capabilities for this role on this context (overrides)

param: stdClass $role
param: context $context
return: array

get_users_from_role_on_context($role, context $context)   X-Ref
Find all user assignment of users for this role, on this context

param: stdClass $role
param: context $context
return: array

user_has_role_assignment($userid, $roleid, $contextid = 0)   X-Ref
Simple function returning a boolean true if user has roles
in context or parent contexts, otherwise false.

param: int $userid
param: int $roleid
param: int $contextid empty means any context
return: bool

role_get_name(stdClass $role, $context = null, $rolenamedisplay = ROLENAME_ALIAS)   X-Ref
Get localised role name or alias if exists and format the text.

param: stdClass $role role object
param: context|bool $context empty means system context
param: int $rolenamedisplay type of role name
return: string localised role name or course role name alias

role_get_description(stdClass $role)   X-Ref
Returns localised role description if available.
If the name is empty it tries to find the default role name using
hardcoded list of default role names or other methods in the future.

param: stdClass $role
return: string localised role name

role_get_names(context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null)   X-Ref
Get all the localised role names for a context.

In new installs default roles have empty names, this function
add localised role names using current language pack.

param: context $context the context, null means system context
param: array of role objects with a ->localname field containing the context-specific role name.
param: int $rolenamedisplay
param: bool $returnmenu true means id=>localname, false means id=>rolerecord
return: array Array of context-specific role names, or role objects with a ->localname field added.

role_fix_names($roleoptions, context $context = null, $rolenamedisplay = ROLENAME_ALIAS, $returnmenu = null)   X-Ref
Prepare list of roles for display, apply aliases and localise default role names.

param: array $roleoptions array roleid => roleobject (with optional coursealias), strings are accepted for backwards compatibility only
param: context $context the context, null means system context
param: int $rolenamedisplay
param: bool $returnmenu null means keep the same format as $roleoptions, true means id=>localname, false means id=>rolerecord
return: array Array of context-specific role names, or role objects with a ->localname field added.

component_level_changed($cap, $comp, $contextlevel)   X-Ref
Aids in detecting if a new line is required when reading a new capability

This function helps admin/roles/manage.php etc to detect if a new line should be printed
when we read in a new capability.
Most of the time, if the 2 components are different we should print a new line, (e.g. course system->rss client)
but when we are in grade, all reports/import/export capabilities should be together

param: stdClass $cap component string a
param: string $comp component string b
param: int $contextlevel
return: bool whether 2 component are in different "sections"

fix_role_sortorder($allroles)   X-Ref
Fix the roles.sortorder field in the database, so it contains sequential integers,
and return an array of roleids in order.

param: array $allroles array of roles, as returned by get_all_roles();
return: array $role->sortorder =-> $role->id with the keys in ascending order.

switch_roles($first, $second)   X-Ref
Switch the sort order of two roles (used in admin/roles/manage.php).

param: stdClass $first The first role. Actually, only ->sortorder is used.
param: stdClass $second The second role. Actually, only ->sortorder is used.
return: boolean success or failure

role_cap_duplicate($sourcerole, $targetrole)   X-Ref
Duplicates all the base definitions of a role

param: stdClass $sourcerole role to copy from
param: int $targetrole id of role to copy to

get_roles_with_cap_in_context($context, $capability)   X-Ref
Returns two lists, this can be used to find out if user has capability.
Having any needed role and no forbidden role in this context means
user has this capability in this context.
Use get_role_names_with_cap_in_context() if you need role names to display in the UI

param: stdClass $context
param: string $capability
return: array($neededroles, $forbiddenroles)

get_roles_with_caps_in_context($context, $capabilities)   X-Ref
Returns an array of role IDs that have ALL of the the supplied capabilities
Uses get_roles_with_cap_in_context(). Returns $allowed minus $forbidden

param: stdClass $context
param: array $capabilities An array of capabilities
return: array of roles with all of the required capabilities

get_role_names_with_caps_in_context($context, $capabilities)   X-Ref
Returns an array of role names that have ALL of the the supplied capabilities
Uses get_roles_with_caps_in_context(). Returns $allowed minus $forbidden

param: stdClass $context
param: array $capabilities An array of capabilities
return: array of roles with all of the required capabilities

prohibit_is_removable($roleid, context $context, $capability)   X-Ref
This function verifies the prohibit comes from this context
and there are no more prohibits in parent contexts.

param: int $roleid
param: context $context
param: string $capability name
return: bool

role_change_permission($roleid, $context, $capname, $permission)   X-Ref
More user friendly role permission changing,
it should produce as few overrides as possible.

param: int $roleid
param: stdClass|context $context
param: string $capname capability name
param: int $permission
return: void

get_sorted_contexts($select, $params = array()   X-Ref
Runs get_records select on context table and returns the result
Does get_records_select on the context table, and returns the results ordered
by contextlevel, and then the natural sort order within each level.
for the purpose of $select, you need to know that the context table has been
aliased to ctx, so for example, you can call get_sorted_contexts('ctx.depth = 3');

param: string $select the contents of the WHERE clause. Remember to do ctx.fieldname.
param: array $params any parameters required by $select.
return: array the requested context records.

extract_suspended_users($context, &$users, $ignoreusers=array()   X-Ref
Given context and array of users, returns array of users whose enrolment status is suspended,
or enrolment has expired or has not started. Also removes those users from the given array

param: context $context context in which suspended users should be extracted.
param: array $users list of users.
param: array $ignoreusers array of user ids to ignore, e.g. guest
return: array list of suspended users.

get_suspended_userids(context $context, $usecache = false)   X-Ref
Given context and array of users, returns array of user ids whose enrolment status is suspended,
or enrolment has expired or not started.

param: context $context context in which user enrolment is checked.
param: bool $usecache Enable or disable (default) the request cache
return: array list of suspended user id's.

get_with_capability_sql(context $context, $capability)   X-Ref
Gets sql for finding users with capability in the given context

param: context $context
param: string|array $capability Capability name or array of names.
return: array($sql, $params)