Merge branch 'MDL-51632_echo_url' of git://github.com/moodlerooms/moodle
[moodle.git] / course / loginas.php
blob9feeec58e0519e36272f078ab2ce69f381ee4095
1 <?php
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));
11 $PAGE->set_url($url);
13 // Reset user back to their real self if needed, for security reasons you need to log out and log in again.
14 if (\core\session\manager::is_loggedinas()) {
15 require_sesskey();
16 require_logout();
18 // We can not set wanted URL here because the session is closed.
19 redirect(new moodle_url($url, array('redirect'=>1)));
22 if ($redirect) {
23 if ($id and $id != SITEID) {
24 $SESSION->wantsurl = "$CFG->wwwroot/course/view.php?id=".$id;
25 } else {
26 $SESSION->wantsurl = "$CFG->wwwroot/";
29 redirect(get_login_url());
32 // Try log in as this user.
33 $userid = required_param('user', PARAM_INT);
35 require_sesskey();
36 $course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST);
38 // User must be logged in.
40 $systemcontext = context_system::instance();
41 $coursecontext = context_course::instance($course->id);
43 require_login();
45 if (has_capability('moodle/user:loginas', $systemcontext)) {
46 if (is_siteadmin($userid)) {
47 print_error('nologinas');
49 $context = $systemcontext;
50 $PAGE->set_context($context);
51 } else {
52 require_login($course);
53 require_capability('moodle/user:loginas', $coursecontext);
54 if (is_siteadmin($userid)) {
55 print_error('nologinas');
57 if (!is_enrolled($coursecontext, $userid)) {
58 print_error('usernotincourse');
60 $context = $coursecontext;
62 // Check if course has SEPARATEGROUPS and user is part of that group.
63 if (groups_get_course_groupmode($course) == SEPARATEGROUPS &&
64 !has_capability('moodle/site:accessallgroups', $context)) {
65 $samegroup = false;
66 if ($groups = groups_get_all_groups($course->id, $USER->id)) {
67 foreach ($groups as $group) {
68 if (groups_is_member($group->id, $userid)) {
69 $samegroup = true;
70 break;
74 if (!$samegroup) {
75 print_error('nologinas');
80 // Login as this user and return to course home page.
81 \core\session\manager::loginas($userid, $context);
82 $newfullname = fullname($USER, true);
84 $strloginas = get_string('loginas');
85 $strloggedinas = get_string('loggedinas', '', $newfullname);
87 $PAGE->set_title($strloggedinas);
88 $PAGE->set_heading($course->fullname);
89 $PAGE->navbar->add($strloggedinas);
90 notice($strloggedinas, "$CFG->wwwroot/course/view.php?id=$course->id");