Reputation: 4464
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.
Upvotes: 10
Views: 23104
Reputation: 1
include the library 'accesslib.php' and then use the 'is_siteadmin()' function
Upvotes: 0
Reputation: 27465
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";
}
Upvotes: 10
Reputation: 131
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.
Upvotes: 1
Reputation: 139
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);
Upvotes: 6
Reputation: 307
$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
Upvotes: 9
Reputation: 950
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
Upvotes: 3