2 // Allows a teacher/admin to login as another user (in stealth mode)
4 require_once('../config.php');
5 require_once('lib.php');
7 $id = optional_param('id', SITEID
, PARAM_INT
); // course id
8 $redirect = optional_param('redirect', 0, PARAM_BOOL
);
10 $url = new moodle_url('/course/loginas.php', array('id'=>$id));
13 /// Reset user back to their real self if needed, for security reasons you need to log out and log in again
14 if (session_is_loggedinas()) {
18 // We can not set wanted URL here because the session is closed.
19 redirect(new moodle_url($url, array('redirect'=>1)));
23 if ($id and $id != SITEID
) {
24 $SESSION->wantsurl
= "$CFG->wwwroot/course/view.php?id=".$id;
26 $SESSION->wantsurl
= "$CFG->wwwroot/";
29 redirect(get_login_url());
32 ///-------------------------------------
33 /// We are trying to log in as this user in the first place
35 $userid = required_param('user', PARAM_INT
); // login as this user
38 $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST
);
40 /// User must be logged in
42 $systemcontext = context_system
::instance();
43 $coursecontext = context_course
::instance($course->id
);
47 if (has_capability('moodle/user:loginas', $systemcontext)) {
48 if (is_siteadmin($userid)) {
49 print_error('nologinas');
51 $context = $systemcontext;
52 $PAGE->set_context($context);
54 require_login($course);
55 require_capability('moodle/user:loginas', $coursecontext);
56 if (is_siteadmin($userid)) {
57 print_error('nologinas');
59 if (!is_enrolled($coursecontext, $userid)) {
60 print_error('usernotincourse');
62 $context = $coursecontext;
64 // Check if course has SEPARATEGROUPS and user is part of that group.
65 if (groups_get_course_groupmode($course) == SEPARATEGROUPS
&&
66 !has_capability('moodle/site:accessallgroups', $context)) {
68 if ($groups = groups_get_all_groups($course->id
, $USER->id
)) {
69 foreach ($groups as $group) {
70 if (groups_is_member($group->id
, $userid)) {
77 print_error('nologinas');
82 /// Login as this user and return to course home page.
83 $oldfullname = fullname($USER, true);
84 session_loginas($userid, $context);
85 $newfullname = fullname($USER, true);
87 add_to_log($course->id
, "course", "loginas", "../user/view.php?id=$course->id&user=$userid", "$oldfullname -> $newfullname");
89 $strloginas = get_string('loginas');
90 $strloggedinas = get_string('loggedinas', '', $newfullname);
92 $PAGE->set_title($strloggedinas);
93 $PAGE->set_heading($course->fullname
);
94 $PAGE->navbar
->add($strloggedinas);
95 notice($strloggedinas, "$CFG->wwwroot/course/view.php?id=$course->id");