Beispiel #1
0
/**
 * Check if user has previously logged in to the SquirrelMail session.  If user
 * has not logged in, execution will stop inside this function.
 *
 * @return int A positive value is returned if user has previously logged in
 * successfully.
 */
function is_logged_in()
{
    if (sqsession_is_registered('user_is_logged_in')) {
        return;
    } else {
        global $PHP_SELF, $HTTP_POST_VARS, $_POST, $session_expired_post, $session_expired_location, $squirrelmail_language;
        //  First we store some information in the new session to prevent
        //  information-loss.
        //
        if (!check_php_version(4, 1)) {
            $session_expired_post = $HTTP_POST_VARS;
        } else {
            $session_expired_post = $_POST;
        }
        $session_expired_location = $PHP_SELF;
        if (!sqsession_is_registered('session_expired_post')) {
            sqsession_register($session_expired_post, 'session_expired_post');
        }
        if (!sqsession_is_registered('session_expired_location')) {
            sqsession_register($session_expired_location, 'session_expired_location');
        }
        session_write_close();
        // signout page will deal with users who aren't logged
        // in on its own; don't show error here
        //
        if (strpos($PHP_SELF, 'signout.php') !== FALSE) {
            return;
        }
        include_once SM_PATH . 'functions/display_messages.php';
        set_up_language($squirrelmail_language, true);
        logout_error(_("You must be logged in to access this page."));
        exit;
    }
}
function logout_error($errString, $errTitle = '')
{
    global $frame_top, $org_logo, $org_name, $org_logo_width, $org_logo_height, $hide_sm_attributions, $version, $squirrelmail_language, $color, $theme, $theme_default;
    $base_uri = sqm_baseuri();
    include_once SM_PATH . 'functions/page_header.php';
    if (!isset($org_logo)) {
        // Don't know yet why, but in some accesses $org_logo is not set.
        include SM_PATH . 'config/config.php';
    }
    /* Display width and height like good little people */
    $width_and_height = '';
    if (isset($org_logo_width) && is_numeric($org_logo_width) && $org_logo_width > 0) {
        $width_and_height = " width=\"{$org_logo_width}\"";
    }
    if (isset($org_logo_height) && is_numeric($org_logo_height) && $org_logo_height > 0) {
        $width_and_height .= " height=\"{$org_logo_height}\"";
    }
    if (!isset($frame_top) || $frame_top == '') {
        $frame_top = '_top';
    }
    // load default theme if possible
    if (!isset($color) && @file_exists($theme[$theme_default]['PATH'])) {
        @(include $theme[$theme_default]['PATH']);
    }
    if (!isset($color)) {
        $color = array();
        $color[0] = '#dcdcdc';
        /* light gray    TitleBar               */
        $color[1] = '#800000';
        /* red                                  */
        $color[2] = '#cc0000';
        /* light red     Warning/Error Messages */
        $color[4] = '#ffffff';
        /* white         Normal Background      */
        $color[7] = '#0000cc';
        /* blue          Links                  */
        $color[8] = '#000000';
        /* black         Normal text            */
    }
    $logout_link = $base_uri . 'src/login.php';
    list($junk, $errString, $errTitle, $logout_link) = do_hook('logout_error', $errString, $errTitle, $logout_link);
    if ($errTitle == '') {
        $errTitle = $errString;
    }
    set_up_language($squirrelmail_language, true);
    displayHtmlHeader($org_name . ' - ' . $errTitle, '', false);
    echo '<body text="' . $color[8] . '" bgcolor="' . $color[4] . '" link="' . $color[7] . '" vlink="' . $color[7] . '" alink="' . $color[7] . "\">\n\n" . '<center>';
    if (isset($org_logo) && $org_logo != '') {
        echo '<img src="' . $org_logo . '" alt="' . sprintf(_("%s Logo"), $org_name) . "\"{$width_and_height} /><br />\n";
    }
    echo ($hide_sm_attributions ? '' : '<small>' . sprintf(_("SquirrelMail version %s"), $version) . '<br />' . _("By the SquirrelMail Project Team") . "<br /></small>\n") . '<table cellspacing="1" cellpadding="0" bgcolor="' . $color[1] . '" width="70%">' . '<tr><td>' . '<table width="100%" border="0" bgcolor="' . $color[4] . '" align="center">' . '<tr><td bgcolor="' . $color[0] . '" align="center">' . '<font color="' . $color[2] . '"><b>' . _("ERROR") . '</b></font>' . '</td></tr>' . '<tr><td align="center">' . $errString . '</td></tr>' . '<tr><td bgcolor="' . $color[0] . '" align="center">' . '<font color="' . $color[2] . '"><b>' . '<a href="' . $logout_link . '" target="' . $frame_top . '">' . _("Go to the login page") . '</a></b></font></td></tr>' . '</table></td></tr></table></center></body></html>';
}
Beispiel #3
0
/**
 * Check if user has previously logged in to the SquirrelMail session.  If user
 * has not logged in, execution will stop inside this function.
 *
 * @return void This function returns ONLY if user has previously logged in
 * successfully (otherwise, execution terminates herein).
 */
function is_logged_in()
{
    if (sqsession_is_registered('user_is_logged_in')) {
        return;
    } else {
        global $session_expired_post, $session_expired_location, $squirrelmail_language;
        // use $message to indicate what logout text the user
        // will see... if 0, typical "You must be logged in"
        // if 1, information that the user session was saved
        // and will be resumed after (re)login
        //
        $message = 0;
        //  First we store some information in the new session to prevent
        //  information-loss.
        $session_expired_post = $_POST;
        if (defined('PAGE_NAME')) {
            $session_expired_location = PAGE_NAME;
        }
        if (!sqsession_is_registered('session_expired_post')) {
            sqsession_register($session_expired_post, 'session_expired_post');
        }
        if (!sqsession_is_registered('session_expired_location')) {
            sqsession_register($session_expired_location, 'session_expired_location');
            if ($session_expired_location == 'compose') {
                $message = 1;
            }
        }
        session_write_close();
        // signout page will deal with users who aren't logged
        // in on its own; don't show error here
        if (defined('PAGE_NAME') && PAGE_NAME == 'signout') {
            return;
        }
        include_once SM_PATH . 'functions/display_messages.php';
        set_up_language($squirrelmail_language, true);
        if (!$message) {
            logout_error(_("You must be logged in to access this page."));
        } else {
            logout_error(_("Your session has expired, but will be resumed after logging in again."));
        }
        exit;
    }
}
/**
 * Displays error when user is logged out
 * 
 * Error strings can be overriden by logout_error hook
 * @param string $errString error message
 * @param string $errTitle title of page with error message
 * @since 1.2.6
 */
function logout_error($errString, $errTitle = '')
{
    global $frame_top, $org_logo, $org_logo_width, $org_logo_height, $org_name, $hide_sm_attributions, $squirrelmail_language, $oTemplate, $base_uri;
    $login_link = array('URI' => $base_uri . 'src/login.php', 'FRAME' => $frame_top);
    /* As of 1.5.2, plugin parameters are combined into one array; 
       plugins on this hook must be updated */
    $temp = array(&$errString, &$errTitle, &$login_link);
    do_hook('logout_error', $temp);
    if ($errTitle == '') {
        $errTitle = $errString;
    }
    set_up_language($squirrelmail_language, true);
    displayHtmlHeader($org_name . ' - ' . $errTitle, '', false);
    /* If they don't have a logo, don't bother.. */
    $logo_str = '';
    if (isset($org_logo) && $org_logo) {
        if (isset($org_logo_width) && is_numeric($org_logo_width) && $org_logo_width > 0) {
            $width = $org_logo_width;
        } else {
            $width = '';
        }
        if (isset($org_logo_height) && is_numeric($org_logo_height) && $org_logo_height > 0) {
            $height = $org_logo_height;
        } else {
            $height = '';
        }
        $logo_str = create_image($org_logo, sprintf(_("%s Logo"), $org_name), $width, $height, '', 'sqm_loginImage');
    }
    $sm_attribute_str = '';
    if (isset($hide_sm_attributions) && !$hide_sm_attributions) {
        $sm_attribute_str = _("SquirrelMail Webmail") . "\n" . _("By the SquirrelMail Project Team");
    }
    $oTemplate->assign('logo_str', $logo_str);
    $oTemplate->assign('sm_attribute_str', $sm_attribute_str);
    $oTemplate->assign('login_link', $login_link);
    $oTemplate->assign('errorMessage', $errString);
    $oTemplate->display('error_logout.tpl');
    $oTemplate->display('footer.tpl');
}
Beispiel #5
0
/**
 * Check if user has previously logged in to the Squirrelmail session.  If user
 * has not logged in, execution will stop inside this function.
 *
 * @return int A positive value is returned if user has previously logged in
 * successfully.
 */
function is_logged_in()
{
    return;
    if (sqsession_is_registered('user_is_logged_in')) {
        return;
    } else {
        global $PHP_SELF, $session_expired_post, $session_expired_location, $squirrelmail_language;
        /*  First we store some information in the new session to prevent
         *  information-loss.
         */
        $session_expired_post = $_POST;
        $session_expired_location = $PHP_SELF;
        if (!sqsession_is_registered('session_expired_post')) {
            sqsession_register($session_expired_post, 'session_expired_post');
        }
        if (!sqsession_is_registered('session_expired_location')) {
            sqsession_register($session_expired_location, 'session_expired_location');
        }
        include_once SM_PATH . 'functions/display_messages.php';
        set_up_language($squirrelmail_language, true);
        logout_error(_("You must be logged in to access this page."));
        exit;
    }
}
function sqimap_append_done($imap_stream, $folder = '')
{
    global $squirrelmail_language, $color;
    fputs($imap_stream, "\r\n");
    $tmp = fgets($imap_stream, 1024);
    if (preg_match("/(.*)(BAD|NO)(.*)\$/", $tmp, $regs)) {
        set_up_language($squirrelmail_language);
        require_once SM_PATH . 'functions/display_messages.php';
        $reason = $regs[3];
        if ($regs[2] == 'NO') {
            $string = "<b><font color={$color['2']}>\n" . _("ERROR : Could not append message to") . " {$folder}." . "</b><br>\n" . _("Server responded: ") . $reason . "<br>\n";
            if (preg_match("/(.*)(quota)(.*)\$/i", $reason, $regs)) {
                $string .= _("Solution: ") . _("Remove unneccessary messages from your folder and start with your Trash folder.") . "<br>\n";
            }
            $string .= "</font>\n";
            error_box($string, $color);
        } else {
            $string = "<b><font color={$color['2']}>\n" . _("ERROR : Bad or malformed request.") . "</b><br>\n" . _("Server responded: ") . $tmp . "</font><br>\n";
            error_box($string, $color);
            exit;
        }
    }
}
Beispiel #7
0
function sqimap_append_checkresponse($response, $folder)
{
    if (preg_match("/(.*)(BAD|NO)(.*)\$/", $response, $regs)) {
        global $squirrelmail_language, $color;
        set_up_language($squirrelmail_language);
        require_once SM_PATH . 'functions/display_messages.php';
        $reason = $regs[3];
        if ($regs[2] == 'NO') {
            $string = "<b><font color=\"{$color['2']}\">\n" . _("ERROR: Could not append message to") . " {$folder}." . "</b><br />\n" . _("Server responded:") . ' ' . $reason . "<br />\n";
            if (preg_match("/(.*)(quota)(.*)\$/i", $reason, $regs)) {
                $string .= _("Solution:") . ' ' . _("Remove unneccessary messages from your folders. Start with your Trash folder.") . "<br />\n";
            }
            $string .= "</font>\n";
            error_box($string, $color);
        } else {
            $string = "<b><font color=\"{$color['2']}\">\n" . _("ERROR: Bad or malformed request.") . "</b><br />\n" . _("Server responded:") . ' ' . $reason . "</font><br />\n";
            error_box($string, $color);
            exit;
        }
    }
}
function sqimap_get_headerfield($imap_stream, $field)
{
    $sid = sqimap_session_id(false);
    $results = array();
    $read_list = array();
    $query = "{$sid} FETCH 1:* (UID BODY.PEEK[HEADER.FIELDS ({$field})])\r\n";
    fputs($imap_stream, $query);
    $readin_list = sqimap_read_data_list($imap_stream, $sid, false, $response, $message);
    $i = 0;
    foreach ($readin_list as $r) {
        $r = implode('', $r);
        /* first we unfold the header */
        $r = str_replace(array("\r\n\t", "\r\n\\s"), array('', ''), $r);
        /* 
         * now we can make a new header array with each element representing 
         * a headerline
         */
        $r = explode("\r\n", $r);
        if (!$uid_support) {
            if (!preg_match("/^\\*\\s+([0-9]+)\\s+FETCH/iAU", $r[0], $regs)) {
                set_up_language($squirrelmail_language);
                echo '<br><b><font color=$color[2]>' . _("ERROR : Could not complete request.") . '</b><br>' . _("Unknown response from IMAP server: ") . ' 1.' . $r[0] . "</font><br>\n";
            } else {
                $id = $regs[1];
            }
        } else {
            if (!preg_match("/^\\*\\s+([0-9]+)\\s+FETCH.*UID\\s+([0-9]+)\\s+/iAU", $r[0], $regs)) {
                set_up_language($squirrelmail_language);
                echo '<br><b><font color=$color[2]>' . _("ERROR : Could not complete request.") . '</b><br>' . _("Unknown response from IMAP server: ") . ' 1.' . $r[0] . "</font><br>\n";
            } else {
                $id = $regs[2];
            }
        }
        $field = $r[1];
        $field = substr($field, strlen($field) + 2);
        $result[] = array($id, $field);
    }
    return $result;
}
* don't have to worry.
*
* This is for a RedHat package bug and a Konqueror (pre 2.1.1?) bug
*/
global $send, $PHP_SELF;
if (isset($send) && substr($send, 0, 1) == "\n" && substr($PHP_SELF, -12) == '/compose.php') {
    if ($REQUEST_METHOD == 'POST') {
        global $HTTP_POST_VARS;
        TrimArray($HTTP_POST_VARS);
    } else {
        global $HTTP_GET_VARS;
        TrimArray($HTTP_GET_VARS);
    }
}
require_once SM_PATH . 'include/load_prefs.php';
require_once SM_PATH . 'functions/page_header.php';
require_once SM_PATH . 'functions/prefs.php';
/* Set up the language (i18n.php was included by auth.php). */
global $username, $data_dir;
set_up_language(getPref($data_dir, $username, 'language'));
$timeZone = getPref($data_dir, $username, 'timezone');
/* Check to see if we are allowed to set the TZ environment variable.
 * We are able to do this if ... 
 *   safe_mode is disabled OR
 *   safe_mode_allowed_env_vars is empty (you are allowed to set any) OR
 *   safe_mode_allowed_env_vars contains TZ 
 */
$tzChangeAllowed = !ini_get('safe_mode') || !strcmp(ini_get('safe_mode_allowed_env_vars'), '') || preg_match('/^([\\w_]+,)*TZ/', ini_get('safe_mode_allowed_env_vars'));
if ($timeZone != SMPREF_NONE && $timeZone != "" && $tzChangeAllowed) {
    putenv("TZ=" . $timeZone);
}
function logout_error($errString, $errTitle = '')
{
    global $frame_top, $org_logo, $org_name, $org_logo_width, $org_logo_height, $hide_sm_attributions, $version, $squirrelmail_language;
    $base_uri = sqm_baseuri();
    include_once SM_PATH . 'functions/page_header.php';
    if (!isset($org_logo)) {
        // Don't know yet why, but in some accesses $org_logo is not set.
        include SM_PATH . 'config/config.php';
    }
    /* Display width and height like good little people */
    $width_and_height = '';
    if (isset($org_logo_width) && is_numeric($org_logo_width) && $org_logo_width > 0) {
        $width_and_height = " WIDTH=\"{$org_logo_width}\"";
    }
    if (isset($org_logo_height) && is_numeric($org_logo_height) && $org_logo_height > 0) {
        $width_and_height .= " HEIGHT=\"{$org_logo_height}\"";
    }
    if (!isset($frame_top) || $frame_top == '') {
        $frame_top = '_top';
    }
    if (!isset($color)) {
        $color = array();
        $color[0] = '#DCDCDC';
        /* light gray    TitleBar               */
        $color[1] = '#800000';
        /* red                                  */
        $color[2] = '#CC0000';
        /* light red     Warning/Error Messages */
        $color[4] = '#FFFFFF';
        /* white         Normal Background      */
        $color[7] = '#0000CC';
        /* blue          Links                  */
        $color[8] = '#000000';
        /* black         Normal text            */
    }
    if ($errTitle == '') {
        $errTitle = $errString;
    }
    set_up_language($squirrelmail_language, true);
    displayHtmlHeader($errTitle, '', false);
    echo "<BODY TEXT=\"{$color['8']}\" BGCOLOR=\"{$color['4']}\" LINK=\"{$color['7']}\" VLINK=\"{$color['7']}\" ALINK=\"{$color['7']}\">\n\n" . '<CENTER>';
    if (isset($org_logo) && $org_logo != '') {
        echo "<IMG SRC=\"{$org_logo}\" ALT=\"" . sprintf(_("%s Logo"), $org_name) . "\"{$width_and_height}><BR>\n";
    }
    echo ($hide_sm_attributions ? '' : '<SMALL>' . sprintf(_("SquirrelMail version %s"), $version) . "<BR>\n" . '  ' . _("By the SquirrelMail Development Team") . "<BR></SMALL>\n") . "<table cellspacing=1 cellpadding=0 bgcolor=\"{$color['1']}\" width=\"70%\"><tr><td>" . "<TABLE WIDTH=\"100%\" BORDER=\"0\" BGCOLOR=\"{$color['4']}\" ALIGN=CENTER>" . "<TR><TD BGCOLOR=\"{$color['0']}\" ALIGN=\"center\">" . "<FONT COLOR=\"{$color['2']}\"><B>" . _("ERROR") . '</B></FONT></TD></TR>' . '<TR><TD ALIGN="center">' . $errString . '</TD></TR>' . "<TR><TD BGCOLOR=\"{$color['0']}\" ALIGN=\"center\">" . "<FONT COLOR=\"{$color['2']}\"><B>" . '<a href="' . $base_uri . 'src/login.php" target="' . $frame_top . '">' . _("Go to the login page") . "</a></B></FONT>" . '</TD></TR>' . '</TABLE></td></tr></table></center></body></html>';
}
Beispiel #11
0
/* SquirrelMail required files. */
require_once SM_PATH . 'functions/strings.php';
require_once SM_PATH . 'config/config.php';
require_once SM_PATH . 'functions/i18n.php';
require_once SM_PATH . 'functions/plugin.php';
require_once SM_PATH . 'functions/constants.php';
require_once SM_PATH . 'functions/page_header.php';
require_once SM_PATH . 'functions/html.php';
require_once SM_PATH . 'functions/global.php';
require_once SM_PATH . 'functions/imap_general.php';
require_once SM_PATH . 'functions/forms.php';
/**
 * $squirrelmail_language is set by a cookie when the user selects
 * language and logs out
 */
set_up_language($squirrelmail_language, TRUE, TRUE);
/**
 * Find out the base URI to set cookies.
 */
if (!function_exists('sqm_baseuri')) {
    require_once SM_PATH . 'functions/display_messages.php';
}
$base_uri = sqm_baseuri();
/*
 * In case the last session was not terminated properly, make sure
 * we get a new one.
 */
sqsession_destroy();
header('Pragma: no-cache');
/**
 * This detects if the IMAP server has logins disabled, and if so, 
Beispiel #12
0
$location = get_location();
sqsession_is_active();
sqsession_unregister('user_is_logged_in');
sqsession_register($base_uri, 'base_uri');
/* get globals we me need */
sqGetGlobalVar('login_username', $login_username);
sqGetGlobalVar('secretkey', $secretkey);
sqGetGlobalVar('js_autodetect_results', $js_autodetect_results);
if (!sqGetGlobalVar('squirrelmail_language', $squirrelmail_language) || $squirrelmail_language == '') {
    $squirrelmail_language = $squirrelmail_default_language;
}
if (!sqgetGlobalVar('mailtodata', $mailtodata)) {
    $mailtodata = '';
}
/* end of get globals */
set_up_language($squirrelmail_language, true);
/* Refresh the language cookie. */
sqsetcookie('squirrelmail_language', $squirrelmail_language, time() + 2592000, $base_uri);
if (!isset($login_username)) {
    include_once SM_PATH . 'functions/display_messages.php';
    logout_error(_("You must be logged in to access this page."));
    exit;
}
if (!sqsession_is_registered('user_is_logged_in')) {
    do_hook('login_before');
    /**
     * Regenerate session id to make sure that authenticated session uses
     * different ID than one used before user authenticated.  This is a
     * countermeasure against session fixation attacks.
     * NB: session_regenerate_id() was added in PHP 4.3.2 (and new session
     *     cookie is only sent out in this call as of PHP 4.3.3), but PHP 4
Beispiel #13
0
// it first to avoid register_globals headaches
//
$right_frame_url = '';
do_hook('webmail_top');
/**
 * We'll need this to later have a noframes version
 *
 * Check if the user has a language preference, but no cookie.
 * Send him a cookie with his language preference, if there is
 * such discrepancy.
 */
$my_language = getPref($data_dir, $username, 'language');
if ($my_language != $squirrelmail_language) {
    sqsetcookie('squirrelmail_language', $my_language, time() + 2592000, $base_uri);
}
set_up_language($my_language);
$output = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\">\n" . "<html><head>\n" . "<meta name=\"robots\" content=\"noindex,nofollow\">\n" . "<title>{$org_title}</title>\n" . "</head>";
$left_size = getPref($data_dir, $username, 'left_size');
$location_of_bar = getPref($data_dir, $username, 'location_of_bar');
if (isset($languages[$squirrelmail_language]['DIR']) && strtolower($languages[$squirrelmail_language]['DIR']) == 'rtl') {
    $temp_location_of_bar = 'right';
} else {
    $temp_location_of_bar = 'left';
}
if ($location_of_bar == '') {
    $location_of_bar = $temp_location_of_bar;
}
$temp_location_of_bar = '';
if ($left_size == "") {
    if (isset($default_left_size)) {
        $left_size = $default_left_size;
Beispiel #14
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;
}