public static function terminate_current() {
        global $DB;

        if (!self::$sessionactive) {
            self::init_empty_session();
            self::$sessionactive = false;
            return;
        }

        try {
            $DB->delete_records('external_tokens', array('sid'=>session_id(), 'tokentype'=>EXTERNAL_TOKEN_EMBEDDED));
        } catch (\Exception $ignored) {
            // Probably install/upgrade - ignore this problem.
        }

        // Initialize variable to pass-by-reference to headers_sent(&$file, &$line).
        $file = null;
        $line = null;
        if (headers_sent($file, $line)) {
            error_log('Cannot terminate session properly - headers were already sent in file: '.$file.' on line '.$line);
        }

        // Write new empty session and make sure the old one is deleted.
        $sid = session_id();
        session_regenerate_id(true);
        $DB->delete_records('sessions', array('sid'=>$sid));
        self::init_empty_session();
        self::add_session_record($_SESSION['USER']->id); // Do not use $USER here because it may not be set up yet.
        session_write_close();
        self::$sessionactive = false;
    }