Get user roles/capabilities

Get user roles/capabilities

di Sami Cooper -
Numero di risposte: 8
I require a function to output the user 'roles' as an array, regardless of what page they are on. Examples:

  • If they are a student on any course page, flag that they are a student.
  • If they are a site admin flag that they are a site admin.
  • If they are a teacher on any course, flag that they are a teacher
  • If they are a [insert any role] flag that they are a [*role]
  • If they have multiple roles assign flag each role in the array.
  • If the user is a non-editing teacher on one course and a student on another, but also a site admin, flag all three
I'm hoping that there is a non course context function and that I do not have to loop through every course to check their roles/capabilities, but if I have to how would I do that?
Media dei voti: -
In riposta a Sami Cooper

Re: Get user roles/capabilities

di Tim Hunt -
Immagine Core developers Immagine Documentation writers Immagine Particularly helpful Moodlers Immagine Peer reviewers Immagine Plugin developers
This feature exists in Moodle, but I don't onw how you get there through the navigtion (I think it might have got lost. I think there should be a link to this from the user's profile - with the link only appearing to people like admins who are allowed to seet it.)

Anyway, you can access it directly by typing a URL likehttps://moodle.example.com/admin/roles/usersroles.php?courseid=1&userid=12345

You can access that if you have any of the capabilities 'moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override' or 'moodle/role:manage' in the user's context. (Also, I don't know why courseid is required in the URL, but it is. However, passing 1 (site id) seems to work.)
In riposta a Tim Hunt

Re: Get user roles/capabilities

di Amanda Doughty -
Immagine Core developers Immagine Plugin developers
Weirdly you get to it from 'Preferences' on the user profile page.
In riposta a Tim Hunt

Re: Get user roles/capabilities

di Sami Cooper -
Thanks. I'll try to make sense of the script within /admin/roles/usersroles.php and wrap it in a function that outputs what I need (probably an array of each role assigned to the user).
In riposta a Sami Cooper

Re: Get user roles/capabilities

di Sami Cooper -
OK, this did it:

require_once('/var/www/html/moodle/config.php' );
global $USER;

$sql = "SELECT ra.id, ra.userid, ra.contextid, ra.roleid, r.name, r.shortname
FROM {role_assignments} ra
JOIN {context} c ON ra.contextid = c.id
JOIN {role} r ON ra.roleid = r.id
WHERE ra.userid = ?
ORDER BY contextlevel DESC, contextid ASC, r.sortorder ASC";
$roleassignments = $DB->get_records_sql($sql, array($USER->id));

$user_roles = array();
foreach($roleassignments as $k => $v){
$user_roles[$v->roleid] = $v->name;
}

Now I just need to find out if they are a site admin and add that to the array.