Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
/lib/ -> accesslib.php (source)

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

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: 7752 lines (274 kb)
Included or required:0 times
Referenced: 0 times
Includes or requires: 0 files

Defines 8 classes

context:: (37 methods):
  reset_caches()
  cache_add()
  cache_remove()
  cache_get()
  cache_get_by_id()
  preload_from_record()
  __set()
  __get()
  __isset()
  __unset()
  getIterator()
  __construct()
  create_instance_from_record()
  merge_context_temp_table()
  instance_by_id()
  update_moved()
  set_locked()
  reset_paths()
  delete_content()
  delete_capabilities()
  delete()
  insert_context_record()
  get_context_name()
  is_locked()
  get_child_contexts()
  is_parent_of()
  get_parent_contexts()
  is_child_of()
  get_parent_context_ids()
  get_parent_context_paths()
  get_parent_context()
  get_course_context()
  get_cleanup_sql()
  build_paths()
  create_level_instances()
  reload_if_dirty()
  mark_dirty()

context_helper:: (19 methods):
  __construct()
  reset_levels()
  init_levels()
  get_class_for_level()
  get_all_levels()
  cleanup_instances()
  create_instances()
  build_all_paths()
  reset_caches()
  get_preload_record_columns()
  get_preload_record_columns_sql()
  preload_from_record()
  preload_contexts_by_id()
  preload_course()
  delete_instance()
  get_level_name()
  get_navigation_filter_context()
  get_url()
  get_capabilities()

context_system:: (11 methods):
  __construct()
  get_level_name()
  get_context_name()
  get_url()
  get_capabilities()
  create_level_instances()
  instance()
  get_child_contexts()
  get_cleanup_sql()
  build_paths()
  set_locked()

context_user:: (9 methods):
  __construct()
  get_level_name()
  get_context_name()
  get_url()
  get_capabilities()
  instance()
  create_level_instances()
  get_cleanup_sql()
  build_paths()

context_coursecat:: (10 methods):
  __construct()
  get_level_name()
  get_context_name()
  get_url()
  get_capabilities()
  instance()
  get_child_contexts()
  create_level_instances()
  get_cleanup_sql()
  build_paths()

context_course:: (10 methods):
  __construct()
  get_level_name()
  get_context_name()
  get_url()
  get_capabilities()
  get_course_context()
  instance()
  create_level_instances()
  get_cleanup_sql()
  build_paths()

context_module:: (10 methods):
  __construct()
  get_level_name()
  get_context_name()
  get_url()
  get_capabilities()
  get_course_context()
  instance()
  create_level_instances()
  get_cleanup_sql()
  build_paths()

context_block:: (15 methods):
  __construct()
  get_level_name()
  get_context_name()
  get_url()
  get_capabilities()
  get_course_context()
  instance()
  get_child_contexts()
  create_level_instances()
  get_cleanup_sql()
  build_paths()
  get_sorted_contexts()
  extract_suspended_users()
  get_suspended_userids()
  get_with_capability_sql()

Defines 15 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_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_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()

Class: context  - X-Ref

Basic moodle context abstraction class.

Google confirms that no other important framework is using "context" class,
we could use something else like mcontext or moodle_context, but we need to type
this very often which would be annoying and it would take too much space...

This class is derived from stdClass for backwards compatibility with
odl $context record that was returned from DML $DB->get_record()

reset_caches()   X-Ref
Resets the cache to remove all data.


cache_add(context $context)   X-Ref
Adds a context to the cache. If the cache is full, discards a batch of
older entries.

param: context $context New context to add
return: void

cache_remove(context $context)   X-Ref
Removes a context from the cache.

param: context $context Context object to remove
return: void

cache_get($contextlevel, $instance)   X-Ref
Gets a context from the cache.

param: int $contextlevel Context level
param: int $instance Instance ID
return: context|bool Context or false if not in cache

cache_get_by_id($id)   X-Ref
Gets a context from the cache based on its id.

param: int $id Context ID
return: context|bool Context or false if not in cache

preload_from_record(stdClass $rec)   X-Ref
Preloads context information from db record and strips the cached info.

param: stdClass $rec
return: void (modifies $rec)

__set($name, $value)   X-Ref
Magic setter method, we do not want anybody to modify properties from the outside

param: string $name
param: mixed $value

__get($name)   X-Ref
Magic method getter, redirects to read only values.

param: string $name
return: mixed

__isset($name)   X-Ref
Full support for isset on our magic read only properties.

param: string $name
return: bool

__unset($name)   X-Ref
All properties are read only, sorry.

param: string $name

getIterator()   X-Ref
Create an iterator because magic vars can't be seen by 'foreach'.

Now we can convert context object to array using convert_to_array(),
and feed it properly to json_encode().

__construct(stdClass $record)   X-Ref
Constructor is protected so that devs are forced to
use context_xxx::instance() or context::instance_by_id().

param: stdClass $record

create_instance_from_record(stdClass $record)   X-Ref
This function is also used to work around 'protected' keyword problems in context_helper.

param: stdClass $record
return: context instance

merge_context_temp_table()   X-Ref
Copy prepared new contexts from temp table to context table,
we do this in db specific way for perf reasons only.


instance_by_id($id, $strictness = MUST_EXIST)   X-Ref
Get a context instance as an object, from a given context id.

param: int $id context id
param: int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
return: context|bool the context object or false if not found

update_moved(context $newparent)   X-Ref
Update context info after moving context in the tree structure.

param: context $newparent
return: void

set_locked(bool $locked)   X-Ref
Set whether this context has been locked or not.

param: bool    $locked
return: $this

reset_paths($rebuild = true)   X-Ref
Remove all context path info and optionally rebuild it.

param: bool $rebuild
return: void

delete_content()   X-Ref
Delete all data linked to content, do not delete the context record itself


delete_capabilities()   X-Ref
Unassign all capabilities from a context.


delete()   X-Ref
Delete the context content and the context record itself


insert_context_record($contextlevel, $instanceid, $parentpath)   X-Ref
Utility method for context creation

param: int $contextlevel
param: int $instanceid
param: string $parentpath
return: stdClass context record

get_context_name($withprefix = true, $short = false, $escape = true)   X-Ref
Returns human readable context identifier.

param: boolean $withprefix whether to prefix the name of the context with the
param: boolean $short whether to use the short name of the thing. Only applies
param: boolean $escape Whether the returned name of the thing is to be
return: string the human readable context name.

is_locked()   X-Ref
Whether the current context is locked.

return: bool

get_child_contexts()   X-Ref
Recursive function which, given a context, find all its children context ids.

For course category contexts it will return immediate children and all subcategory contexts.
It will NOT recurse into courses or subcategories categories.
If you want to do that, call it on the returned courses/categories.

When called for a course context, it will return the modules and blocks
displayed in the course page and blocks displayed on the module pages.

If called on a user/course/module context it _will_ populate the cache with the appropriate
contexts ;-)

return: array Array of child records

is_parent_of(context $possiblechild, bool $includeself)   X-Ref
Determine if the current context is a parent of the possible child.

param: context $possiblechild
param: bool $includeself Whether to check the current context
return: bool

get_parent_contexts($includeself = false)   X-Ref
Returns parent contexts of this context in reversed order, i.e. parent first,
then grand parent, etc.

param: bool $includeself true means include self too
return: array of context instances

is_child_of(context $possibleparent, bool $includeself)   X-Ref
Determine if the current context is a child of the possible parent.

param: context $possibleparent
param: bool $includeself Whether to check the current context
return: bool

get_parent_context_ids($includeself = false)   X-Ref
Returns parent context ids of this context in reversed order, i.e. parent first,
then grand parent, etc.

param: bool $includeself true means include self too
return: array of context ids

get_parent_context_paths($includeself = false)   X-Ref
Returns parent context paths of this context.

param: bool $includeself true means include self too
return: array of context paths

get_parent_context()   X-Ref
Returns parent context

return: context

get_course_context($strict = true)   X-Ref
Is this context part of any course? If yes return course context.

param: bool $strict true means throw exception if not found, false means return false if not found
return: context_course context of the enclosing course, null if not found or exception

get_cleanup_sql()   X-Ref
Returns sql necessary for purging of stale context instances.

return: string cleanup SQL

build_paths($force)   X-Ref
Rebuild context paths and depths at context level.

param: bool $force
return: void

create_level_instances()   X-Ref
Create missing context instances at given level

return: void

reload_if_dirty()   X-Ref
Reset all cached permissions and definitions if the necessary.

return: void

mark_dirty()   X-Ref
Mark a context as dirty (with timestamp) so as to force reloading of the context.


Class: context_helper  - X-Ref

Context maintenance and helper methods.

This is "extends context" is a bloody hack that tires to work around the deficiencies
in the "protected" keyword in PHP, this helps us to hide all the internals of context
level implementation from the rest of code, the code completion returns what developers need.

Thank you Tim Hunt for helping me with this nasty trick.

__construct()   X-Ref
Instance does not make sense here, only static use


reset_levels()   X-Ref
Reset internal context levels array.


init_levels()   X-Ref
Initialise context levels, call before using self::$alllevels.


get_class_for_level($contextlevel)   X-Ref
Returns a class name of the context level class

param: int $contextlevel (CONTEXT_SYSTEM, etc.)
return: string class name of the context class

get_all_levels()   X-Ref
Returns a list of all context levels

return: array int=>string (level=>level class name)

cleanup_instances()   X-Ref
Remove stale contexts that belonged to deleted instances.
Ideally all code should cleanup contexts properly, unfortunately accidents happen...

return: void

create_instances($contextlevel = null, $buildpaths = true)   X-Ref
Create all context instances at the given level and above.

param: int $contextlevel null means all levels
param: bool $buildpaths
return: void

build_all_paths($force = false)   X-Ref
Rebuild paths and depths in all context levels.

param: bool $force false means add missing only
return: void

reset_caches()   X-Ref
Resets the cache to remove all data.


get_preload_record_columns($tablealias)   X-Ref
Returns all fields necessary for context preloading from user $rec.

This helps with performance when dealing with hundreds of contexts.

param: string $tablealias context table alias in the query
return: array (table.column=>alias, ...)

get_preload_record_columns_sql($tablealias)   X-Ref
Returns all fields necessary for context preloading from user $rec.

This helps with performance when dealing with hundreds of contexts.

param: string $tablealias context table alias in the query
return: string

preload_from_record(stdClass $rec)   X-Ref
Preloads context information from db record and strips the cached info.

The db request has to contain all columns from context_helper::get_preload_record_columns().

param: stdClass $rec
return: void (modifies $rec)

preload_contexts_by_id(array $contextids)   X-Ref
Preload a set of contexts using their contextid.

param: array $contextids

preload_course($courseid)   X-Ref
Preload all contexts instances from course.

To be used if you expect multiple queries for course activities...

param: int $courseid

delete_instance($contextlevel, $instanceid)   X-Ref
Delete context instance

param: int $contextlevel
param: int $instanceid
return: void

get_level_name($contextlevel)   X-Ref
Returns the name of specified context level

param: int $contextlevel
return: string name of the context level

get_navigation_filter_context(?context $context)   X-Ref
Gets the current context to be used for navigation tree filtering.

param: context|null $context The current context to be checked against.
return: context|null the context that navigation tree filtering should use.

get_url()   X-Ref
not used


get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT)   X-Ref
not used

param: string $sort

Class: context_system  - X-Ref

System context class

__construct(stdClass $record)   X-Ref
Please use context_system::instance() if you need the instance of context.

param: stdClass $record

get_level_name()   X-Ref
Returns human readable context level name.

return: string the human readable context level name.

get_context_name($withprefix = true, $short = false, $escape = true)   X-Ref
Returns human readable context identifier.

param: boolean $withprefix does not apply to system context
param: boolean $short does not apply to system context
param: boolean $escape does not apply to system context
return: string the human readable context name.

get_url()   X-Ref
Returns the most relevant URL for this context.

return: moodle_url

get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT)   X-Ref
Returns array of relevant context capability records.

param: string $sort
return: array

create_level_instances()   X-Ref
Create missing context instances at system context


instance($instanceid = 0, $strictness = MUST_EXIST, $cache = true)   X-Ref
Returns system context instance.

param: int $instanceid should be 0
param: int $strictness
param: bool $cache
return: context_system context instance

get_child_contexts()   X-Ref
Returns all site contexts except the system context, DO NOT call on production servers!!

Contexts are not cached.

return: array

get_cleanup_sql()   X-Ref
Returns sql necessary for purging of stale context instances.

return: string cleanup SQL

build_paths($force)   X-Ref
Rebuild context paths and depths at system context level.

param: bool $force

set_locked(bool $locked)   X-Ref
Set whether this context has been locked or not.

param: bool    $locked
return: $this

Class: context_user  - X-Ref

User context class

__construct(stdClass $record)   X-Ref
Please use context_user::instance($userid) if you need the instance of context.
Alternatively if you know only the context id use context::instance_by_id($contextid)

param: stdClass $record

get_level_name()   X-Ref
Returns human readable context level name.

return: string the human readable context level name.

get_context_name($withprefix = true, $short = false, $escape = true)   X-Ref
Returns human readable context identifier.

param: boolean $withprefix whether to prefix the name of the context with User
param: boolean $short does not apply to user context
param: boolean $escape does not apply to user context
return: string the human readable context name.

get_url()   X-Ref
Returns the most relevant URL for this context.

return: moodle_url

get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT)   X-Ref
Returns array of relevant context capability records.

param: string $sort
return: array

instance($userid, $strictness = MUST_EXIST)   X-Ref
Returns user context instance.

param: int $userid id from {user} table
param: int $strictness
return: context_user context instance

create_level_instances()   X-Ref
Create missing context instances at user context level


get_cleanup_sql()   X-Ref
Returns sql necessary for purging of stale context instances.

return: string cleanup SQL

build_paths($force)   X-Ref
Rebuild context paths and depths at user context level.

param: bool $force

Class: context_coursecat  - X-Ref

Course category context class

__construct(stdClass $record)   X-Ref
Please use context_coursecat::instance($coursecatid) if you need the instance of context.
Alternatively if you know only the context id use context::instance_by_id($contextid)

param: stdClass $record

get_level_name()   X-Ref
Returns human readable context level name.

return: string the human readable context level name.

get_context_name($withprefix = true, $short = false, $escape = true)   X-Ref
Returns human readable context identifier.

param: boolean $withprefix whether to prefix the name of the context with Category
param: boolean $short does not apply to course categories
param: boolean $escape Whether the returned name of the context is to be HTML escaped or not.
return: string the human readable context name.

get_url()   X-Ref
Returns the most relevant URL for this context.

return: moodle_url

get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT)   X-Ref
Returns array of relevant context capability records.

param: string $sort
return: array

instance($categoryid, $strictness = MUST_EXIST)   X-Ref
Returns course category context instance.

param: int $categoryid id from {course_categories} table
param: int $strictness
return: context_coursecat context instance

get_child_contexts()   X-Ref
Returns immediate child contexts of category and all subcategories,
children of subcategories and courses are not returned.

return: array

create_level_instances()   X-Ref
Create missing context instances at course category context level


get_cleanup_sql()   X-Ref
Returns sql necessary for purging of stale context instances.

return: string cleanup SQL

build_paths($force)   X-Ref
Rebuild context paths and depths at course category context level.

param: bool $force

Class: context_course  - X-Ref

Course context class

__construct(stdClass $record)   X-Ref
Please use context_course::instance($courseid) if you need the instance of context.
Alternatively if you know only the context id use context::instance_by_id($contextid)

param: stdClass $record

get_level_name()   X-Ref
Returns human readable context level name.

return: string the human readable context level name.

get_context_name($withprefix = true, $short = false, $escape = true)   X-Ref
Returns human readable context identifier.

param: boolean $withprefix whether to prefix the name of the context with Course
param: boolean $short whether to use the short name of the thing.
param: bool $escape Whether the returned category name is to be HTML escaped or not.
return: string the human readable context name.

get_url()   X-Ref
Returns the most relevant URL for this context.

return: moodle_url

get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT)   X-Ref
Returns array of relevant context capability records.

param: string $sort
return: array

get_course_context($strict = true)   X-Ref
Is this context part of any course? If yes return course context.

param: bool $strict true means throw exception if not found, false means return false if not found
return: context_course context of the enclosing course, null if not found or exception

instance($courseid, $strictness = MUST_EXIST)   X-Ref
Returns course context instance.

param: int $courseid id from {course} table
param: int $strictness
return: context_course context instance

create_level_instances()   X-Ref
Create missing context instances at course context level


get_cleanup_sql()   X-Ref
Returns sql necessary for purging of stale context instances.

return: string cleanup SQL

build_paths($force)   X-Ref
Rebuild context paths and depths at course context level.

param: bool $force

Class: context_module  - X-Ref

Course module context class

__construct(stdClass $record)   X-Ref
Please use context_module::instance($cmid) if you need the instance of context.
Alternatively if you know only the context id use context::instance_by_id($contextid)

param: stdClass $record

get_level_name()   X-Ref
Returns human readable context level name.

return: string the human readable context level name.

get_context_name($withprefix = true, $short = false, $escape = true)   X-Ref
Returns human readable context identifier.

param: boolean $withprefix whether to prefix the name of the context with the
param: boolean $short does not apply to module context
param: boolean $escape Whether the returned name of the context is to be HTML escaped or not.
return: string the human readable context name.

get_url()   X-Ref
Returns the most relevant URL for this context.

return: moodle_url

get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT)   X-Ref
Returns array of relevant context capability records.

param: string $sort
return: array

get_course_context($strict = true)   X-Ref
Is this context part of any course? If yes return course context.

param: bool $strict true means throw exception if not found, false means return false if not found
return: context_course context of the enclosing course, null if not found or exception

instance($cmid, $strictness = MUST_EXIST)   X-Ref
Returns module context instance.

param: int $cmid id of the record from {course_modules} table; pass cmid there, NOT id in the instance column
param: int $strictness
return: context_module context instance

create_level_instances()   X-Ref
Create missing context instances at module context level


get_cleanup_sql()   X-Ref
Returns sql necessary for purging of stale context instances.

return: string cleanup SQL

build_paths($force)   X-Ref
Rebuild context paths and depths at module context level.

param: bool $force

Class: context_block  - X-Ref

Block context class

__construct(stdClass $record)   X-Ref
Please use context_block::instance($blockinstanceid) if you need the instance of context.
Alternatively if you know only the context id use context::instance_by_id($contextid)

param: stdClass $record

get_level_name()   X-Ref
Returns human readable context level name.

return: string the human readable context level name.

get_context_name($withprefix = true, $short = false, $escape = true)   X-Ref
Returns human readable context identifier.

param: boolean $withprefix whether to prefix the name of the context with Block
param: boolean $short does not apply to block context
param: boolean $escape does not apply to block context
return: string the human readable context name.

get_url()   X-Ref
Returns the most relevant URL for this context.

return: moodle_url

get_capabilities(string $sort = self::DEFAULT_CAPABILITY_SORT)   X-Ref
Returns array of relevant context capability records.

param: string $sort
return: array

get_course_context($strict = true)   X-Ref
Is this context part of any course? If yes return course context.

param: bool $strict true means throw exception if not found, false means return false if not found
return: context_course context of the enclosing course, null if not found or exception

instance($blockinstanceid, $strictness = MUST_EXIST)   X-Ref
Returns block context instance.

param: int $blockinstanceid id from {block_instances} table.
param: int $strictness
return: context_block context instance

get_child_contexts()   X-Ref
Block do not have child contexts...

return: array

create_level_instances()   X-Ref
Create missing context instances at block context level


get_cleanup_sql()   X-Ref
Returns sql necessary for purging of stale context instances.

return: string cleanup SQL

build_paths($force)   X-Ref
Rebuild context paths and depths at block context level.

param: bool $force

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)

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)   X-Ref
Function to write context specific overrides, or default capabilities.

param: string $capability string name
param: int $permission CAP_ constants
param: int $roleid role id
param: int|context $contextid context id
param: bool $overwrite
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: stdClass $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_quiz_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_quiz_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_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 $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_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: string $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
param: string $capname capability name
param: int $permission
return: void