Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.
/lib/ -> accesslib.php (source)

Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 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: 7813 lines (277 kb)
Included or required:0 times
Referenced: 2 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_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()

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.

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

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

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

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

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

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

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

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

return: void (modifies $rec)
param: stdClass $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.

return: mixed
param: string $name

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

return: bool
param: string $name

__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.

return: context instance
param: stdClass $record

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.

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

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

return: void
param: context $newparent

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

return: $this
param: bool    $locked

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

return: void
param: bool $rebuild

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

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

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

return: string the human readable context name.
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

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.

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

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

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

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

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

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.

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

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

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

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.

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

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.

return: void
param: bool $force

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

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

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.

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

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

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

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.

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

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.

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

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

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

return: void This is intentional. See MDL-37115. You will need to get the context
param: stdClass $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

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

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

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

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

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

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.

return: string the human readable context name.
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

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.

return: array
param: string $sort

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.

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

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.

return: $this
param: bool    $locked

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.

return: string the human readable context name.
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

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.

return: array
param: string $sort

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

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

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.

return: string the human readable context name.
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.

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.

return: array
param: string $sort

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

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

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.

return: string the human readable context name.
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.

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.

return: array
param: string $sort

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

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

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

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

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.

return: string the human readable context name.
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.

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.

return: array
param: string $sort

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

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

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

return: context_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

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.

return: string the human readable context name.
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

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.

return: array
param: string $sort

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

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

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

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

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');

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

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

return: array list of suspended users.
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

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.

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

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

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

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.

return: void
param: bool $resetcontexts

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.

return: void
param: int|array $roles

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

return: array
param: int $roleid

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.

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

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

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

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.

return: boolean true if the user has this capability. Otherwise false.
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

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.

return: boolean true if the user has any of these capabilities. Otherwise false.
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

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.

return: boolean true if the user has all of these capabilities. Otherwise false.
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

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.

return: boolean true if the user will have this capability.
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.

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.

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

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).

return: bool
param: int $userid

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.

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

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.

return: void terminates with an error if the user does not have the given capability.
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'.

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.

return: void terminates with an error if the user does not have the given capability.
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'.

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

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

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.

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

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.

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

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.

return: void
param: context_course $coursecontext

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.

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

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

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

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

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

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

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

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

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

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

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

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

return: bool always true or exception
param: string $capability string name
param: int $permission CAP_ constants
param: int $roleid role id
param: int|context $contextid context id
param: bool $overwrite

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

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

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.

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

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)

return: int new/existing id of the assignment
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

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

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

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

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

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

return: void
param: int $userid

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'.

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

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

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

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.

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

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.

return: boolean Returns true if the user is able to access the course
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

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.

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

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

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

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

return: array
param: string $archetype role archetype

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

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

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.

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

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

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

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

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

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.

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

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.

return: array
param: context $context

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.

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

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

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

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.

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

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

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

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.

return: array
param: context $context

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

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

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.)

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

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

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

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.

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

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

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

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.

return: array
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'

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

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

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.

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

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

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

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

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

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

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

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

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

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

return: array if $withusercounts is false, then an array $roleid => $rolename.
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.

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.

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

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

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

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.

return: array if $withcounts is false, then an array $roleid => $rolename.
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.

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

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

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

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

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()

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

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

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

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.

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

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

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

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.

return: array of user records
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

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 .

return: array sorted copy of the array
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

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).

return: array
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.

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

return: int Returns the result count
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

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.

return: array Array of categories and courses.
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.

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.

return: array|bool Array of courses, if none found false is returned.
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.

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

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

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 ;)

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

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

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

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

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

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

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

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.

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

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

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

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.

return: string localised role name
param: stdClass $role

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.

return: array Array of context-specific role names, or role objects with a ->localname field added.
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

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.

return: array Array of context-specific role names, or role objects with a ->localname field added.
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

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

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

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.

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

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

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

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

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

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

return: array of roles with all of the required capabilities
param: stdClass $context
param: array $capabilities An array of 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

return: array of roles with all of the required capabilities
param: stdClass $context
param: array $capabilities An array of 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.

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

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

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