Note: You are currently viewing documentation for Moodle 1.9. Up-to-date documentation for the latest stable version is available here: How permissions are calculated.

How permissions are calculated: Difference between revisions

From MoodleDocs
m (Typo)
 
(55 intermediate revisions by 8 users not shown)
Line 1: Line 1:
{{Roles}}
{{Roles}}
One of the most frequently asked question is: ''What permissions does a user have in a given context?'' This article will document the main function in Moodle that is used to answer the question.  The function is ''has_capability()''. It can be found in ''lib/accesslib.php''. The function implements the rules for "summing" permissions from multiple roles and overrides. Given a user, a capability, and a context, the function returns ''true'' if the user is allowed to perform the action controlled by the capability in the given context, and ''false'' otherwise. 


This article is written for non-programmers as well as programmers. It describes ''what'' the function does, not ''how''. The ''how'' is complicated. The ''what'' turns out to be surprisingly simple!
A frequently asked question is, "What are my permissions in this context?". This article attempts to explain how Moodle answers that question. The article is written for non-programmers as well as programmers. It describes what the function does, not how it does it. If you are a programmer and want to see the how, look at the functions has_capability_in_accessdata and has_capability() in lib/accesslib.php.  


Notice that the function ''does not'' attempt to answer the Big Question posed in the first sentence of this article. Instead, it answers the little question "Can some user do ''CAP'' here?" where ''CAP'' is a specific capability. Moodle never computes a user's complete set of permissions.  It would be very costly to do so, and also wasteful, since most of the permissions would never be tested.  Instead, Moodle computes permissions lazily, i.e., on demand. Moodle does not cache computed permissions, but recomputes them every time they need to be tested. This is why role assignments and overrides no longer have delayed effects, as they did in Moodle 1.7.
Incidentally, you will be able generate permission tables like the ones in this article using the 'Explain' links on the new [[Development:Roles_administration_improvements_for_Moodle_2.0#Check_permissions_page|Check permissions]] page in Moodle 2.0. In earlier version, you can install the [[The rolesdebug.php roles debugging script|rolesdebug.php roles debugging script]].


The function is called as follows:


    has_capability(CAPABILITY,CONTEXT,USER);
==Clarifying the question==


The function returns a true/false result
Let us refine the question "What are my permissions in this context?"


* ''true'' means the user should be allowed to perform the action
Naturally, '''my''' can be any user that Moodle knows about. If you don't specify a particular user, it will default to the currently logged in user.
* ''false'' means the user should be prevented from perfoming the action


The CONTEXT can be System context or some context nested arbitrarily deeply within System. Internally, the function uses Unix-style paths to represent contexts (e.g., /1/3/4/150), but such details do not concern us here.
'''Permissions''' can be broken down into a computed permissions of '''true''' or '''false''' for each '''capability'''. The different capabilities are completely independant (apart from the magic 'moodle/site:doanything' capability which will be explained later).


Suppose a user is about to attempt a quiz (mod/quiz:attempt) in a module context nested four levels deep within System.
A '''context''' is a part of a Moodle site. For example a course, a course category, an activity, or so on. Contexts are nested, so an activity will be in a course, which will be in one or more categories, which will be in the whole system. The most specific context that you are in is the most important, and is the one that should be used when asking the question. The other, less-specific contexts that contain this one also influence the result.


      System
So, while our original question was "What are my permissions in this context?" the question Moodle will answer is "Does user ''$user'' have capability ''$capability'' in context ''$context''?" and the answer will be 'Yes' or 'No'.
 
 
==The calculation==
 
As explained in the previous section, we want to know whether has_capability($capability, $context, $user) returns true or false.
 
In order to calculate the answer, Moodle needs to combine various pieces of data.
 
===Data used by the function===
 
====Relevant contexts====
 
To simplify the explanation, let us work with a particular example. Suppose that user $user wants to reply to a forum post ($capability is 'mod/forum:replypost') in a particular forum. And suppose that the forum is in a course in Subcategory B which is in Category A in this Moodle site. That is, the relevant contexts are:
 
      System
         |
         |
     Category A
     Category A
Line 27: Line 39:
       Course
       Course
         |
         |
       Quiz <--- the user is here
       Forum <--- the user is here
 
====Role assignments====
 
All the roles that the user has been assigned in all the relevant contexts will influence the outcome of the has_capability question.
 
A natural example would be that a user has the role 'Student' assigned in context 'Course', and role 'Authenticated User' assigned in context System.
 
However, our example is going to be unnatural and complex, in order to demonstrate all the possible complexities. In our example the user has
* Role R1 in context System
* Roles R2 and R3 in context Subcategory B
* Roles R1 and R4 in context Forum
 
====Role definitions====
 
Naturally, the definition of each role affects the outcome of has_capability. (Role definitions are edited at Administration ► Users ► Permissions ► Define roles.) The role definition sets a permissions of 'Not set', 'Allow', 'Prevent' or 'Prohibit' for each capability.
 
As mentioned above, different capabilities are independent, so, for example, we only need to specify the settings for the 'mod/forum:replypost' capability.
* For role R1, 'mod/forum:replypost' is set to Allow.
* For roles R2 and R3, 'mod/forum:replypost' is Not set.
* For role R4, 'mod/forum:replypost' is set to Prevent.
Remember, this is an intentionally complex and unnatural example.
 
====Permission overrides====


In Moodle you can override the permissions for a role in a particular context. You can think of that as changing the definition of the role in that context. An example would be "In this category of courses, we want to prevent students from posting to forums." In the absence of an override to a different permission, you can imagine that there is an override of 'Inherit' which means use the permission from higher up the chain of contexts.


The quiz module will call ''has_capability'' to see if the user should be allowed to perform this action.
In our ongoing example, we will assume the following overrides have been set up:
* In context Course,
** for role R2, the permissions for 'mod/forum:replypost' is overridden to Prevent
** for role R3, the permissions for 'mod/forum:replypost' is overridden to Allow.


The function considers the following permissions data:
===Representing the data in tabular form===


* ''Role definitions'' (these are in the System context)
All the data mentioned in the previous section is best seen by writing it in a table.
* ''Role assignments'' which have been made in any of the five contexts
* ''Role overrides'' which may occur in any of the contexts except System (there is no concept of override in System).


Note that there may be multiple assignments and/or overrides in any single context.
In the table, there will be one row for each context, and at the start of each row, we write the name of the roles assigned in that context.


Whether or not the user can attempt the quiz is a function of the data, as well as the location of the data in the context chain.
And there  will also be one column for each context, and in that column we write any permission overrides for the roles in each row.


The function ignores any data that isn't used in the computation. It ignores
Except that in the column that represents the System context, we write the permissions from the role definition.


* roles that aren't assigned to the user
Normally, we think of contexts like folders in a file system, with the System context at the top, and the Forum context at the bottom. However, for this table, it turns out to be simpler later if we reverse the normal order, and put the Forum context in the first row and column, and the System context at the end.
* capabilities other than one we're testing
* permissions that are Not set.


After ignoring the above data, we are left with a very simple "data slice" consisting of just those permissions for the capability we're testing, in which all values are either Allow (A), Prevent (P), or Prohibit (X). This data can be represented in a neat tabular form, resembling an addition problem. For our quiz example, suppose we have
The table for the example we have been building up looks like this:


    P  A  P
[[Image:Role_calc_table1.png]]
          A
    P  A  X
    A    P
      P  A
    --------
      ?   


The top row represents the permissions in the role definitions, one permission from each role. In the example, you can see that the user is currently assigned three roles. The remaining rows represent the overrides. In the example, you can see that the user has
===The calculation===


* one override in category A,  
The calculation proceeds by working through the table in normal reading order, left to right, top to bottom. (That is why we put the Forum context first and the System context last.)
* three overrides in the category B
* two overrides the course
* two overrides in the quiz itself.


When representing a complex example like this, it is convenient to line up the override permissions under the role that's being overridden, but it is not necessary to do so because we don't "add" permissions in columns the way we add numbers.
# First, look through the entire table and see if there are any Prohibit permissions anywhere. If there are, stop. The final answer is false - the user does not have this capability.
# If there are no Prohibits, start at the beginning of the first row with role assignments, and go along until you get to a cell containing 'Allow' and/or 'Prevent'. In this cell,
#* If there are more Allows than Prevents, stop. The answer is true - the user has this capability.
#* If there are more Prevents than Allows, stop. The answer is false - the user does not have this capability.
#* If the number of Prevents and Allows is equal, jump down to the start of the next row with role assignments, and repeat this step 2.
# If you get to the end of the table without passing a cell with different numbers of Prevents and Allows, then the answer is false - the user does not have this capability.


We will "add" the permissions in some sense and write the result below the horizontal line. The result, which we call the ''computed permission'', will be either ''A'', ''P'', or ''X''. The function will return ''true'' or ''false'' based on the computed permission.
====Calculating the answer to our example====


Before we start "adding," check the data to see if it contains a prohibit ''X'' anywhere. If it does, we're done. The computed permission is ''X''. For our example...
1. There are no Prohibits anywhere, so proceed to step 2.
2a. Work along the Forum row. We get to the last column. There are an equal number of Prevents and Allows here, so jump down to the start of the next row with role assignments.
2b. Work along the Subcategory B row. We get to the second column that corresponds to the overrides in the Course context. There are an equal number of Prevents and Allows here, so jump down to the start of the next row with role assignments.
2c. Work along the System context row. We get to the last column. There are more allows than prevents here, so the final answer is Yes, this user can reply to a post in this forum.


    P  A  P
The path the algorithm takes is shown by the path in this diagram:
          A
    P  A  X
    A    P
      P  A
    --------
      X    <----- computed permission


[[Image:Role_calc_table2.png]]


If there is no ''X'', the addition algorithm must be used. Unlike normal addition, the addition algorithm
====Some variations to our example====


* starts on the bottom line and works its way up
TODO
* considers one whole line at a time (rather than working in columns)
* may stop with a result before reaching the top line.


Here is the algorithm:
==Does this calculation make sense?==


#Start on the bottom line.
In almost every situation, the complex tie-breaking rules will not be required. Instead, the rules above will just calculate the answer you would expect if you don't think about it too deeply.
#If there is only one permission on the line, take its value as the computed permission and STOP
#If there are two more permissions on the line, add them using the following numerical equivalents: A = +1, P = -1
##If the sum is positive, the computed permission is ''A''. STOP 
##If the sum is negative, the computed permission is ''P''. STOP 
##If the sum is zero, the calculation is inconclusive. If this this is already the top line, the computed permission is ''P''; STOP.  Otherwise, move to the line above and go to step 2.


Notice that the algorithm stops when either (1) a conclusive result is obtained, or (2) the top line is reached without obtaining a conclusive result.
For example, you might be a student in a course and an Authenticated user in the System context. In that case, the calculation becomes:
* Does the student role actually determine the answer? That is, is there an override or does the role definition say whether this capability is Allowed or Prevented. If so, the most specific override gives the answer.
* Otherwise, is this allowed by the Authenticated user role?


Let's take our original example, replacing the ''X'' by ''P'' to make it more interesting:
===Simple rules for using roles===


    P  A  P
If you follow the following guidelines, then the result of has_capability will always follow your intuitive expectations. (If you have a real-life situation where it is not possible to stick to these guidelines, then please post about it in the [http://moodle.org/mod/forum/view.php?id=6826 Roles and Capabilities forum].)
          A
    P  A  P
    A    P
      P  A
    --------
      ?  


Now carry out the steps of the algorithm
* When you define a role, just use permissions Allow or Not set (unless you actually need Prohibit).
* When you override permissions, only use permissions Allow and Prevent where you actually need them. Leave everything else set to inherit.
* Assign each user at most one role in each context (except, perhaps, in the System context).


* There are two permissions on line 5
===When to use prohibit===
* Since ''P + A = 0'', the result is inconclusive and we must look at line 4.
* There are two permissions on line 4.
* Since ''A + P = 0'', the result is inconclusive and we must look at line 3.
* There are three permissions on line 3.
* Since ''A + P + P = -1'' we have a conclusive result! The computed permission is ''P''.


    P  A  P
Prohibit is designed for one particular situation.
          A
    P  A  P
    A    P
      P  A
    --------
      P      <----- computed permission


If the computed permission had been ''A'', the function would have returned ''true'' without further ado, allowing the user to perform the action.
Suppose a particular user has posted some inappropriate content in a forum. While you investigate what happened, and possibly for a disciplinary period after that, you want to prevent that user from posting anything else.


However if the computed permission is ''P'' or ''X'', the function does not immediately return ''false''. Rather, it tests if the user has ''moodle/site:doanything = Allow'' (since this permission trumps all others). The function does this by calling itself:
To do this, you create a special 'No posting' role, where a range of capabilities like mod/forum:replypost are set to Prohibit. Then you assign that role to that bad user in the system context. That will ensure that, no matter how the other roles are define, or what role overrides have been set, that user will not be able to post to any forums.


        final result = has_capability(moodle/site:doanything,CONTEXT, USER);
==Some practical examples==
 
TODO
 
Checks whether the current logged in user can update a course
<pre>
$course = get_record('course', 'id', optional_param('id',1));
$context = get_context_instance(CONTEXT_COURSE, $course->id);
if (has_capability('moodle/course:update', $context)) {
  /** do stuff here */
}
</pre>


==See also==
==See also==
*Using Moodle [http://moodle.org/mod/forum/discuss.php?d=90140 Logged in: what role am I?] and [http://moodle.org/mod/forum/discuss.php?d=66782 What happens if a user has multiple roles in a course?] forum discussions
 
Forum threads:
* [http://moodle.org/mod/forum/discuss.php?d=90140 Logged in: what role am I?]
* [http://moodle.org/mod/forum/discuss.php?d=66782 What happens if a user has multiple roles in a course?]
 
* [[Development:Roles_administration_improvements_for_Moodle_2.0|Roles administration improvements for Moodle 2.0]]
* [[The rolesdebug.php roles debugging script]]


[[Category:Roles]]
[[Category:Roles]]


[[fr:Comment les permissions sont calculées ?]]
[[fr:Comment les permissions sont calculées ?]]
[[cs:Jak se vypočítávají oprávnění]]

Latest revision as of 02:35, 30 July 2010


A frequently asked question is, "What are my permissions in this context?". This article attempts to explain how Moodle answers that question. The article is written for non-programmers as well as programmers. It describes what the function does, not how it does it. If you are a programmer and want to see the how, look at the functions has_capability_in_accessdata and has_capability() in lib/accesslib.php.

Incidentally, you will be able generate permission tables like the ones in this article using the 'Explain' links on the new Check permissions page in Moodle 2.0. In earlier version, you can install the rolesdebug.php roles debugging script.


Clarifying the question

Let us refine the question "What are my permissions in this context?"

Naturally, my can be any user that Moodle knows about. If you don't specify a particular user, it will default to the currently logged in user.

Permissions can be broken down into a computed permissions of true or false for each capability. The different capabilities are completely independant (apart from the magic 'moodle/site:doanything' capability which will be explained later).

A context is a part of a Moodle site. For example a course, a course category, an activity, or so on. Contexts are nested, so an activity will be in a course, which will be in one or more categories, which will be in the whole system. The most specific context that you are in is the most important, and is the one that should be used when asking the question. The other, less-specific contexts that contain this one also influence the result.

So, while our original question was "What are my permissions in this context?" the question Moodle will answer is "Does user $user have capability $capability in context $context?" and the answer will be 'Yes' or 'No'.


The calculation

As explained in the previous section, we want to know whether has_capability($capability, $context, $user) returns true or false.

In order to calculate the answer, Moodle needs to combine various pieces of data.

Data used by the function

Relevant contexts

To simplify the explanation, let us work with a particular example. Suppose that user $user wants to reply to a forum post ($capability is 'mod/forum:replypost') in a particular forum. And suppose that the forum is in a course in Subcategory B which is in Category A in this Moodle site. That is, the relevant contexts are:

      System
        |
    Category A
        |					      
   Subcategory B
        |
      Course
        |
      Forum  <--- the user is here

Role assignments

All the roles that the user has been assigned in all the relevant contexts will influence the outcome of the has_capability question.

A natural example would be that a user has the role 'Student' assigned in context 'Course', and role 'Authenticated User' assigned in context System.

However, our example is going to be unnatural and complex, in order to demonstrate all the possible complexities. In our example the user has

  • Role R1 in context System
  • Roles R2 and R3 in context Subcategory B
  • Roles R1 and R4 in context Forum

Role definitions

Naturally, the definition of each role affects the outcome of has_capability. (Role definitions are edited at Administration ► Users ► Permissions ► Define roles.) The role definition sets a permissions of 'Not set', 'Allow', 'Prevent' or 'Prohibit' for each capability.

As mentioned above, different capabilities are independent, so, for example, we only need to specify the settings for the 'mod/forum:replypost' capability.

  • For role R1, 'mod/forum:replypost' is set to Allow.
  • For roles R2 and R3, 'mod/forum:replypost' is Not set.
  • For role R4, 'mod/forum:replypost' is set to Prevent.

Remember, this is an intentionally complex and unnatural example.

Permission overrides

In Moodle you can override the permissions for a role in a particular context. You can think of that as changing the definition of the role in that context. An example would be "In this category of courses, we want to prevent students from posting to forums." In the absence of an override to a different permission, you can imagine that there is an override of 'Inherit' which means use the permission from higher up the chain of contexts.

In our ongoing example, we will assume the following overrides have been set up:

  • In context Course,
    • for role R2, the permissions for 'mod/forum:replypost' is overridden to Prevent
    • for role R3, the permissions for 'mod/forum:replypost' is overridden to Allow.

Representing the data in tabular form

All the data mentioned in the previous section is best seen by writing it in a table.

In the table, there will be one row for each context, and at the start of each row, we write the name of the roles assigned in that context.

And there will also be one column for each context, and in that column we write any permission overrides for the roles in each row.

Except that in the column that represents the System context, we write the permissions from the role definition.

Normally, we think of contexts like folders in a file system, with the System context at the top, and the Forum context at the bottom. However, for this table, it turns out to be simpler later if we reverse the normal order, and put the Forum context in the first row and column, and the System context at the end.

The table for the example we have been building up looks like this:

Role calc table1.png

The calculation

The calculation proceeds by working through the table in normal reading order, left to right, top to bottom. (That is why we put the Forum context first and the System context last.)

  1. First, look through the entire table and see if there are any Prohibit permissions anywhere. If there are, stop. The final answer is false - the user does not have this capability.
  2. If there are no Prohibits, start at the beginning of the first row with role assignments, and go along until you get to a cell containing 'Allow' and/or 'Prevent'. In this cell,
    • If there are more Allows than Prevents, stop. The answer is true - the user has this capability.
    • If there are more Prevents than Allows, stop. The answer is false - the user does not have this capability.
    • If the number of Prevents and Allows is equal, jump down to the start of the next row with role assignments, and repeat this step 2.
  3. If you get to the end of the table without passing a cell with different numbers of Prevents and Allows, then the answer is false - the user does not have this capability.

Calculating the answer to our example

1. There are no Prohibits anywhere, so proceed to step 2. 2a. Work along the Forum row. We get to the last column. There are an equal number of Prevents and Allows here, so jump down to the start of the next row with role assignments. 2b. Work along the Subcategory B row. We get to the second column that corresponds to the overrides in the Course context. There are an equal number of Prevents and Allows here, so jump down to the start of the next row with role assignments. 2c. Work along the System context row. We get to the last column. There are more allows than prevents here, so the final answer is Yes, this user can reply to a post in this forum.

The path the algorithm takes is shown by the path in this diagram:

Role calc table2.png

Some variations to our example

TODO

Does this calculation make sense?

In almost every situation, the complex tie-breaking rules will not be required. Instead, the rules above will just calculate the answer you would expect if you don't think about it too deeply.

For example, you might be a student in a course and an Authenticated user in the System context. In that case, the calculation becomes:

  • Does the student role actually determine the answer? That is, is there an override or does the role definition say whether this capability is Allowed or Prevented. If so, the most specific override gives the answer.
  • Otherwise, is this allowed by the Authenticated user role?

Simple rules for using roles

If you follow the following guidelines, then the result of has_capability will always follow your intuitive expectations. (If you have a real-life situation where it is not possible to stick to these guidelines, then please post about it in the Roles and Capabilities forum.)

  • When you define a role, just use permissions Allow or Not set (unless you actually need Prohibit).
  • When you override permissions, only use permissions Allow and Prevent where you actually need them. Leave everything else set to inherit.
  • Assign each user at most one role in each context (except, perhaps, in the System context).

When to use prohibit

Prohibit is designed for one particular situation.

Suppose a particular user has posted some inappropriate content in a forum. While you investigate what happened, and possibly for a disciplinary period after that, you want to prevent that user from posting anything else.

To do this, you create a special 'No posting' role, where a range of capabilities like mod/forum:replypost are set to Prohibit. Then you assign that role to that bad user in the system context. That will ensure that, no matter how the other roles are define, or what role overrides have been set, that user will not be able to post to any forums.

Some practical examples

TODO

Checks whether the current logged in user can update a course

$course = get_record('course', 'id', optional_param('id',1)); 
$context = get_context_instance(CONTEXT_COURSE, $course->id);
if (has_capability('moodle/course:update', $context)) {
  /** do stuff here */
}

See also

Forum threads: