public static function loginas($userid, \context $context, $generateevent = true) {
        global $USER;

        if (self::is_loggedinas()) {
            return;
        }

        // Switch to fresh new $_SESSION.
        $_SESSION = array();
        $_SESSION['REALSESSION'] = clone($GLOBALS['SESSION']);
        $GLOBALS['SESSION'] = new \stdClass();
        $_SESSION['SESSION'] =& $GLOBALS['SESSION'];

        // Create the new $USER object with all details and reload needed capabilities.
        $_SESSION['REALUSER'] = clone($GLOBALS['USER']);
        $user = get_complete_user_data('id', $userid);
        $user->realuser       = $_SESSION['REALUSER']->id;
        $user->loginascontext = $context;

        // Let enrol plugins deal with new enrolments if necessary.
        enrol_check_plugins($user);

        if ($generateevent) {
            // Create event before $USER is updated.
            $event = \core\event\user_loggedinas::create(
                array(
                    'objectid' => $USER->id,
                    'context' => $context,
                    'relateduserid' => $userid,
                    'other' => array(
                        'originalusername' => fullname($USER, true),
                        'loggedinasusername' => fullname($user, true)
                    )
                )
            );
        }

        // Set up global $USER.
        \core\session\manager::set_user($user);

        if ($generateevent) {
            $event->trigger();
        }
    }