function sqimap_login($username, $password, $imap_server_address, $imap_port, $hide)
{
    global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech;
    if (!isset($onetimepad) || empty($onetimepad)) {
        sqgetglobalvar('onetimepad', $onetimepad, SQ_SESSION);
    }
    $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
    $host = $imap_server_address;
    if ($use_imap_tls == true and check_php_version(4, 3) and extension_loaded('openssl')) {
        /* Use TLS by prefixing "tls://" to the hostname */
        $imap_server_address = 'tls://' . $imap_server_address;
    }
    $imap_stream = fsockopen($imap_server_address, $imap_port, $error_number, $error_string, 15);
    /* Do some error correction */
    if (!$imap_stream) {
        if (!$hide) {
            set_up_language($squirrelmail_language, true);
            require_once SM_PATH . 'functions/display_messages.php';
            $string = sprintf(_("Error connecting to IMAP server: %s.") . "<br>\r\n", $imap_server_address) . "{$error_number} : {$error_string}<br>\r\n";
            logout_error($string, $color);
        }
        exit;
    }
    $server_info = fgets($imap_stream, 1024);
    /* Decrypt the password */
    $password = OneTimePadDecrypt($password, $onetimepad);
    if ($imap_auth_mech == 'cram-md5' or $imap_auth_mech == 'digest-md5') {
        // We're using some sort of authentication OTHER than plain or login
        $tag = sqimap_session_id(false);
        if ($imap_auth_mech == 'digest-md5') {
            $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
        } elseif ($imap_auth_mech == 'cram-md5') {
            $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
        }
        fputs($imap_stream, $query);
        $answer = sqimap_fgets($imap_stream);
        // Trim the "+ " off the front
        $response = explode(" ", $answer, 3);
        if ($response[0] == '+') {
            // Got a challenge back
            $challenge = $response[1];
            if ($imap_auth_mech == 'digest-md5') {
                $reply = digest_md5_response($username, $password, $challenge, 'imap', $host);
            } elseif ($imap_auth_mech == 'cram-md5') {
                $reply = cram_md5_response($username, $password, $challenge);
            }
            fputs($imap_stream, $reply);
            $read = sqimap_fgets($imap_stream);
            if ($imap_auth_mech == 'digest-md5') {
                // DIGEST-MD5 has an extra step..
                if (substr($read, 0, 1) == '+') {
                    // OK so far..
                    fputs($imap_stream, "\r\n");
                    $read = sqimap_fgets($imap_stream);
                }
            }
            $results = explode(" ", $read, 3);
            $response = $results[1];
            $message = $results[2];
        } else {
            // Fake the response, so the error trap at the bottom will work
            $response = "BAD";
            $message = 'IMAP server does not appear to support the authentication method selected.';
            $message .= '  Please contact your system administrator.';
        }
    } elseif ($imap_auth_mech == 'login') {
        // Original IMAP login code
        $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
        $read = sqimap_run_command($imap_stream, $query, false, $response, $message);
    } elseif ($imap_auth_mech == 'plain') {
        /* Replace this with SASL PLAIN if it ever gets implemented */
        $response = "BAD";
        $message = 'SquirrelMail does not support SASL PLAIN yet. Rerun conf.pl and use login instead.';
    } else {
        $response = "BAD";
        $message = "Internal SquirrelMail error - unknown IMAP authentication method chosen.  Please contact the developers.";
    }
    /* If the connection was not successful, lets see why */
    if ($response != 'OK') {
        if (!$hide) {
            if ($response != 'NO') {
                /* "BAD" and anything else gets reported here. */
                $message = htmlspecialchars($message);
                set_up_language($squirrelmail_language, true);
                require_once SM_PATH . 'functions/display_messages.php';
                if ($response == 'BAD') {
                    $string = sprintf(_("Bad request: %s") . "<br>\r\n", $message);
                } else {
                    $string = sprintf(_("Unknown error: %s") . "<br>\n", $message);
                }
                if (isset($read) && is_array($read)) {
                    $string .= '<br>' . _("Read data:") . "<br>\n";
                    foreach ($read as $line) {
                        $string .= htmlspecialchars($line) . "<br>\n";
                    }
                }
                error_box($string, $color);
                exit;
            } else {
                /*
                 * If the user does not log in with the correct
                 * username and password it is not possible to get the
                 * correct locale from the user's preferences.
                 * Therefore, apply the same hack as on the login
                 * screen.
                 *
                 * $squirrelmail_language is set by a cookie when
                 * the user selects language and logs out
                 */
                set_up_language($squirrelmail_language, true);
                include_once SM_PATH . 'functions/display_messages.php';
                sqsession_destroy();
                logout_error(_("Unknown user or password incorrect."));
                exit;
            }
        } else {
            exit;
        }
    }
    return $imap_stream;
}
예제 #2
0
파일: bug_report.php 프로젝트: jprice/EHCP
$body_top = "I subscribe to the squirrelmail-users mailing list.\n" . "  [ ]  True - No need to CC me when replying\n" . "  [ ]  False - Please CC me when replying\n" . "\n" . "This bug occurs when I ...\n" . "  ... view a particular message\n" . "  ... use a specific plugin/function\n" . "  ... try to do/view/use ....\n" . "\n\n\n" . "The description of the bug:\n\n\n" . "I can reproduce the bug by:\n\n\n" . "(Optional) I got bored and found the bug occurs in:\n\n\n" . "(Optional) I got really bored and here's a fix:\n\n\n" . "----------------------------------------------\n" . "\nMy browser information:\n" . '  ' . $HTTP_USER_AGENT . "\n";
if (isset($browser)) {
    $body_top .= "  get_browser() information (List)\n" . Show_Array((array) $browser);
}
$body_top .= "\nMy web server information:\n" . "  PHP Version " . phpversion() . "\n" . "  PHP Extensions (List)\n" . Show_Array(get_loaded_extensions()) . "\nSquirrelMail-specific information:\n" . "  Version:  {$version}\n" . "  Plugins (List)\n" . Show_Array($plugins);
if (isset($ldap_server) && $ldap_server[0] && !extension_loaded('ldap')) {
    $warning = 1;
    $warnings['ldap'] = "LDAP server defined in SquirrelMail config, " . "but the module is not loaded in PHP";
    $corrections['ldap'][] = "Reconfigure PHP with the option '--with-ldap'";
    $corrections['ldap'][] = "Then recompile PHP and reinstall";
    $corrections['ldap'][] = "-- OR --";
    $corrections['ldap'][] = "Reconfigure SquirrelMail to not use LDAP";
}
$body = "\nMy IMAP server information:\n" . "  Server type:  {$imap_server_type}\n";
/* check imap server's mapping */
$imapServerAddress = sqimap_get_user_server($imapServerAddress, $username);
/*
 * add tls:// prefix, if tls is used.
 * No need to check for openssl.
 * User can't use SquirrelMail if this part is misconfigured
 */
if ($use_imap_tls == true) {
    $imapServerAddress = 'tls://' . $imapServerAddress;
}
$imap_stream = fsockopen($imapServerAddress, $imapPort, $error_number, $error_string);
$server_info = fgets($imap_stream, 1024);
if ($imap_stream) {
    // SUPRESS HOST NAME
    $list = explode(' ', $server_info);
    $list[2] = '[HIDDEN]';
    $server_info = implode(' ', $list);
예제 #3
0
/**
 * Logs the user into the imap server.  If $hide is set, no error messages
 * will be displayed.  This function returns the imap connection handle.
 */
function sqimap_login($username, $password, $imap_server_address, $imap_port, $hide)
{
    global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech, $sqimap_capabilities;
    if (!isset($onetimepad) || empty($onetimepad)) {
        sqgetglobalvar('onetimepad', $onetimepad, SQ_SESSION);
    }
    if (!isset($sqimap_capabilities)) {
        sqgetglobalvar('sqimap_capabilities', $capability, SQ_SESSION);
    }
    $host = $imap_server_address;
    $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
    $imap_stream = sqimap_create_stream($imap_server_address, $imap_port, $use_imap_tls);
    /* Decrypt the password */
    //$password = OneTimePadDecrypt($password, $onetimepad);
    if ($imap_auth_mech == 'cram-md5' or $imap_auth_mech == 'digest-md5') {
        // We're using some sort of authentication OTHER than plain or login
        $tag = sqimap_session_id(false);
        if ($imap_auth_mech == 'digest-md5') {
            $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
        } elseif ($imap_auth_mech == 'cram-md5') {
            $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
        }
        fputs($imap_stream, $query);
        $answer = sqimap_fgets($imap_stream);
        // Trim the "+ " off the front
        $response = explode(" ", $answer, 3);
        if ($response[0] == '+') {
            // Got a challenge back
            $challenge = $response[1];
            if ($imap_auth_mech == 'digest-md5') {
                $reply = digest_md5_response($username, $password, $challenge, 'imap', $host);
            } elseif ($imap_auth_mech == 'cram-md5') {
                $reply = cram_md5_response($username, $password, $challenge);
            }
            fputs($imap_stream, $reply);
            $read = sqimap_fgets($imap_stream);
            if ($imap_auth_mech == 'digest-md5') {
                // DIGEST-MD5 has an extra step..
                if (substr($read, 0, 1) == '+') {
                    // OK so far..
                    fputs($imap_stream, "\r\n");
                    $read = sqimap_fgets($imap_stream);
                }
            }
            $results = explode(" ", $read, 3);
            $response = $results[1];
            $message = $results[2];
        } else {
            // Fake the response, so the error trap at the bottom will work
            $response = "BAD";
            $message = 'IMAP server does not appear to support the authentication method selected.';
            $message .= '  Please contact your system administrator.';
        }
    } elseif ($imap_auth_mech == 'login') {
        // Original IMAP login code
        $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
        $read = sqimap_run_command($imap_stream, $query, false, $response, $message);
    } elseif ($imap_auth_mech == 'plain') {
        /***
         * SASL PLAIN
         *
         *  RFC 2595 Chapter 6
         *
         *  The mechanism consists of a single message from the client to the
         *  server.  The client sends the authorization identity (identity to
         *  login as), followed by a US-ASCII NUL character, followed by the
         *  authentication identity (identity whose password will be used),
         *  followed by a US-ASCII NUL character, followed by the clear-text
         *  password.  The client may leave the authorization identity empty to
         *  indicate that it is the same as the authentication identity.
         *
         **/
        $tag = sqimap_session_id(false);
        $sasl = isset($capability['SASL-IR']) && $capability['SASL-IR'] ? true : false;
        $auth = base64_encode("{$username}{$username}{$password}");
        if ($sasl) {
            // IMAP Extension for SASL Initial Client Response
            // <draft-siemborski-imap-sasl-initial-response-01b.txt>
            $query = $tag . " AUTHENTICATE PLAIN {$auth}\r\n";
            fputs($imap_stream, $query);
            $read = sqimap_fgets($imap_stream);
        } else {
            $query = $tag . " AUTHENTICATE PLAIN\r\n";
            fputs($imap_stream, $query);
            $read = sqimap_fgets($imap_stream);
            if (substr($read, 0, 1) == '+') {
                // OK so far..
                fputs($imap_stream, "{$auth}\r\n");
                $read = sqimap_fgets($imap_stream);
            }
        }
        $results = explode(" ", $read, 3);
        $response = $results[1];
        $message = $results[2];
    } else {
        $response = "BAD";
        $message = "Internal SquirrelMail error - unknown IMAP authentication method chosen.  Please contact the developers.";
    }
    /* If the connection was not successful, lets see why */
    if ($response != 'OK') {
        if (!$hide) {
            if ($response != 'NO') {
                /* "BAD" and anything else gets reported here. */
                $message = htmlspecialchars($message);
                set_up_language($squirrelmail_language, true);
                require_once SM_PATH . 'functions/display_messages.php';
                if ($response == 'BAD') {
                    $string = sprintf(_("Bad request: %s") . "<br />\r\n", $message);
                } else {
                    $string = sprintf(_("Unknown error: %s") . "<br />\n", $message);
                }
                if (isset($read) && is_array($read)) {
                    $string .= '<br />' . _("Read data:") . "<br />\n";
                    foreach ($read as $line) {
                        $string .= htmlspecialchars($line) . "<br />\n";
                    }
                }
                error_box($string, $color);
                exit;
            } else {
                /*
                 * If the user does not log in with the correct
                 * username and password it is not possible to get the
                 * correct locale from the user's preferences.
                 * Therefore, apply the same hack as on the login
                 * screen.
                 *
                 * $squirrelmail_language is set by a cookie when
                 * the user selects language and logs out
                 */
                set_up_language($squirrelmail_language, true);
                include_once SM_PATH . 'functions/display_messages.php';
                sqsession_destroy();
                /* terminate the session nicely */
                sqimap_logout($imap_stream);
                logout_error(_("Unknown user or password incorrect."));
                exit;
            }
        } else {
            exit;
        }
    }
    return $imap_stream;
}
예제 #4
0
/**
 * Retrieve long text string containing semi-formatted (simple text
 * with newlines and spaces for indentation) SquirrelMail system
 * specs
 *
 * @return array A three-element array, the first element containing
 *               the string of system specs, the second one containing 
 *               a list of any warnings that may have occurred, keyed
 *               by a warning "type" (which is used to key the corrections
 *               array next), and the third element of which is a list
 *               of sub-arrays keyed by warning "type": the sub-arrays
 *               are lists of correction messages associated with the
 *               warnings.  The second and third return elements may
 *               be empty arrays if no warnings were found.
 *
 * @since 1.5.2
 *
 */
function get_system_specs()
{
    //FIXME: configtest and this plugin should be using the same code to generate the basic SM system specifications and setup detection
    global $imapServerAddress, $username, $imapPort, $imap_server_type, $use_imap_tls, $ldap_server;
    // load required libraries
    //
    include_once SM_PATH . 'functions/imap_general.php';
    $browscap = ini_get('browscap');
    if (!empty($browscap)) {
        $browser = get_browser();
    }
    $warnings = array();
    $corrections = array();
    sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER);
    if (!sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER)) {
        $HTTP_USER_AGENT = "Browser information is not available.";
    }
    $body_top = "My browser information:\n" . '  ' . $HTTP_USER_AGENT . "\n";
    if (isset($browser)) {
        $body_top .= "  get_browser() information (List)\n" . Show_Array((array) $browser);
    }
    $body_top .= "\nMy web server information:\n" . "  PHP Version " . phpversion() . "\n" . "  PHP Extensions (List)\n" . Show_Array(get_loaded_extensions()) . "\nSquirrelMail-specific information:\n" . "  Version:  " . SM_VERSION . "\n" . "  Plugins (List)\n" . br_show_plugins() . "\n";
    if (!empty($ldap_server[0]) && $ldap_server[0] && !extension_loaded('ldap')) {
        $warnings['ldap'] = "LDAP server defined in SquirrelMail config, " . "but the module is not loaded in PHP";
        $corrections['ldap'][] = "Reconfigure PHP with the option '--with-ldap'";
        $corrections['ldap'][] = "Then recompile PHP and reinstall";
        $corrections['ldap'][] = "-- OR --";
        $corrections['ldap'][] = "Reconfigure SquirrelMail to not use LDAP";
    }
    $body = "\nMy IMAP server information:\n" . "  Server type:  {$imap_server_type}\n";
    $imapServerAddress = sqimap_get_user_server($imapServerAddress, $username);
    $imap_stream = sqimap_create_stream($imapServerAddress, $imapPort, $use_imap_tls);
    if ($imap_stream) {
        $body .= '  Capabilities: ';
        if ($imap_capabilities = sqimap_capability($imap_stream)) {
            foreach ($imap_capabilities as $capability => $value) {
                if (is_array($value)) {
                    foreach ($value as $val) {
                        $body .= $capability . "={$val} ";
                    }
                } else {
                    $body .= $capability . (is_bool($value) ? ' ' : "={$value} ");
                }
            }
        }
        $body .= "\n";
        sqimap_logout($imap_stream);
    } else {
        $body .= "  Unable to connect to IMAP server to get information.\n";
        $warnings['imap'] = "Unable to connect to IMAP server";
        $corrections['imap'][] = "Make sure you specified the correct mail server";
        $corrections['imap'][] = "Make sure the mail server is running IMAP, not POP";
        $corrections['imap'][] = "Make sure the server responds to port {$imapPort}";
    }
    $warning_num = 0;
    if (!empty($warnings)) {
        foreach ($warnings as $key => $value) {
            if ($warning_num == 0) {
                $body_top .= "WARNINGS WERE REPORTED WITH YOUR SETUP:\n";
                $body_top = "WARNINGS WERE REPORTED WITH YOUR SETUP -- SEE BELOW\n\n{$body_top}";
            }
            $warning_num++;
            $body_top .= "\n{$value}\n";
            foreach ($corrections[$key] as $corr_val) {
                $body_top .= "  * {$corr_val}\n";
            }
        }
        $body_top .= "\n{$warning_num} warning(s) reported.\n";
        $body_top .= "----------------------------------------------\n";
    }
    $body = $body_top . $body;
    return array($body, $warnings, $corrections);
}
예제 #5
0
    $cpw_ldap_bindpw = $cpw_ldap['bindpw'];
}
if (isset($cpw_ldap['admindn'])) {
    $cpw_ldap_admindn = $cpw_ldap['admindn'];
}
if (isset($cpw_ldap['adminpw'])) {
    $cpw_ldap_adminpw = $cpw_ldap['adminpw'];
}
if (isset($cpw_ldap['userid_attr'])) {
    $cpw_ldap_userid_attr = $cpw_ldap['userid_attr'];
}
if (isset($cpw_ldap['default_crypto'])) {
    $cpw_ldap_default_crypto = $cpw_ldap['default_crypto'];
}
/** make sure that setting does not contain mapping */
$cpw_ldap_server = sqimap_get_user_server($cpw_ldap_server, $username);
/**
 * Adding plugin hooks
 */
global $squirrelmail_plugin_hooks;
$squirrelmail_plugin_hooks['change_password_dochange']['ldap'] = 'cpw_ldap_dochange';
$squirrelmail_plugin_hooks['change_password_init']['ldap'] = 'cpw_ldap_init';
/**
 * Makes sure that required functions and configuration options are set.
 */
function cpw_ldap_init()
{
    global $oTemplate, $cpw_ldap_basedn;
    // set initial value for error tracker
    $cpw_ldap_initerr = false;
    // check for ldap support in php
예제 #6
0
/**
 * Logs the user into the IMAP server.  If $hide is set, no error messages
 * will be displayed (if set to 1, just exits, if set to 2, returns FALSE).
 * This function returns the IMAP connection handle.
 * @param string $username user name
 * @param string $password password encrypted with onetimepad. Since 1.5.2
 *  function can use internal password functions, if parameter is set to
 *  boolean false.
 * @param string $imap_server_address address of imap server
 * @param integer $imap_port port of imap server
 * @param int $hide controls display connection errors:
 *                  0 = do not hide
 *                  1 = show no errors (just exit)
 *                  2 = show no errors (return FALSE)
 *                  3 = show no errors (return error string)
 * @param array $stream_options Stream context options, see config_local.php
 *                           for more details (OPTIONAL)
 * @return mixed The IMAP connection stream, or if the connection fails,
 *               FALSE if $hide is set to 2 or an error string if $hide
 *               is set to 3.
 */
function sqimap_login($username, $password, $imap_server_address, $imap_port, $hide, $stream_options = array())
{
    global $color, $squirrelmail_language, $onetimepad, $use_imap_tls, $imap_auth_mech, $sqimap_capabilities, $display_imap_login_error;
    // Note/TODO: This hack grabs the $authz argument from the session. In the short future,
    // a new argument in function sqimap_login() will be used instead.
    $authz = '';
    global $authz;
    sqgetglobalvar('authz', $authz, SQ_SESSION);
    if (!empty($authz)) {
        /* authz plugin - specific:
         * Get proxy login parameters from authz plugin configuration. If they
         * exist, they will override the current ones.
         * This is useful if we want to use different SASL authentication mechanism
         * and/or different TLS settings for proxy logins. */
        global $authz_imap_auth_mech, $authz_use_imap_tls, $authz_imapPort_tls;
        $imap_auth_mech = !empty($authz_imap_auth_mech) ? strtolower($authz_imap_auth_mech) : $imap_auth_mech;
        $use_imap_tls = !empty($authz_use_imap_tls) ? $authz_use_imap_tls : $use_imap_tls;
        $imap_port = !empty($authz_use_imap_tls) ? $authz_imapPort_tls : $imap_port;
        if ($imap_auth_mech == 'login' || $imap_auth_mech == 'cram-md5') {
            logout_error("Misconfigured Plugin (authz or equivalent):<br/>" . "The LOGIN and CRAM-MD5 authentication mechanisms cannot be used when attempting proxy login.");
            exit;
        }
    }
    /* get imap login password */
    if ($password === false) {
        /* standard functions */
        $password = sqauth_read_password();
    } else {
        /* old way. $key must be extracted from cookie */
        if (!isset($onetimepad) || empty($onetimepad)) {
            sqgetglobalvar('onetimepad', $onetimepad, SQ_SESSION);
        }
        /* Decrypt the password */
        $password = OneTimePadDecrypt($password, $onetimepad);
    }
    if (!isset($sqimap_capabilities)) {
        sqgetglobalvar('sqimap_capabilities', $sqimap_capabilities, SQ_SESSION);
    }
    $host = $imap_server_address;
    $imap_server_address = sqimap_get_user_server($imap_server_address, $username);
    $imap_stream = sqimap_create_stream($imap_server_address, $imap_port, $use_imap_tls, $stream_options);
    if ($imap_auth_mech == 'cram-md5' or $imap_auth_mech == 'digest-md5') {
        // We're using some sort of authentication OTHER than plain or login
        $tag = sqimap_session_id(false);
        if ($imap_auth_mech == 'digest-md5') {
            $query = $tag . " AUTHENTICATE DIGEST-MD5\r\n";
        } elseif ($imap_auth_mech == 'cram-md5') {
            $query = $tag . " AUTHENTICATE CRAM-MD5\r\n";
        }
        fputs($imap_stream, $query);
        $answer = sqimap_fgets($imap_stream);
        // Trim the "+ " off the front
        $response = explode(" ", $answer, 3);
        if ($response[0] == '+') {
            // Got a challenge back
            $challenge = $response[1];
            if ($imap_auth_mech == 'digest-md5') {
                $reply = digest_md5_response($username, $password, $challenge, 'imap', $host, $authz);
            } elseif ($imap_auth_mech == 'cram-md5') {
                $reply = cram_md5_response($username, $password, $challenge);
            }
            fputs($imap_stream, $reply);
            $read = sqimap_fgets($imap_stream);
            if ($imap_auth_mech == 'digest-md5') {
                // DIGEST-MD5 has an extra step..
                if (substr($read, 0, 1) == '+') {
                    // OK so far..
                    fputs($imap_stream, "\r\n");
                    $read = sqimap_fgets($imap_stream);
                }
            }
            $results = explode(" ", $read, 3);
            $response = $results[1];
            $message = $results[2];
        } else {
            // Fake the response, so the error trap at the bottom will work
            $response = "BAD";
            $message = 'IMAP server does not appear to support the authentication method selected.';
            $message .= '  Please contact your system administrator.';
        }
    } elseif ($imap_auth_mech == 'login') {
        // Original IMAP login code
        $query = 'LOGIN "' . quoteimap($username) . '" "' . quoteimap($password) . '"';
        $read = sqimap_run_command($imap_stream, $query, false, $response, $message);
    } elseif ($imap_auth_mech == 'plain') {
        /***
         * SASL PLAIN, RFC 4616 (updates 2595)
         *
         * The mechanism consists of a single message, a string of [UTF-8]
         * encoded [Unicode] characters, from the client to the server.  The
         * client presents the authorization identity (identity to act as),
         * followed by a NUL (U+0000) character, followed by the authentication
         * identity (identity whose password will be used), followed by a NUL
         * (U+0000) character, followed by the clear-text password.  As with
         * other SASL mechanisms, the client does not provide an authorization
         * identity when it wishes the server to derive an identity from the
         * credentials and use that as the authorization identity.
         */
        $tag = sqimap_session_id(false);
        $sasl = isset($sqimap_capabilities['SASL-IR']) && $sqimap_capabilities['SASL-IR'] ? true : false;
        if (!empty($authz)) {
            $auth = base64_encode("{$username}{$authz}{$password}");
        } else {
            $auth = base64_encode("{$username}{$username}{$password}");
        }
        if ($sasl) {
            // IMAP Extension for SASL Initial Client Response
            // <draft-siemborski-imap-sasl-initial-response-01b.txt>
            $query = $tag . " AUTHENTICATE PLAIN {$auth}\r\n";
            fputs($imap_stream, $query);
            $read = sqimap_fgets($imap_stream);
        } else {
            $query = $tag . " AUTHENTICATE PLAIN\r\n";
            fputs($imap_stream, $query);
            $read = sqimap_fgets($imap_stream);
            if (substr($read, 0, 1) == '+') {
                // OK so far..
                fputs($imap_stream, "{$auth}\r\n");
                $read = sqimap_fgets($imap_stream);
            }
        }
        $results = explode(" ", $read, 3);
        $response = $results[1];
        $message = $results[2];
    } else {
        $response = "BAD";
        $message = "Internal SquirrelMail error - unknown IMAP authentication method chosen.  Please contact the developers.";
    }
    /* If the connection was not successful, lets see why */
    if ($response != 'OK') {
        if (!$hide || $hide == 3) {
            //FIXME: UUURG... We don't want HTML in error messages, should also do html sanitizing of error messages elsewhere; should't assume output is destined for an HTML browser here
            if ($response != 'NO') {
                /* "BAD" and anything else gets reported here. */
                $message = sm_encode_html_special_chars($message);
                set_up_language($squirrelmail_language, true);
                if ($response == 'BAD') {
                    if ($hide == 3) {
                        return sprintf(_("Bad request: %s"), $message);
                    }
                    $string = sprintf(_("Bad request: %s") . "<br />\r\n", $message);
                } else {
                    if ($hide == 3) {
                        return sprintf(_("Unknown error: %s"), $message);
                    }
                    $string = sprintf(_("Unknown error: %s") . "<br />\n", $message);
                }
                if (isset($read) && is_array($read)) {
                    $string .= '<br />' . _("Read data:") . "<br />\n";
                    foreach ($read as $line) {
                        $string .= sm_encode_html_special_chars($line) . "<br />\n";
                    }
                }
                error_box($string);
                exit;
            } else {
                /*
                 * If the user does not log in with the correct
                 * username and password it is not possible to get the
                 * correct locale from the user's preferences.
                 * Therefore, apply the same hack as on the login
                 * screen.
                 *
                 * $squirrelmail_language is set by a cookie when
                 * the user selects language and logs out
                 */
                set_up_language($squirrelmail_language, true);
                sqsession_destroy();
                /* terminate the session nicely */
                sqimap_logout($imap_stream);
                // determine what error message to use
                //
                $fail_msg = _("Unknown user or password incorrect.");
                if ($display_imap_login_error) {
                    // See if there is an error message from the server
                    // Skip any rfc5530 response code: '[something]' at the
                    // start of the message
                    if (!empty($message) && $message[0] == '[' && ($end = strstr($message, ']')) && $end != ']') {
                        $message = substr($end, 1);
                    }
                    // Remove surrounding spaces and if there
                    // is anything left, display that as the
                    // error message:
                    $message = trim($message);
                    if (strlen($message)) {
                        $fail_msg = _($message);
                    }
                }
                if ($hide == 3) {
                    return $fail_msg;
                }
                logout_error($fail_msg);
                exit;
            }
        } else {
            if ($hide == 2) {
                return FALSE;
            }
            exit;
        }
    }
    /* Special error case:
     * Login referrals. The server returns:
     * ? OK [REFERRAL <imap url>]
     * Check RFC 2221 for details. Since we do not support login referrals yet
     * we log the user out.
     */
    if (stristr($message, 'REFERRAL imap') === TRUE) {
        sqimap_logout($imap_stream);
        set_up_language($squirrelmail_language, true);
        sqsession_destroy();
        logout_error(_("Your mailbox is not located at this server. Try a different server or consult your system administrator"));
        exit;
    }
    return $imap_stream;
}