Moodle context and roles

One thing which I found myself constantly having to look up when I started developing with Moodle was what all the Context and Role IDs were.

So here is a quick list of them in case it helps anyone:

Contexts Levels

CONTEXT_SYSTEM = 10

CONTEXT_USER = 30

CONTEXT_COURSECAT = 40

CONTEXT_COURSE = 50

CONTEXT_MODULE = 70

CONTEXT_BLOCK = 80

These values are defined in moodle/lib/accesslib around line 140. They represent the `contextlevel` value you will find in the `mdl_context` database table. Basically what that means is, if the `mdl_context` record has a level of 30, it is the context of a user (where the user’s id is the `instanceid`), if the `mdl_context` record has a level of 50, it’s the context of a particular course (where the course id is the `instanceid`), etc…

Roles

These can be found in the `mdl_roles` table, and by default the values you will have are:

1 = Admin

2 = Course Creator

3 = Teacher

4 = Non-Editing Teacher

5 = Student

6 = Guest

7 = Authenticated user

Though you may have more if you have created your own roles, for example you may have a “Tutor”/”Personal Tutor” role if you are using the popular Personal Learning Plan block.

The way these roles work is that every time a user is assigned to a course, there is a record made in the `mdl_role_assignment` table. This record is in the format of:

`roleid` = (A valid role id as defined above, so let’s say “5″ for this example).

`contextid` = (A valid `id` from the `mdl_context` table)

`userid` = (The user’s id from `mdl_user`)

The rest of the fields aren’t too important really, at least not for this explanation.

So let’s look at a couple of examples of how we could use this information and the two tables (`mdl_context` and `mdl_role_assignments`).

Let’s say we had a course with the id of “3″ and we want to find all the students assigned to this course. If the course was properly created in Moodle, then there will be a record for it in the `mdl_context` table, so all we have to do is join that with the `mdl_role_assignments` table, where we know that students will have the `roleid` of 5, e.g:

SELECT
    u.firstname, u.lastname, u.username
FROM
    mdl_user u
INNER JOIN
    mdl_role_assignments r ON r.userid = u.id
INNER JOIN
    mdl_context c ON c.id = r.contextid
WHERE
    c.instanceid = 3
    AND r.roleid = 5

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *