Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Access API: Difference between revisions

From MoodleDocs
Line 107: Line 107:
</code>
</code>


Good example is choice module where we have one slot for each participant, people that are not enrolled are not allowed to vote <code>is_enrolled($context, NULL, 'mod/choice:choose')</code>. Another example is assignment where users need to be enrolled and have capability to submit assignemnts <code>is_enrolled($this->context, $USER, 'mod/assignment:submit')</code>.
Good example is choice module where we have one slot for each participant, people that are not enrolled are not allowed to vote <code>is_enrolled($context, $USER, 'mod/choice:choose')</code>. Another example is assignment where users need to be enrolled and have capability to submit assignemnts <code>is_enrolled($this->context, $USER, 'mod/assignment:submit')</code>.


====get_enrolled_users()====
====get_enrolled_users()====

Revision as of 17:35, 14 January 2012

Moodle 2.2 The Access API gives you functions so you can determine what the current user is allow to do, and it allows modules to extend Moodle with new capabilities.

Overview

Moodle is using a role based access control model. Most entities in Moodle (system, users, course categories, courses, modules and blocks) are represented by contexts that are arranged in a tree like hierarchy called context tree. Role is a set of capability definitions, each capability usually represents an ability of user to do something. Roles are defined at the top most system context level. Role definitions can be overridden at lower context levels. User access control is calculated from the definitions of roles assigned to users.

All users that did not log-in yet automatically get the default role defined in $CFG->notloggedinroleid, it is not possible to assign any other role to this non-existent user id. There is one special guest user account that is user when user logs in using the guest login button or when guest autologin is enabled. Again you can not assign any roles to the guest account directly, this account gets the $CFG->guestroleid automatically. All other authenticated users get the default user role specified in $CFG->defaultuserroleid and in the frontpage context the role specified in $CFG->defaultfrontpageroleid.

How to define new capabilities in plugins

Capabilities are defined by $capabilities array defined in db/access.php files. The name of the capability consists of "plugintype/pluginname:capabilityname".

For example:

$capabilities = array(
   'mod/folder:managefiles' => array(
       'riskbitmask' => RISK_SPAM,
       'captype' => 'write',
       'contextlevel' => CONTEXT_MODULE,
       'archetypes' => array(
           'editingteacher' => CAP_ALLOW
       )
   ),
);

Where the meaning of array keys is:

  • riskbitmask - associated risks
  • captype - read or write capability type, for security reasons system prevents all write capabilities for guest account and not-logged-in users
  • contextlevel - specified as context level constant, the lowest level where is this capability usable, plugins may hardcode exceptions if they use capability in more contexts
  • archetypes - specifies defaults for roles with standard archetypes, this is used in installs, upgrades and when resetting roles (it is recommended to use only CAP_ALLOW here)

It is necessary to bump up plugin version number after any change in db/access.php.

The capability names are defined in plugin language files, the name of the string consists of "pluginname:capabilityname", in the example above it would be:

$string['folder:managefiles'] = 'Manage files in folder module';

Useful functions and classes

Context fetching

In plugins context instances are usually only instantiated because they are instantiated and deleted automatically by the system.

Fetching by object id:

$systemcontext = context_system::instance();
$usercontext = context_user::instance($user->id);
$categorycontext = context_coursecat::instance($category->id);
$coursecontext = context_course::instance($course->id);
$contextmodule = context_module::instance($cm->id);

Fetching by context id:

$context = context::instance_by_id($contextid);

Notes:

  • by default exception is thrown if context can not be created
  • deleted users do not have contexts any more


There are multiple deprecated context related functions since 2.2, it is not necessary to replace them immediately. The following two functions are equivalent to the context fetching examples above:

function get_context_instance($contextlevel, $instance = 0, $strictness = IGNORE_MISSING)
function get_context_instance_by_id($id, $strictness = IGNORE_MISSING)

Determining that a user has a given capability

When implementing access control always ask "Does the user have capability to do something?". It is incorrect to ask "Does the user have a role somewhere?".

has_capability()

has_capability() is the most important function:

function has_capability($capability, context $context, $user = null, $doanything = true)

Check whether a user has a particular capability in a given context. For example:

$context = context_module::instance($cm->id);
has_capability('mod/folder:managefiles', $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, it is not recommended to use false here.

require_capability()

Function require_capability() is very similar, it is throwing access control exception if user does not have the capability.

function require_capability($capability, context $context, $userid = null, $doanything = true, $errormessage = 'nopermissions', $stringfile = ) {

Enrolment functions

Since Moodle 2.2 there is a new concept of user enrolments, they are fully independent from the roles and capabilities, see Enrol API for more information.

Capabilities are very often used in combination with enrolment status.

is_enrolled()

Is user participating in the course? Returns true for students and teachers, false for administrators and other managers. User enrolments can be either active or suspended, suspended users can not enter the course (unless there is some kind of guest access allowed) and are usually hidden in the UI.

function is_enrolled(context $context, $user = null, $withcapability = , $onlyactive = false)

Good example is choice module where we have one slot for each participant, people that are not enrolled are not allowed to vote is_enrolled($context, $USER, 'mod/choice:choose'). Another example is assignment where users need to be enrolled and have capability to submit assignemnts is_enrolled($this->context, $USER, 'mod/assignment:submit').

get_enrolled_users()

function get_enrolled_sql(context $context, $withcapability = , $groupid = 0, $onlyactive = false)
function get_enrolled_users(context $context, $withcapability = , $groupid = 0, $userfields = 'u.*', $orderby = , $limitfrom = 0, $limitnum = 0)

Other related functions

function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false)
function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false)
function get_users_by_capability(context $context, $capability, $fields = , $sort = , $limitfrom = , $limitnum = ,
                                 $groups = , $exceptions = , $doanything_ignored = null, $view_ignored = null, $useviewallgroups = false)
function isguestuser($user = null)
function isloggedin()
function is_siteadmin($user_or_id = null)
function is_guest(context $context, $user = null)
function is_viewing(context $context, $user = null, $withcapability = )

require_login()

Each plugin script should include require_login() or require_course_login() after setting up PAGE->url.

this function does following:

  • it verifies that user is logged in before accessing any course or activities (not-logged-in users can not enter any courses).
  • user is logged in as gu
  • verify access to hidden courses and activities
  • verify experimental groupmembersonly access
  • verify that user is either enrolled or has capability 'moodle/course:view' or some enrol plugin gives them temporary guest access
  • logs access to courses

require_course_login()

This function is supposed to be used only in activities that want to allow read access to content on the frontpage without logging-in. For example view resource files, reading of glossary entries, etc.

See also