简体   繁体   中英

Moodle how to find out the role of the logged in user

How to get context/role of logged in user in moodle? I am trying to implement a context-aware block. The block would suggest the right quizzes to its users based on their moods.

Role can be a teacher, student, teacher assistant or admin. I have already found the get_context_instance() & has_compatibility() functions, but I don't know how to use them for this purpose.

checking user is an admin or not

$admins = get_admins();
$isadmin = false;
foreach($admins as $admin) {
    if ($USER->id == $admin->id) {
        $isadmin = true;
        break;
    }
}

use the result for functions

if ($isadmin) {
    echo "you are an admin";    
} else { 
    echo "you are not an amidn";
}
$context = get_context_instance (CONTEXT_SYSTEM);
$roles = get_user_roles($context, $USER->id, false);
$role = key($roles);
$roleid = $roles[$role]->roleid;

it works to me

In Moodle 2.x you may use the function get_user_roles and this will return list of roles assigned to a particular user in context of course or site or module.

$context = get_context_instance(CONTEXT_COURSE, $courseid, true);
$roles = get_user_roles($context, $USER->id, true);

You can also get the roles in context of module.

$context = get_context_instance(CONTEXT_MODULE, $cm->id, true);
$roles = get_user_roles($context, $USER->id, true);

In moodle the roles are based on the context. I think this code snippet will be helpful for you.

global $COURSE, $USER;

$context = get_context_instance(CONTEXT_COURSE,$COURSE->id);

if (has_capability('moodle/legacy:student', $context, $USER->id, false) ) {
echo "Student";
}

if (has_capability('moodle/legacy:editingteacher', $context, $USER->id, false)) {
echo "is Teacher<br/>";
}
if (has_capability('moodle/legacy:admin', $context, $USER->id, false)) {
echo "is ADMIN<br/>";
}

Bear in mind that it is perfectly possible (but unlikely) to have a Moodle site without the default Student and Teacher roles

You can test for which roles a user has in the following manner:

if (user_has_role_assignment($user1->id, $roleid))
    echo "User is a teacher in some course";

The role id of a teacher is usually 3, and the role id of a student is usually 5, but you can test this looking at the table in Site Administration-> Users -> Permissions -> Define Roles

Please note that one user can have various roles. The function user_has_role_assignment seems to test of which roles he has system wide.

包括库'accesslib.php',然后使用'is_siteadmin()'函数

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM