Example #1
0
function parse_viewheader($imapConnection, $id, $passed_ent_id)
{
    $header_output = array();
    $second = array();
    $first = array();
    if (!$passed_ent_id) {
        $read = sqimap_run_command($imapConnection, "FETCH {$id} BODY[HEADER]", true, $a, $b, TRUE);
    } else {
        $query = "FETCH {$id} BODY[" . $passed_ent_id . '.HEADER]';
        $read = sqimap_run_command($imapConnection, $query, true, $a, $b, TRUE);
    }
    $cnum = 0;
    for ($i = 1; $i < count($read); $i++) {
        $line = sm_encode_html_special_chars($read[$i]);
        switch (true) {
            case preg_match('/^&gt;/i', $line):
                $second[$i] = $line;
                $first[$i] = '&nbsp;';
                $cnum++;
                break;
                // FIXME: is the pipe character below a mistake?  I think the original author might have thought it carried special meaning in the character class, which it does not... but then again, I am not currently trying to understand what this code actually does
            // FIXME: is the pipe character below a mistake?  I think the original author might have thought it carried special meaning in the character class, which it does not... but then again, I am not currently trying to understand what this code actually does
            case preg_match('/^[ |\\t]/', $line):
                $second[$i] = $line;
                $first[$i] = '';
                break;
            case preg_match('/^([^:]+):(.+)/', $line, $regs):
                $first[$i] = $regs[1] . ':';
                $second[$i] = $regs[2];
                $cnum++;
                break;
            default:
                $second[$i] = trim($line);
                $first[$i] = '';
                break;
        }
    }
    for ($i = 0; $i < count($second); $i = $j) {
        $f = isset($first[$i]) ? $first[$i] : '';
        $s = isset($second[$i]) ? nl2br($second[$i]) : '';
        $j = $i + 1;
        while ($first[$j] == '' && $j < count($first)) {
            $s .= '&nbsp;&nbsp;&nbsp;&nbsp;' . nl2br($second[$j]);
            $j++;
        }
        $lowf = strtolower($f);
        /* do not mark these headers as emailaddresses */
        if ($lowf != 'message-id:' && $lowf != 'in-reply-to:' && $lowf != 'references:') {
            parseEmail($s);
        }
        if ($f) {
            $header_output[] = array($f, $s);
        }
    }
    sqimap_logout($imapConnection);
    return $header_output;
}
function parse_viewheader($imapConnection, $id, $passed_ent_id)
{
    $header_full = array();
    if (!$passed_ent_id) {
        $read = sqimap_run_command($imapConnection, "FETCH {$id} BODY[HEADER]", true, $a, $b, TRUE);
    } else {
        $query = "FETCH {$id} BODY[" . $passed_ent_id . '.HEADER]';
        $read = sqimap_run_command($imapConnection, $query, true, $a, $b, TRUE);
    }
    $cnum = 0;
    for ($i = 1; $i < count($read); $i++) {
        $line = htmlspecialchars($read[$i]);
        switch (true) {
            case eregi("^&gt;", $line):
                $second[$i] = $line;
                $first[$i] = '&nbsp;';
                $cnum++;
                break;
            case eregi("^[ |\t]", $line):
                $second[$i] = $line;
                $first[$i] = '';
                break;
            case eregi("^([^:]+):(.+)", $line, $regs):
                $first[$i] = $regs[1] . ':';
                $second[$i] = $regs[2];
                $cnum++;
                break;
            default:
                $second[$i] = trim($line);
                $first[$i] = '';
                break;
        }
    }
    for ($i = 0; $i < count($second); $i = $j) {
        $f = isset($first[$i]) ? $first[$i] : '';
        $s = isset($second[$i]) ? nl2br($second[$i]) : '';
        $j = $i + 1;
        while ($first[$j] == '' && $j < count($first)) {
            $s .= '&nbsp;&nbsp;&nbsp;&nbsp;' . nl2br($second[$j]);
            $j++;
        }
        $lowf = strtolower($f);
        /* do not mark these headers as emailaddresses */
        if ($lowf != 'message-id:' && $lowf != 'in-reply-to:' && $lowf != 'references:') {
            parseEmail($s);
        }
        if ($f) {
            $header_output[] = array($f, $s);
        }
    }
    sqimap_logout($imapConnection);
    return $header_output;
}
Example #3
0
/**
 * Update sent_subfolders settings
 *
 * function updates default sent folder value and 
 * creates required imap folders
 */
function sent_subfolders_update_sentfolder()
{
    global $sent_folder, $auto_create_special, $auto_create_done;
    global $sent_subfolders_base, $sent_subfolders_setting;
    global $data_dir, $imapServerAddress, $imapPort;
    global $use_sent_subfolders, $move_to_sent, $imap_server_type;
    sqgetGlobalVar('username', $username, SQ_SESSION);
    sqgetGlobalVar('key', $key, SQ_COOKIE);
    sqgetGlobalVar('delimiter', $delimiter, SQ_SESSION);
    if ($use_sent_subfolders || $move_to_sent) {
        $year = date('Y');
        $month = date('m');
        $quarter = sent_subfolder_getQuarter($month);
        /*
            Regarding the structure we've got three main possibilities.
            One sent holder. level 0.
            Multiple year holders with messages in it. level 1.
            Multiple year folders with holders in it. level 2.
        */
        /*
                if( $imap_server_type == 'uw' ) {
                    $cnd_delimiter = '';
                } else {
                    $cnd_delimiter = $delimiter;
                }
        */
        $cnd_delimiter = $delimiter;
        switch ($sent_subfolders_setting) {
            case SMPREF_SENT_SUBFOLDERS_YEARLY:
                $level = 1;
                $sent_subfolder = $sent_subfolders_base . $cnd_delimiter . $year;
                break;
            case SMPREF_SENT_SUBFOLDERS_QUARTERLY:
                $level = 2;
                $sent_subfolder = $sent_subfolders_base . $cnd_delimiter . $year . $delimiter . $quarter;
                $year_folder = $sent_subfolders_base . $year;
                break;
            case SMPREF_SENT_SUBFOLDERS_MONTHLY:
                $level = 2;
                $sent_subfolder = $sent_subfolders_base . $cnd_delimiter . $year . $delimiter . $month;
                $year_folder = $sent_subfolders_base . $year;
                break;
            case SMPREF_SENT_SUBFOLDERS_DISABLED:
            default:
                $level = 0;
                $sent_subfolder = $sent_folder;
                $year_folder = $sent_folder;
        }
        /* If this folder is NOT the current sent folder, update stuff. */
        if ($sent_subfolder != $sent_folder) {
            /* First, update the sent folder. */
            setPref($data_dir, $username, 'sent_folder', $sent_subfolder);
            setPref($data_dir, $username, 'move_to_sent', SMPREF_ON);
            $sent_folder = $sent_subfolder;
            $move_to_sent = SMPREF_ON;
            /* Auto-create folders, if they do not yet exist. */
            if ($sent_folder != 'none') {
                /* Create the imap connection. */
                $ic = sqimap_login($username, $key, $imapServerAddress, $imapPort, 10);
                /* Auto-create the year folder, if it does not yet exist. */
                if (!sqimap_mailbox_exists($ic, $year_folder)) {
                    sqimap_mailbox_create($ic, $year_folder, $level == 1 ? '' : 'noselect');
                } else {
                    if (!sqimap_mailbox_is_subscribed($ic, $year_folder)) {
                        sqimap_subscribe($ic, $year_folder);
                    }
                }
                /* Auto-create the subfolder, if it does not yet exist. */
                if (!sqimap_mailbox_exists($ic, $sent_folder)) {
                    sqimap_mailbox_create($ic, $sent_folder, '');
                } else {
                    if (!sqimap_mailbox_is_subscribed($ic, $sent_subfolder)) {
                        sqimap_subscribe($ic, $sent_subfolder);
                    }
                }
                /* Close the imap connection. */
                sqimap_logout($ic);
            }
        }
    }
}
Example #4
0
function deliverMessage($composeMessage, $draft = false)
{
    global $send_to, $send_to_cc, $send_to_bcc, $mailprio, $subject, $body, $username, $popuser, $usernamedata, $identity, $idents, $data_dir, $request_mdn, $request_dr, $default_charset, $color, $useSendmail, $domain, $action, $default_move_to_sent, $move_to_sent;
    global $imapServerAddress, $imapPort, $sent_folder, $key;
    $rfc822_header = $composeMessage->rfc822_header;
    $abook = addressbook_init(false, true);
    $rfc822_header->to = $rfc822_header->parseAddress($send_to, true, array(), '', $domain, array(&$abook, 'lookup'));
    $rfc822_header->cc = $rfc822_header->parseAddress($send_to_cc, true, array(), '', $domain, array(&$abook, 'lookup'));
    $rfc822_header->bcc = $rfc822_header->parseAddress($send_to_bcc, true, array(), '', $domain, array(&$abook, 'lookup'));
    $rfc822_header->priority = $mailprio;
    $rfc822_header->subject = $subject;
    $special_encoding = '';
    if (strtolower($default_charset) == 'iso-2022-jp') {
        if (mb_detect_encoding($body) == 'ASCII') {
            $special_encoding = '8bit';
        } else {
            $body = mb_convert_encoding($body, 'JIS');
            $special_encoding = '7bit';
        }
    }
    $composeMessage->setBody($body);
    if (ereg("^([^@%/]+)[@%/](.+)\$", $username, $usernamedata)) {
        $popuser = $usernamedata[1];
        $domain = $usernamedata[2];
        unset($usernamedata);
    } else {
        $popuser = $username;
    }
    $reply_to = '';
    $from_mail = $idents[$identity]['email_address'];
    $full_name = $idents[$identity]['full_name'];
    $reply_to = $idents[$identity]['reply_to'];
    if (!$from_mail) {
        $from_mail = "{$popuser}@{$domain}";
    }
    $rfc822_header->from = $rfc822_header->parseAddress($from_mail, true);
    if ($full_name) {
        $from = $rfc822_header->from[0];
        if (!$from->host) {
            $from->host = $domain;
        }
        $full_name_encoded = encodeHeader($full_name);
        if ($full_name_encoded != $full_name) {
            $from_addr = $full_name_encoded . ' <' . $from->mailbox . '@' . $from->host . '>';
        } else {
            $from_addr = '"' . $full_name . '" <' . $from->mailbox . '@' . $from->host . '>';
        }
        $rfc822_header->from = $rfc822_header->parseAddress($from_addr, true);
    }
    if ($reply_to) {
        $rfc822_header->reply_to = $rfc822_header->parseAddress($reply_to, true);
    }
    /* Receipt: On Read */
    if (isset($request_mdn) && $request_mdn) {
        $rfc822_header->dnt = $rfc822_header->parseAddress($from_mail, true);
    }
    /* Receipt: On Delivery */
    if (isset($request_dr) && $request_dr) {
        $rfc822_header->more_headers['Return-Receipt-To'] = $from_mail;
    }
    /* multipart messages */
    if (count($composeMessage->entities)) {
        $message_body = new Message();
        $message_body->body_part = $composeMessage->body_part;
        $composeMessage->body_part = '';
        $mime_header = new MessageHeader();
        $mime_header->type0 = 'text';
        $mime_header->type1 = 'plain';
        if ($special_encoding) {
            $mime_header->encoding = $special_encoding;
        } else {
            $mime_header->encoding = '8bit';
        }
        if ($default_charset) {
            $mime_header->parameters['charset'] = $default_charset;
        }
        $message_body->mime_header = $mime_header;
        array_unshift($composeMessage->entities, $message_body);
        $content_type = new ContentType('multipart/mixed');
    } else {
        $content_type = new ContentType('text/plain');
        if ($special_encoding) {
            $rfc822_header->encoding = $special_encoding;
        } else {
            $rfc822_header->encoding = '8bit';
        }
        if ($default_charset) {
            $content_type->properties['charset'] = $default_charset;
        }
    }
    $rfc822_header->content_type = $content_type;
    $composeMessage->rfc822_header = $rfc822_header;
    /* Here you can modify the message structure just before we hand
       it over to deliver */
    $hookReturn = do_hook('compose_send', $composeMessage);
    /* Get any changes made by plugins to $composeMessage. */
    if (is_object($hookReturn[1])) {
        $composeMessage = $hookReturn[1];
    }
    if (!$useSendmail && !$draft) {
        require_once SM_PATH . 'class/deliver/Deliver_SMTP.class.php';
        $deliver = new Deliver_SMTP();
        global $smtpServerAddress, $smtpPort, $pop_before_smtp, $smtp_auth_mech;
        $authPop = isset($pop_before_smtp) && $pop_before_smtp ? true : false;
        get_smtp_user($user, $pass);
        $stream = $deliver->initStream($composeMessage, $domain, 0, $smtpServerAddress, $smtpPort, $user, $pass, $authPop);
    } elseif (!$draft) {
        require_once SM_PATH . 'class/deliver/Deliver_SendMail.class.php';
        global $sendmail_path;
        $deliver = new Deliver_SendMail();
        $stream = $deliver->initStream($composeMessage, $sendmail_path);
    } elseif ($draft) {
        global $draft_folder;
        require_once SM_PATH . 'class/deliver/Deliver_IMAP.class.php';
        $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 0);
        if (sqimap_mailbox_exists($imap_stream, $draft_folder)) {
            require_once SM_PATH . 'class/deliver/Deliver_IMAP.class.php';
            $imap_deliver = new Deliver_IMAP();
            $length = $imap_deliver->mail($composeMessage);
            sqimap_append($imap_stream, $draft_folder, $length);
            $imap_deliver->mail($composeMessage, $imap_stream);
            sqimap_append_done($imap_stream, $draft_folder);
            sqimap_logout($imap_stream);
            unset($imap_deliver);
            return $length;
        } else {
            $msg = '<br />' . sprintf(_("Error: Draft folder %s does not exist."), $draft_folder);
            plain_error_message($msg, $color);
            return false;
        }
    }
    $succes = false;
    if ($stream) {
        $length = $deliver->mail($composeMessage, $stream);
        $succes = $deliver->finalizeStream($stream);
    }
    if (!$succes) {
        $msg = $deliver->dlv_msg . '<br />' . _("Server replied: ") . $deliver->dlv_ret_nr . ' ' . $deliver->dlv_server_msg;
        plain_error_message($msg, $color);
    } else {
        unset($deliver);
        $move_to_sent = getPref($data_dir, $username, 'move_to_sent');
        $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 0);
        /* Move to sent code */
        if (isset($default_move_to_sent) && $default_move_to_sent != 0) {
            $svr_allow_sent = true;
        } else {
            $svr_allow_sent = false;
        }
        if (isset($sent_folder) && ($sent_folder != '' || $sent_folder != 'none') && sqimap_mailbox_exists($imap_stream, $sent_folder)) {
            $fld_sent = true;
        } else {
            $fld_sent = false;
        }
        if (isset($move_to_sent) && $move_to_sent != 0 || !isset($move_to_sent)) {
            $lcl_allow_sent = true;
        } else {
            $lcl_allow_sent = false;
        }
        if ($fld_sent && $svr_allow_sent && !$lcl_allow_sent || $fld_sent && $lcl_allow_sent) {
            global $passed_id, $mailbox, $action;
            if ($action == 'reply' || $action == 'reply_all') {
                $save_reply_with_orig = getPref($data_dir, $username, 'save_reply_with_orig');
                if ($save_reply_with_orig) {
                    $sent_folder = $mailbox;
                }
            }
            sqimap_append($imap_stream, $sent_folder, $length);
            require_once SM_PATH . 'class/deliver/Deliver_IMAP.class.php';
            $imap_deliver = new Deliver_IMAP();
            $imap_deliver->mail($composeMessage, $imap_stream);
            sqimap_append_done($imap_stream, $sent_folder);
            unset($imap_deliver);
        }
        global $passed_id, $mailbox, $action;
        ClearAttachments($composeMessage);
        if ($action == 'reply' || $action == 'reply_all') {
            sqimap_mailbox_select($imap_stream, $mailbox);
            sqimap_messages_flag($imap_stream, $passed_id, $passed_id, 'Answered', false);
        }
        sqimap_logout($imap_stream);
    }
    return $succes;
}
Example #5
0
/**
 * Update sent_subfolders settings
 *
 * function updates default sent folder value and
 * creates required imap folders
 */
function sent_subfolders_update_sentfolder_do()
{
    global $sent_folder, $username, $data_dir, $imapServerAddress, $imapPort, $imap_stream_options, $move_to_sent;
    sqgetGlobalVar('delimiter', $delimiter, SQ_SESSION);
    $use_sent_subfolders = getPref($data_dir, $username, 'use_sent_subfolders', SMPREF_OFF);
    $sent_subfolders_setting = getPref($data_dir, $username, 'sent_subfolders_setting', SMPREF_SENT_SUBFOLDERS_DISABLED);
    $sent_subfolders_base = getPref($data_dir, $username, 'sent_subfolders_base', $sent_folder);
    if ($use_sent_subfolders || $move_to_sent) {
        $year = date('Y');
        $month = date('m');
        $quarter = sent_subfolder_getQuarter($month);
        /**
         * Regarding the structure we've got three main possibilities.
         * One sent holder. level 0.
         * Multiple year holders with messages in it. level 1.
         * Multiple year folders with holders in it. level 2.
         */
        switch ($sent_subfolders_setting) {
            case SMPREF_SENT_SUBFOLDERS_YEARLY:
                $level = 1;
                $sent_subfolder = $sent_subfolders_base . $delimiter . $year;
                break;
            case SMPREF_SENT_SUBFOLDERS_QUARTERLY:
                $level = 2;
                $sent_subfolder = $sent_subfolders_base . $delimiter . $year . $delimiter . $quarter;
                $year_folder = $sent_subfolders_base . $delimiter . $year;
                break;
            case SMPREF_SENT_SUBFOLDERS_MONTHLY:
                $level = 2;
                $sent_subfolder = $sent_subfolders_base . $delimiter . $year . $delimiter . $month;
                $year_folder = $sent_subfolders_base . $delimiter . $year;
                break;
            case SMPREF_SENT_SUBFOLDERS_DISABLED:
            default:
                $level = 0;
                $sent_subfolder = $sent_folder;
                $year_folder = $sent_folder;
        }
        /* If this folder is NOT the current sent folder, update stuff. */
        if ($sent_subfolder != $sent_folder) {
            /* Auto-create folders, if they do not yet exist. */
            if ($sent_subfolder != 'none') {
                /* Create the imap connection. */
                $ic = sqimap_login($username, false, $imapServerAddress, $imapPort, 10, $imap_stream_options);
                $boxes = false;
                /**
                 * If sent_subfolder can't store messages (noselect) ||
                 * year_folder can't store subfolders (noinferiors) in level=2 setup ||
                 * subfolder_base can't store subfolders (noinferiors), setup is broken
                 */
                if (sqimap_mailbox_is_noselect($ic, $sent_subfolder, $boxes) || $level == 2 && sqimap_mailbox_is_noinferiors($ic, $year_folder, $boxes) || sqimap_mailbox_is_noinferiors($ic, $sent_subfolders_base, $boxes)) {
                    error_box(_("Sent subfolders options are misconfigured."));
                } else {
                    if ($level == 2) {
                        /* Auto-create the year folder, if it does not yet exist. */
                        if (!sqimap_mailbox_exists($ic, $year_folder)) {
                            sqimap_mailbox_create($ic, $year_folder, 'noselect');
                            // TODO: safety check for imap servers that can't create subfolders
                        } else {
                            if (!sqimap_mailbox_is_subscribed($ic, $year_folder)) {
                                sqimap_subscribe($ic, $year_folder);
                            }
                        }
                    }
                    /* Auto-create the subfolder, if it does not yet exist. */
                    if (!sqimap_mailbox_exists($ic, $sent_subfolder)) {
                        sqimap_mailbox_create($ic, $sent_subfolder, '');
                    } else {
                        if (!sqimap_mailbox_is_subscribed($ic, $sent_subfolder)) {
                            sqimap_subscribe($ic, $sent_subfolder);
                        }
                    }
                    /* Update sent_folder setting in prefs only if the base
                       subfolders setting is not the same as the normal sent
                       folder...  otherwise, it is quite misleading to the user.
                       If the sent folder is the same as the subfolders base, it's
                       OK to leave the sent folder as is.
                       The sent_folder setting itself needs to be the actual
                       subfolder (not the base) for proper functionality */
                    if ($sent_subfolders_base != $sent_folder) {
                        setPref($data_dir, $username, 'sent_folder', $sent_subfolders_base);
                        setPref($data_dir, $username, 'move_to_sent', SMPREF_ON);
                        setPref($data_dir, $username, 'translate_special_folders', SMPREF_OFF);
                    }
                    $sent_folder = $sent_subfolder;
                    $move_to_sent = SMPREF_ON;
                }
                /* Close the imap connection. */
                sqimap_logout($ic);
            }
        }
    }
}
    }
}
/** First create the top node in the tree **/
for ($i = 0; $i < $numboxes; $i++) {
    if ($boxes[$i]['unformatted-dm'] == $mailbox && strlen($boxes[$i]['unformatted-dm']) == strlen($mailbox)) {
        $foldersTree[0]['value'] = $mailbox;
        $foldersTree[0]['doIHaveChildren'] = false;
        continue;
    }
}
/* Now create the nodes for subfolders of the parent folder
   You can tell that it is a subfolder by tacking the mailbox delimiter
   on the end of the $mailbox string, and compare to that.  */
for ($i = 0; $i < $numboxes; $i++) {
    if (substr($boxes[$i]['unformatted'], 0, strlen($mailbox_no_dm . $delimiter)) == $mailbox_no_dm . $delimiter) {
        addChildNodeToTree($boxes[$i]["unformatted"], $boxes[$i]['unformatted-dm'], $foldersTree);
    }
}
/** Lets start removing the folders and messages **/
if ($move_to_trash == true && $can_move_to_trash == true) {
    /** if they wish to move messages to the trash **/
    walkTreeInPostOrderCreatingFoldersUnderTrash(0, $imap_stream, $foldersTree, $mailbox);
    walkTreeInPreOrderDeleteFolders(0, $imap_stream, $foldersTree);
} else {
    /** if they do NOT wish to move messages to the trash (or cannot)**/
    walkTreeInPreOrderDeleteFolders(0, $imap_stream, $foldersTree);
}
/** Log out this session **/
sqimap_logout($imap_stream);
$location = get_location();
header("Location: {$location}/folders.php?success=delete");
Example #7
0
/**
 * This function builds an array with all the information about
 * the options available to the user, and returns it. The options
 * are grouped by the groups in which they are displayed.
 * For each option, the following information is stored:
 * - name: the internal (variable) name
 * - caption: the description of the option in the UI
 * - type: one of SMOPT_TYPE_*
 * - refresh: one of SMOPT_REFRESH_*
 * - size: one of SMOPT_SIZE_*
 * - save: the name of a function to call when saving this option
 * @return array all option information
 */
function load_optpage_data_folder()
{
    global $username, $key, $imapServerAddress, $imapPort;
    global $folder_prefix, $default_folder_prefix, $show_prefix_option;
    /* Get some imap data we need later. */
    $imapConnection = sqimap_login($username, $key, $imapServerAddress, $imapPort, 0);
    $boxes = sqimap_mailbox_list($imapConnection);
    /* Build a simple array into which we will build options. */
    $optgrps = array();
    $optvals = array();
    /******************************************************/
    /* LOAD EACH GROUP OF OPTIONS INTO THE OPTIONS ARRAY. */
    /******************************************************/
    /*** Load the General Options into the array ***/
    $optgrps[SMOPT_GRP_SPCFOLDER] = _("Special Folder Options");
    $optvals[SMOPT_GRP_SPCFOLDER] = array();
    if (!isset($folder_prefix)) {
        $folder_prefix = $default_folder_prefix;
    }
    if ($show_prefix_option) {
        $optvals[SMOPT_GRP_SPCFOLDER][] = array('name' => 'folder_prefix', 'caption' => _("Folder Path"), 'type' => SMOPT_TYPE_STRING, 'refresh' => SMOPT_REFRESH_FOLDERLIST, 'size' => SMOPT_SIZE_LARGE);
    }
    $trash_folder_values = array(SMPREF_NONE => '[ ' . _("Do not use Trash") . ' ]', 'whatever' => $boxes);
    $optvals[SMOPT_GRP_SPCFOLDER][] = array('name' => 'trash_folder', 'caption' => _("Trash Folder"), 'type' => SMOPT_TYPE_FLDRLIST, 'refresh' => SMOPT_REFRESH_FOLDERLIST, 'posvals' => $trash_folder_values, 'save' => 'save_option_trash_folder');
    $draft_folder_values = array(SMPREF_NONE => '[ ' . _("Do not use Drafts") . ' ]', 'whatever' => $boxes);
    $optvals[SMOPT_GRP_SPCFOLDER][] = array('name' => 'draft_folder', 'caption' => _("Draft Folder"), 'type' => SMOPT_TYPE_FLDRLIST, 'refresh' => SMOPT_REFRESH_FOLDERLIST, 'posvals' => $draft_folder_values, 'save' => 'save_option_draft_folder');
    $sent_folder_values = array(SMPREF_NONE => '[ ' . _("Do not use Sent") . ' ]', 'whatever' => $boxes);
    $optvals[SMOPT_GRP_SPCFOLDER][] = array('name' => 'sent_folder', 'caption' => _("Sent Folder"), 'type' => SMOPT_TYPE_FLDRLIST, 'refresh' => SMOPT_REFRESH_FOLDERLIST, 'posvals' => $sent_folder_values, 'save' => 'save_option_sent_folder');
    /*** Load the General Options into the array ***/
    $optgrps[SMOPT_GRP_FOLDERLIST] = _("Folder List Options");
    $optvals[SMOPT_GRP_FOLDERLIST] = array();
    $optvals[SMOPT_GRP_FOLDERLIST][] = array('name' => 'location_of_bar', 'caption' => _("Location of Folder List"), 'type' => SMOPT_TYPE_STRLIST, 'refresh' => SMOPT_REFRESH_ALL, 'posvals' => array(SMPREF_LOC_LEFT => _("Left"), SMPREF_LOC_RIGHT => _("Right")));
    $left_size_values = array();
    for ($lsv = 100; $lsv <= 300; $lsv += 10) {
        $left_size_values[$lsv] = "{$lsv} " . _("pixels");
    }
    $optvals[SMOPT_GRP_FOLDERLIST][] = array('name' => 'left_size', 'caption' => _("Width of Folder List"), 'type' => SMOPT_TYPE_STRLIST, 'refresh' => SMOPT_REFRESH_ALL, 'posvals' => $left_size_values);
    $minute_str = _("Minutes");
    $left_refresh_values = array(SMPREF_NONE => _("Never"));
    foreach (array(30, 60, 120, 180, 300, 600, 1200) as $lr_val) {
        if ($lr_val < 60) {
            $left_refresh_values[$lr_val] = "{$lr_val} " . _("Seconds");
        } else {
            if ($lr_val == 60) {
                $left_refresh_values[$lr_val] = "1 " . _("Minute");
            } else {
                $left_refresh_values[$lr_val] = $lr_val / 60 . " {$minute_str}";
            }
        }
    }
    $optvals[SMOPT_GRP_FOLDERLIST][] = array('name' => 'left_refresh', 'caption' => _("Auto Refresh Folder List"), 'type' => SMOPT_TYPE_STRLIST, 'refresh' => SMOPT_REFRESH_FOLDERLIST, 'posvals' => $left_refresh_values);
    $optvals[SMOPT_GRP_FOLDERLIST][] = array('name' => 'unseen_notify', 'caption' => _("Enable Unread Message Notification"), 'type' => SMOPT_TYPE_STRLIST, 'refresh' => SMOPT_REFRESH_FOLDERLIST, 'posvals' => array(SMPREF_UNSEEN_NONE => _("No Notification"), SMPREF_UNSEEN_INBOX => _("Only INBOX"), SMPREF_UNSEEN_ALL => _("All Folders")));
    $optvals[SMOPT_GRP_FOLDERLIST][] = array('name' => 'unseen_type', 'caption' => _("Unread Message Notification Type"), 'type' => SMOPT_TYPE_STRLIST, 'refresh' => SMOPT_REFRESH_FOLDERLIST, 'posvals' => array(SMPREF_UNSEEN_ONLY => _("Only Unseen"), SMPREF_UNSEEN_TOTAL => _("Unseen and Total")));
    $optvals[SMOPT_GRP_FOLDERLIST][] = array('name' => 'collapse_folders', 'caption' => _("Enable Collapsable Folders"), 'type' => SMOPT_TYPE_BOOLEAN, 'refresh' => SMOPT_REFRESH_FOLDERLIST);
    $optvals[SMOPT_GRP_FOLDERLIST][] = array('name' => 'unseen_cum', 'caption' => _("Enable Cumulative Unread Message Notification"), 'type' => SMOPT_TYPE_BOOLEAN, 'refresh' => SMOPT_REFRESH_FOLDERLIST);
    $optvals[SMOPT_GRP_FOLDERLIST][] = array('name' => 'date_format', 'caption' => _("Show Clock on Folders Panel"), 'type' => SMOPT_TYPE_STRLIST, 'refresh' => SMOPT_REFRESH_FOLDERLIST, 'posvals' => array('0' => _("International date and time"), '1' => _("American date and time"), '2' => _("European date and time"), '3' => _("Show weekday and time"), '4' => _("Show time with seconds"), '5' => _("Show time"), '6' => _("No Clock")));
    $optvals[SMOPT_GRP_FOLDERLIST][] = array('name' => 'hour_format', 'caption' => _("Hour Format"), 'type' => SMOPT_TYPE_STRLIST, 'refresh' => SMOPT_REFRESH_FOLDERLIST, 'posvals' => array(SMPREF_TIME_12HR => _("12-hour clock"), SMPREF_TIME_24HR => _("24-hour clock")));
    $optvals[SMOPT_GRP_FOLDERLIST][] = array('name' => 'search_memory', 'caption' => _("Memory Search"), 'type' => SMOPT_TYPE_STRLIST, 'refresh' => SMOPT_REFRESH_NONE, 'posvals' => array(0 => _("Disabled"), 1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9'));
    /*** Load the General Options into the array ***/
    $optgrps[SMOPT_GRP_FOLDERSELECT] = _("Folder Selection Options");
    $optvals[SMOPT_GRP_FOLDERSELECT] = array();
    $delim = sqimap_get_delimiter($imapConnection);
    $optvals[SMOPT_GRP_FOLDERSELECT][] = array('name' => 'mailbox_select_style', 'caption' => _("Selection List Style"), 'type' => SMOPT_TYPE_STRLIST, 'refresh' => SMOPT_REFRESH_NONE, 'posvals' => array(0 => _("Long:") . ' "' . _("Folder") . $delim . _("Subfolder") . '"', 1 => _("Indented:") . ' "&nbsp;&nbsp;&nbsp;&nbsp;' . _("Subfolder") . '"', 2 => _("Delimited:") . ' ".&nbsp;' . _("Subfolder") . '"'), 'htmlencoded' => true);
    /* Assemble all this together and return it as our result. */
    $result = array('grps' => $optgrps, 'vals' => $optvals);
    sqimap_logout($imapConnection);
    return $result;
}
Example #8
0
/**
 * Given a list of folder names, unsubscribes from each of them.
 */
function folders_unsubscribe($imapConnection, $folder_names)
{
    global $color, $oTemplate;
    if (count($folder_names) == 0 || $folder_names[0] == '') {
        plain_error_message(_("You have not selected a folder to unsubscribe. Please do so.") . '<br /><a href="../src/folders.php">' . _("Click here to go back") . '</a>.', $color);
        sqimap_logout($imapConnection);
        $oTemplate->display('footer.tpl');
        exit;
    }
    foreach ($folder_names as $folder_name) {
        sqimap_unsubscribe($imapConnection, $folder_name);
    }
    return;
}
Example #9
0
/**
 * temporary function to make use of the deliver class.
 * In the future the responsible backend should be automaticly loaded
 * and conf.pl should show a list of available backends.
 * The message also should be constructed by the message class.
 *
 * @param object $composeMessage The message being sent.  Please note
 *                               that it is passed by reference and
 *                               will be returned modified, with additional
 *                               headers, such as Message-ID, Date, In-Reply-To,
 *                               References, and so forth.
 *
 * @return boolean FALSE if delivery failed, or some non-FALSE value
 *                 upon success.
 *
 */
function deliverMessage(&$composeMessage, $draft = false)
{
    global $send_to, $send_to_cc, $send_to_bcc, $mailprio, $subject, $body, $username, $identity, $idents, $data_dir, $request_mdn, $request_dr, $default_charset, $useSendmail, $domain, $action, $default_move_to_sent, $move_to_sent, $imapServerAddress, $imapPort, $imap_stream_options, $sent_folder, $key;
    $rfc822_header = $composeMessage->rfc822_header;
    $abook = addressbook_init(false, true);
    $rfc822_header->to = $rfc822_header->parseAddress($send_to, true, array(), '', $domain, array(&$abook, 'lookup'));
    $rfc822_header->cc = $rfc822_header->parseAddress($send_to_cc, true, array(), '', $domain, array(&$abook, 'lookup'));
    $rfc822_header->bcc = $rfc822_header->parseAddress($send_to_bcc, true, array(), '', $domain, array(&$abook, 'lookup'));
    $rfc822_header->priority = $mailprio;
    $rfc822_header->subject = $subject;
    $special_encoding = '';
    if (strtolower($default_charset) == 'iso-2022-jp') {
        if (mb_detect_encoding($body) == 'ASCII') {
            $special_encoding = '8bit';
        } else {
            $body = mb_convert_encoding($body, 'JIS');
            $special_encoding = '7bit';
        }
    }
    $composeMessage->setBody($body);
    $reply_to = '';
    $reply_to = $idents[$identity]['reply_to'];
    if ($reply_to && strpos($reply_to, '@') === FALSE) {
        $reply_to .= '@' . $domain;
    }
    $from_addr = build_from_header($identity);
    $rfc822_header->from = $rfc822_header->parseAddress($from_addr, true);
    if ($reply_to) {
        $rfc822_header->reply_to = $rfc822_header->parseAddress($reply_to, true);
    }
    /* Receipt: On Read */
    if (isset($request_mdn) && $request_mdn) {
        $rfc822_header->dnt = $rfc822_header->parseAddress($from_addr, true);
    } elseif (isset($rfc822_header->dnt)) {
        unset($rfc822_header->dnt);
    }
    /* Receipt: On Delivery */
    if (!empty($request_dr)) {
        //FIXME: it would be better to fiddle with headers inside of the message object or possibly when delivering the message to its destination; is this possible?
        $rfc822_header->more_headers['Return-Receipt-To'] = $from_addr;
    } elseif (isset($rfc822_header->more_headers['Return-Receipt-To'])) {
        unset($rfc822_header->more_headers['Return-Receipt-To']);
    }
    /* multipart messages */
    if (count($composeMessage->entities)) {
        $message_body = new Message();
        $message_body->body_part = $composeMessage->body_part;
        $composeMessage->body_part = '';
        $mime_header = new MessageHeader();
        $mime_header->type0 = 'text';
        $mime_header->type1 = 'plain';
        if ($special_encoding) {
            $mime_header->encoding = $special_encoding;
        } else {
            $mime_header->encoding = '8bit';
        }
        if ($default_charset) {
            $mime_header->parameters['charset'] = $default_charset;
        }
        $message_body->mime_header = $mime_header;
        array_unshift($composeMessage->entities, $message_body);
        $content_type = new ContentType('multipart/mixed');
    } else {
        $content_type = new ContentType('text/plain');
        if ($special_encoding) {
            $rfc822_header->encoding = $special_encoding;
        } else {
            $rfc822_header->encoding = '8bit';
        }
        if ($default_charset) {
            $content_type->properties['charset'] = $default_charset;
        }
    }
    $rfc822_header->content_type = $content_type;
    $composeMessage->rfc822_header = $rfc822_header;
    if ($action == 'reply' || $action == 'reply_all') {
        global $passed_id, $passed_ent_id;
        $reply_id = $passed_id;
        $reply_ent_id = $passed_ent_id;
    } else {
        $reply_id = '';
        $reply_ent_id = '';
    }
    /* Here you can modify the message structure just before we hand
       it over to deliver; plugin authors note that $composeMessage
       is sent and modified by reference since 1.5.2 */
    do_hook('compose_send', $composeMessage);
    if (!$useSendmail && !$draft) {
        require_once SM_PATH . 'class/deliver/Deliver_SMTP.class.php';
        $deliver = new Deliver_SMTP();
        global $smtpServerAddress, $smtpPort, $smtp_stream_options, $pop_before_smtp, $pop_before_smtp_host;
        $authPop = isset($pop_before_smtp) && $pop_before_smtp ? true : false;
        if (empty($pop_before_smtp_host)) {
            $pop_before_smtp_host = $smtpServerAddress;
        }
        get_smtp_user($user, $pass);
        $stream = $deliver->initStream($composeMessage, $domain, 0, $smtpServerAddress, $smtpPort, $user, $pass, $authPop, $pop_before_smtp_host, $smtp_stream_options);
    } elseif (!$draft) {
        require_once SM_PATH . 'class/deliver/Deliver_SendMail.class.php';
        global $sendmail_path, $sendmail_args;
        // Check for outdated configuration
        if (!isset($sendmail_args)) {
            if ($sendmail_path == '/var/qmail/bin/qmail-inject') {
                $sendmail_args = '';
            } else {
                $sendmail_args = '-i -t';
            }
        }
        $deliver = new Deliver_SendMail(array('sendmail_args' => $sendmail_args));
        $stream = $deliver->initStream($composeMessage, $sendmail_path);
    } elseif ($draft) {
        global $draft_folder;
        $imap_stream = sqimap_login($username, false, $imapServerAddress, $imapPort, 0, $imap_stream_options);
        if (sqimap_mailbox_exists($imap_stream, $draft_folder)) {
            require_once SM_PATH . 'class/deliver/Deliver_IMAP.class.php';
            $imap_deliver = new Deliver_IMAP();
            $success = $imap_deliver->mail($composeMessage, $imap_stream, $reply_id, $reply_ent_id, $imap_stream, $draft_folder);
            sqimap_logout($imap_stream);
            unset($imap_deliver);
            $composeMessage->purgeAttachments();
            return $success;
        } else {
            $msg = '<br />' . sprintf(_("Error: Draft folder %s does not exist."), sm_encode_html_special_chars($draft_folder));
            plain_error_message($msg);
            return false;
        }
    }
    $success = false;
    if ($stream) {
        $deliver->mail($composeMessage, $stream, $reply_id, $reply_ent_id);
        $success = $deliver->finalizeStream($stream);
    }
    if (!$success) {
        // $deliver->dlv_server_msg is not always server's reply
        $msg = _("Message not sent.") . "<br />\n" . (isset($deliver->dlv_msg) ? $deliver->dlv_msg : '');
        if (!empty($deliver->dlv_server_msg)) {
            // add 'server replied' part only when it is not empty.
            // Delivery error can be generated by delivery class itself
            $msg .= '<br />' . _("Server replied:") . ' ' . (isset($deliver->dlv_ret_nr) ? $deliver->dlv_ret_nr . ' ' : '') . nl2br(sm_encode_html_special_chars($deliver->dlv_server_msg));
        }
        plain_error_message($msg);
    } else {
        unset($deliver);
        $imap_stream = sqimap_login($username, false, $imapServerAddress, $imapPort, 0, $imap_stream_options);
        // mark as replied or forwarded if applicable
        //
        global $what, $iAccount, $startMessage, $passed_id, $fwduid, $mailbox;
        if ($action == 'reply' || $action == 'reply_all' || $action == 'forward' || $action == 'forward_as_attachment') {
            require SM_PATH . 'functions/mailbox_display.php';
            $aMailbox = sqm_api_mailbox_select($imap_stream, $iAccount, $mailbox, array('setindex' => $what, 'offset' => $startMessage), array());
            switch ($action) {
                case 'reply':
                case 'reply_all':
                    // check if we are allowed to set the \\Answered flag
                    if (in_array('\\answered', $aMailbox['PERMANENTFLAGS'], true)) {
                        $aUpdatedMsgs = sqimap_toggle_flag($imap_stream, array($passed_id), '\\Answered', true, false);
                        if (isset($aUpdatedMsgs[$passed_id]['FLAGS'])) {
                            /**
                             * Only update the cached headers if the header is
                             * cached.
                             */
                            if (isset($aMailbox['MSG_HEADERS'][$passed_id])) {
                                $aMailbox['MSG_HEADERS'][$passed_id]['FLAGS'] = $aMsg['FLAGS'];
                            }
                        }
                    }
                    break;
                case 'forward':
                case 'forward_as_attachment':
                    // check if we are allowed to set the $Forwarded flag (RFC 4550 paragraph 2.8)
                    if (in_array('$forwarded', $aMailbox['PERMANENTFLAGS'], true) || in_array('\\*', $aMailbox['PERMANENTFLAGS'])) {
                        // when forwarding as an attachment from the message
                        // list, passed_id is not used, need to get UID(s)
                        // from the query string
                        //
                        if (empty($passed_id) && !empty($fwduid)) {
                            $ids = explode('_', $fwduid);
                        } else {
                            $ids = array($passed_id);
                        }
                        $aUpdatedMsgs = sqimap_toggle_flag($imap_stream, $ids, '$Forwarded', true, false);
                        foreach ($ids as $id) {
                            if (isset($aUpdatedMsgs[$id]['FLAGS'])) {
                                if (isset($aMailbox['MSG_HEADERS'][$id])) {
                                    $aMailbox['MSG_HEADERS'][$id]['FLAGS'] = $aMsg['FLAGS'];
                                }
                            }
                        }
                    }
                    break;
            }
            /**
             * Write mailbox with updated seen flag information back to cache.
             */
            if (isset($aUpdatedMsgs[$passed_id])) {
                $mailbox_cache[$iAccount . '_' . $aMailbox['NAME']] = $aMailbox;
                sqsession_register($mailbox_cache, 'mailbox_cache');
            }
        }
        // move to sent folder
        //
        $move_to_sent = getPref($data_dir, $username, 'move_to_sent');
        if (isset($default_move_to_sent) && $default_move_to_sent != 0) {
            $svr_allow_sent = true;
        } else {
            $svr_allow_sent = false;
        }
        if (isset($sent_folder) && ($sent_folder != '' || $sent_folder != 'none') && sqimap_mailbox_exists($imap_stream, $sent_folder)) {
            $fld_sent = true;
        } else {
            $fld_sent = false;
        }
        if (isset($move_to_sent) && $move_to_sent != 0 || !isset($move_to_sent)) {
            $lcl_allow_sent = true;
        } else {
            $lcl_allow_sent = false;
        }
        if ($fld_sent && $svr_allow_sent && !$lcl_allow_sent || $fld_sent && $lcl_allow_sent) {
            if ($action == 'reply' || $action == 'reply_all') {
                $save_reply_with_orig = getPref($data_dir, $username, 'save_reply_with_orig');
                if ($save_reply_with_orig) {
                    $sent_folder = $mailbox;
                }
            }
            require_once SM_PATH . 'class/deliver/Deliver_IMAP.class.php';
            $imap_deliver = new Deliver_IMAP();
            $imap_deliver->mail($composeMessage, $imap_stream, $reply_id, $reply_ent_id, $imap_stream, $sent_folder);
            unset($imap_deliver);
        }
        // final cleanup
        //
        $composeMessage->purgeAttachments();
        sqimap_logout($imap_stream);
    }
    return $success;
}
Example #10
0
 /**
  * function mail - send the message parts to the SMTP stream
  *
  * @param Message  $message      Message object to send
  *                               NOTE that this is passed by
  *                               reference and will be modified
  *                               upon return with updated
  *                               fields such as Message ID, References,
  *                               In-Reply-To and Date headers.
  * @param resource $stream       Handle to the outgoing stream
  *                               (when FALSE, nothing will be
  *                               written to the stream; this can
  *                               be used to determine the actual
  *                               number of bytes that will be 
  *                               written to the stream)
  * @param string   $reply_id     Identifies message being replied to
  *                               (OPTIONAL; caller should ONLY specify
  *                               a value for this when the message
  *                               being sent is a reply)
  * @param string   $reply_ent_id Identifies message being replied to
  *                               in the case it was an embedded/attached
  *                               message inside another (OPTIONAL; caller
  *                               should ONLY specify a value for this 
  *                               when the message being sent is a reply)
  * @param resource $imap_stream  If there is an open IMAP stream in 
  *                               the caller's context, it should be
  *                               passed in here.  This is OPTIONAL,
  *                               as one will be created if not given,
  *                               but as some IMAP servers may baulk
  *                               at opening more than one connection
  *                               at a time, the caller should always
  *                               abide if possible.  Currently, this
  *                               stream is only used when $reply_id
  *                               is also non-zero, but that is subject
  *                               to change.
  * @param mixed    $extra        Any implementation-specific variables
  *                               can be passed in here and used in
  *                               an overloaded version of this method
  *                               if needed.
  *
  * @return integer The number of bytes written (or that would have been
  *                 written) to the output stream.
  *
  */
 function mail(&$message, $stream = false, $reply_id = 0, $reply_ent_id = 0, $imap_stream = NULL, $extra = NULL)
 {
     $rfc822_header =& $message->rfc822_header;
     if (count($message->entities)) {
         $boundary = $this->mimeBoundary();
         $rfc822_header->content_type->properties['boundary'] = '"' . $boundary . '"';
     } else {
         $boundary = '';
     }
     $raw_length = 0;
     // calculate reply header if needed
     //
     if ($reply_id) {
         global $imapConnection, $username, $key, $imapServerAddress, $imapPort, $mailbox;
         // try our best to use an existing IMAP handle
         //
         $close_imap_stream = FALSE;
         if (is_resource($imap_stream)) {
             $my_imap_stream = $imap_stream;
         } else {
             if (is_resource($imapConnection)) {
                 $my_imap_stream = $imapConnection;
             } else {
                 $close_imap_stream = TRUE;
                 $my_imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 0);
             }
         }
         sqimap_mailbox_select($my_imap_stream, $mailbox);
         $reply_message = sqimap_get_message($my_imap_stream, $reply_id, $mailbox);
         if ($close_imap_stream) {
             sqimap_logout($my_imap_stream);
         }
         if ($reply_ent_id) {
             /* redefine the messsage in case of message/rfc822 */
             $reply_message = $message->getEntity($reply_ent_id);
             /* message is an entity which contains the envelope and type0=message
              * and type1=rfc822. The actual entities are childs from
              * $reply_message->entities[0]. That's where the encoding and is located
              */
             $orig_header = $reply_message->rfc822_header;
             /* here is the envelope located */
         } else {
             $orig_header = $reply_message->rfc822_header;
         }
         $message->reply_rfc822_header = $orig_header;
     }
     $reply_rfc822_header = isset($message->reply_rfc822_header) ? $message->reply_rfc822_header : '';
     $header = $this->prepareRFC822_Header($rfc822_header, $reply_rfc822_header, $raw_length);
     $this->send_mail($message, $header, $boundary, $stream, $raw_length, $extra);
     return $raw_length;
 }
Example #11
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);
}
Example #12
0
/**
 * Selects a mailbox
 * Before 1.3.0 used more arguments and returned data depended on those arguments.
 * @param stream $imap_stream imap connection resource
 * @param string $mailbox mailbox name
 * @return array results of select command (on success - permanentflags, flags and rights)
 * @since 1.0 or older
 */
function sqimap_mailbox_select($imap_stream, $mailbox)
{
    if (empty($mailbox)) {
        return;
    }
    // cleanup $mailbox in order to prevent IMAP injection attacks
    $mailbox = str_replace(array("\r", "\n"), array("", ""), $mailbox);
    /**
     * Default UW IMAP server configuration allows to access other files
     * on server. $imap_server_type is not checked because interface can
     * be used with 'other' or any other server type setting. $mailbox
     * variable can be modified in any script that uses variable from GET
     * or POST. This code blocks all standard SquirrelMail IMAP API requests
     * that use mailbox with full path (/etc/passwd) or with ../ characters
     * in path (../../etc/passwd)
     */
    if (strstr($mailbox, '../') || substr($mailbox, 0, 1) == '/') {
        global $oTemplate;
        error_box(sprintf(_("Invalid mailbox name: %s"), sm_encode_html_special_chars($mailbox)));
        sqimap_logout($imap_stream);
        $oTemplate->display('footer.tpl');
        die;
    }
    $read = sqimap_run_command($imap_stream, 'SELECT ' . sqimap_encode_mailbox_name($mailbox), true, $response, $message);
    $result = array();
    for ($i = 0, $cnt = count($read); $i < $cnt; $i++) {
        if (preg_match('/^\\*\\s+OK\\s\\[(\\w+)\\s(\\w+)\\]/', $read[$i], $regs)) {
            $result[strtoupper($regs[1])] = $regs[2];
        } else {
            if (preg_match('/^\\*\\s([0-9]+)\\s(\\w+)/', $read[$i], $regs)) {
                $result[strtoupper($regs[2])] = $regs[1];
            } else {
                if (preg_match("/PERMANENTFLAGS(.*)/i", $read[$i], $regs)) {
                    $regs[1] = trim(preg_replace(array("/\\(/", "/\\)/", "/\\]/"), '', $regs[1]));
                    $result['PERMANENTFLAGS'] = explode(' ', strtolower($regs[1]));
                } else {
                    if (preg_match("/FLAGS(.*)/i", $read[$i], $regs)) {
                        $regs[1] = trim(preg_replace(array("/\\(/", "/\\)/"), '', $regs[1]));
                        $result['FLAGS'] = explode(' ', strtolower($regs[1]));
                    }
                }
            }
        }
    }
    if (!isset($result['PERMANENTFLAGS'])) {
        $result['PERMANENTFLAGS'] = $result['FLAGS'];
    }
    if (preg_match('/^\\[(.+)\\]/', $message, $regs)) {
        $result['RIGHTS'] = strtoupper($regs[1]);
    }
    return $result;
}
Example #13
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;
}
Example #14
0
function email_error()
{
    global $imapConnection;
    require $GO_THEME->theme_path . 'header.inc';
    echo '<table border="0" cellpadding="10" width="100%"><tr><td>';
    echo '<p class="Error">' . $ml_connect_failed . ' \'' . $account['host'] . '\' ' . $ml_at_port . ': ' . $account['port'] . '</p>';
    echo '<p class="Error">' . imap_last_error() . '</p>';
    require $GO_THEME->theme_path . 'footer.inc';
    sqimap_logout($imapConnection);
    exit;
}
Example #15
0
function mail_fetch_login()
{
    require_once SM_PATH . 'include/validate.php';
    include_once SM_PATH . 'functions/imap.php';
    require_once SM_PATH . 'plugins/mail_fetch/class.POP3.php';
    require_once SM_PATH . 'plugins/mail_fetch/functions.php';
    global $data_dir, $imapServerAddress, $imapPort;
    sqgetGlobalVar('username', $username, SQ_SESSION);
    sqgetGlobalVar('key', $key, SQ_COOKIE);
    $mailfetch_newlog = getPref($data_dir, $username, 'mailfetch_newlog');
    $outMsg = '';
    $mailfetch_server_number = getPref($data_dir, $username, 'mailfetch_server_number');
    if (!isset($mailfetch_server_number)) {
        $mailfetch_server_number = 0;
    }
    $mailfetch_cypher = getPref($data_dir, $username, 'mailfetch_cypher');
    if ($mailfetch_server_number < 1) {
        $mailfetch_server_number = 0;
    }
    for ($i_loop = 0; $i_loop < $mailfetch_server_number; $i_loop++) {
        $mailfetch_login_[$i_loop] = getPref($data_dir, $username, "mailfetch_login_{$i_loop}");
        $mailfetch_fref_[$i_loop] = getPref($data_dir, $username, "mailfetch_fref_{$i_loop}");
        $mailfetch_pass_[$i_loop] = getPref($data_dir, $username, "mailfetch_pass_{$i_loop}");
        if ($mailfetch_cypher == 'on') {
            $mailfetch_pass_[$i_loop] = decrypt($mailfetch_pass_[$i_loop]);
        }
        if ($mailfetch_pass_[$i_loop] != '' && ($mailfetch_login_[$i_loop] == 'on' && $mailfetch_newlog == 'on' || $mailfetch_fref_[$i_loop] == 'on')) {
            $mailfetch_server_[$i_loop] = getPref($data_dir, $username, "mailfetch_server_{$i_loop}");
            $mailfetch_port_[$i_loop] = getPref($data_dir, $username, "mailfetch_port_{$i_loop}");
            $mailfetch_alias_[$i_loop] = getPref($data_dir, $username, "mailfetch_alias_{$i_loop}");
            $mailfetch_user_[$i_loop] = getPref($data_dir, $username, "mailfetch_user_{$i_loop}");
            $mailfetch_lmos_[$i_loop] = getPref($data_dir, $username, "mailfetch_lmos_{$i_loop}");
            $mailfetch_uidl_[$i_loop] = getPref($data_dir, $username, "mailfetch_uidl_{$i_loop}");
            $mailfetch_subfolder_[$i_loop] = getPref($data_dir, $username, "mailfetch_subfolder_{$i_loop}");
            $mailfetch_server = $mailfetch_server_[$i_loop];
            $mailfetch_port = $mailfetch_port_[$i_loop];
            $mailfetch_user = $mailfetch_user_[$i_loop];
            $mailfetch_alias = $mailfetch_alias_[$i_loop];
            $mailfetch_pass = $mailfetch_pass_[$i_loop];
            $mailfetch_lmos = $mailfetch_lmos_[$i_loop];
            $mailfetch_login = $mailfetch_login_[$i_loop];
            $mailfetch_uidl = $mailfetch_uidl_[$i_loop];
            $mailfetch_subfolder = $mailfetch_subfolder_[$i_loop];
            // $outMsg .= "$mailfetch_alias checked<br>";
            // $outMsg .= "$mailfetch_alias_[$i_loop]<br>";
            $pop3 = new POP3($mailfetch_server, 60);
            if (!$pop3->connect($mailfetch_server, $mailfetch_port)) {
                $outMsg .= _("Warning, ") . $pop3->ERROR;
                continue;
            }
            $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 10);
            $Count = $pop3->login($mailfetch_user, $mailfetch_pass);
            if (($Count == false || $Count == -1) && $pop3->ERROR != '') {
                $outMsg .= _("Login Failed:") . $pop3->ERROR;
                continue;
            }
            //   register_shutdown_function($pop3->quit());
            $msglist = $pop3->uidl();
            $i = 1;
            for ($j = 1; $j < sizeof($msglist); $j++) {
                if ($msglist["{$j}"] == $mailfetch_uidl) {
                    $i = $j + 1;
                    break;
                }
            }
            if ($Count < $i) {
                $pop3->quit();
                continue;
            }
            if ($Count == 0) {
                $pop3->quit();
                continue;
            } else {
                $newmsgcount = $Count - $i + 1;
            }
            // Faster to get them all at once
            $mailfetch_uidl = $pop3->uidl();
            if (!is_array($mailfetch_uidl) && $mailfetch_lmos == 'on') {
                $outMsg .= _("Server does not support UIDL.");
            }
            for (; $i <= $Count; $i++) {
                if (!ini_get('safe_mode')) {
                    set_time_limit(20);
                }
                // 20 seconds per message max
                $Message = "";
                $MessArray = $pop3->get($i);
                if (!$MessArray or gettype($MessArray) != "array") {
                    $outMsg .= _("Warning, ") . $pop3->ERROR;
                    continue 2;
                }
                while (list($lineNum, $line) = each($MessArray)) {
                    $Message .= $line;
                }
                /**
                 * check if mail folder is not null and subscribed
                 * Function can check if mail folder is only unsubscribed 
                 * and use unsubscribed mail folder.
                 */
                if ($mailfetch_subfolder == '' || !mail_fetch_check_folder($imap_stream, $mailfetch_subfolder)) {
                    fputs($imap_stream, "A3{$i} APPEND INBOX {" . strlen($Message) . "}\r\n");
                } else {
                    fputs($imap_stream, "A3{$i} APPEND {$mailfetch_subfolder} {" . strlen($Message) . "}\r\n");
                }
                $Line = fgets($imap_stream, 1024);
                if (substr($Line, 0, 1) == '+') {
                    fputs($imap_stream, $Message);
                    fputs($imap_stream, "\r\n");
                    sqimap_read_data($imap_stream, "A3{$i}", false, $response, $message);
                    if ($mailfetch_lmos != 'on') {
                        $pop3->delete($i);
                    }
                } else {
                    echo "{$Line}";
                    $outMsg .= _("Error Appending Message!");
                }
            }
            $pop3->quit();
            sqimap_logout($imap_stream);
            if (is_array($mailfetch_uidl)) {
                setPref($data_dir, $username, "mailfetch_uidl_{$i_loop}", array_pop($mailfetch_uidl));
            }
        }
    }
    if (trim($outMsg) != '') {
        echo '<br><font size="1">' . _("Mail Fetch Result:") . "<br>{$outMsg}</font>";
    }
    if ($mailfetch_newlog == 'on') {
        setPref($data_dir, $username, 'mailfetch_newlog', 'off');
    }
}
Example #16
0
$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, 
 * squelches the display of the login form and puts up a message
 * explaining the situation.
 */
if ($imap_auth_mech == 'login') {
    $imap = sqimap_create_stream($imapServerAddress, $imapPort, $use_imap_tls);
    $logindisabled = sqimap_capability($imap, 'LOGINDISABLED');
    sqimap_logout($imap);
    if ($logindisabled) {
        $string = _("The IMAP server is reporting that plain text logins are disabled.") . '<br />' . _("Using CRAM-MD5 or DIGEST-MD5 authentication instead may work.") . '<br />';
        if (!$use_imap_tls) {
            $string .= _("Also, the use of TLS may allow SquirrelMail to login.") . '<br />';
        }
        $string .= _("Please contact your system administrator and report this error.");
        error_box($string, $color);
        exit;
    }
}
do_hook('login_cookie');
/* Output the javascript onload function. */
$header = "<script language=\"JavaScript\" type=\"text/javascript\">\n" . "<!--\n" . "  function squirrelmail_loginpage_onload() {\n" . "    var textElements = 0;\n" . "    for (i = 0; i < document.forms[0].elements.length; i++) {\n" . "      if (document.forms[0].elements[i].type == \"text\" || document.forms[0].elements[i].type == \"password\") {\n" . "        textElements++;\n" . "        if (textElements == " . (isset($loginname) ? 2 : 1) . ") {\n" . "          document.forms[0].elements[i].focus();\n" . "          break;\n" . "        }\n" . "      }\n" . "    }\n" . "  }\n" . "// -->\n" . "</script>\n";
if (@file_exists($theme[$theme_default]['PATH'])) {
    @(include $theme[$theme_default]['PATH']);
/**
 * 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;
}
Example #18
0
/**
 * FIXME: Undocumented function
 * @access private
 */
function start_filters()
{
    global $mailbox, $imapServerAddress, $imapPort, $imap, $imap_general, $filters, $imap_stream, $imapConnection, $UseSeparateImapConnection, $AllowSpamFilters;
    sqgetGlobalVar('username', $username, SQ_SESSION);
    sqgetGlobalVar('key', $key, SQ_COOKIE);
    $filters = load_filters();
    // No point running spam filters if there aren't any to run //
    if ($AllowSpamFilters) {
        $spamfilters = load_spam_filters();
        $AllowSpamFilters = false;
        foreach ($spamfilters as $filterkey => $value) {
            if ($value['enabled'] == SMPREF_ON) {
                $AllowSpamFilters = true;
                break;
            }
        }
    }
    // No user filters, and no spam filters, no need to continue //
    if (!$AllowSpamFilters && empty($filters)) {
        return;
    }
    // Detect if we have already connected to IMAP or not.
    // Also check if we are forced to use a separate IMAP connection
    if (!isset($imap_stream) && !isset($imapConnection) || $UseSeparateImapConnection) {
        $stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 10);
        $previously_connected = false;
    } else {
        if (isset($imapConnection)) {
            $stream = $imapConnection;
            $previously_connected = true;
        } else {
            $previously_connected = true;
            $stream = $imap_stream;
        }
    }
    $aStatus = sqimap_status_messages($stream, 'INBOX', array('MESSAGES'));
    if ($aStatus['MESSAGES']) {
        sqimap_mailbox_select($stream, 'INBOX');
        // Filter spam from inbox before we sort them into folders
        if ($AllowSpamFilters) {
            spam_filters($stream);
        }
        // Sort into folders
        user_filters($stream);
    }
    if (!$previously_connected) {
        sqimap_logout($stream);
    }
}
Example #19
0
/**
 * Internal function used to fetch pop3 mails on login
 * @since 1.5.1
 * @private
 */
function mail_fetch_login_function()
{
    include_once SM_PATH . 'functions/imap_general.php';
    global $username, $data_dir, $imapServerAddress, $imapPort, $imap_stream_options;
    $mailfetch_newlog = getPref($data_dir, $username, 'mailfetch_newlog');
    $outMsg = '';
    $mailfetch_server_number = getPref($data_dir, $username, 'mailfetch_server_number');
    if (!isset($mailfetch_server_number)) {
        $mailfetch_server_number = 0;
    }
    $mailfetch_cypher = getPref($data_dir, $username, 'mailfetch_cypher');
    if ($mailfetch_server_number < 1) {
        $mailfetch_server_number = 0;
    }
    for ($i_loop = 0; $i_loop < $mailfetch_server_number; $i_loop++) {
        $mailfetch_login_[$i_loop] = getPref($data_dir, $username, "mailfetch_login_{$i_loop}");
        $mailfetch_fref_[$i_loop] = getPref($data_dir, $username, "mailfetch_fref_{$i_loop}");
        $mailfetch_pass_[$i_loop] = getPref($data_dir, $username, "mailfetch_pass_{$i_loop}");
        if ($mailfetch_cypher == 'on') {
            $mailfetch_pass_[$i_loop] = decrypt($mailfetch_pass_[$i_loop]);
        }
        if ($mailfetch_pass_[$i_loop] != '' && ($mailfetch_login_[$i_loop] == 'on' && $mailfetch_newlog == 'on' || $mailfetch_fref_[$i_loop] == 'on')) {
            // What the heck
            $mailfetch_server_[$i_loop] = getPref($data_dir, $username, "mailfetch_server_{$i_loop}");
            $mailfetch_port_[$i_loop] = getPref($data_dir, $username, "mailfetch_port_{$i_loop}");
            $mailfetch_alias_[$i_loop] = getPref($data_dir, $username, "mailfetch_alias_{$i_loop}");
            $mailfetch_user_[$i_loop] = getPref($data_dir, $username, "mailfetch_user_{$i_loop}");
            $mailfetch_lmos_[$i_loop] = getPref($data_dir, $username, "mailfetch_lmos_{$i_loop}");
            $mailfetch_uidl_[$i_loop] = getPref($data_dir, $username, "mailfetch_uidl_{$i_loop}");
            $mailfetch_subfolder_[$i_loop] = getPref($data_dir, $username, "mailfetch_subfolder_{$i_loop}");
            $mailfetch_auth_[$i_loop] = getPref($data_dir, $username, "mailfetch_auth_{$i_loop}", MAIL_FETCH_AUTH_USER);
            $mailfetch_type_[$i_loop] = getPref($data_dir, $username, "mailfetch_type_{$i_loop}", MAIL_FETCH_USE_PLAIN);
            $mailfetch_server = $mailfetch_server_[$i_loop];
            $mailfetch_port = $mailfetch_port_[$i_loop];
            $mailfetch_user = $mailfetch_user_[$i_loop];
            $mailfetch_alias = $mailfetch_alias_[$i_loop];
            $mailfetch_pass = $mailfetch_pass_[$i_loop];
            $mailfetch_lmos = $mailfetch_lmos_[$i_loop];
            $mailfetch_login = $mailfetch_login_[$i_loop];
            $mailfetch_uidl = $mailfetch_uidl_[$i_loop];
            $mailfetch_subfolder = $mailfetch_subfolder_[$i_loop];
            $mailfetch_auth = $mailfetch_auth_[$i_loop];
            $mailfetch_type = $mailfetch_type_[$i_loop];
            // end of what the heck
            // $outMsg .= "$mailfetch_alias checked<br />";
            // $outMsg .= "$mailfetch_alias_[$i_loop]<br />";
            // FIXME: duplicate code with different output destination.
            $pop3 = new mail_fetch(array('host' => $mailfetch_server, 'port' => $mailfetch_port, 'auth' => $mailfetch_auth, 'tls' => $mailfetch_type, 'timeout' => 60));
            if (!empty($pop3->error)) {
                $outMsg .= _("Warning:") . ' ' . $pop3->error;
                continue;
            }
            $imap_stream = sqimap_login($username, false, $imapServerAddress, $imapPort, 10, $imap_stream_options);
            /* log into pop server*/
            if (!$pop3->login($mailfetch_user, $mailfetch_pass)) {
                $outMsg .= _("Login Failed:") . ' ' . $pop3->error;
                continue;
            }
            $aMsgStat = $pop3->command_stat();
            if (is_bool($aMsgStat)) {
                $outMsg .= _("Can't get mailbox status:") . ' ' . sm_encode_html_special_chars($pop3->error);
                continue;
            }
            $Count = $aMsgStat['count'];
            $i = 1;
            if ($Count > 0) {
                // If we leave messages on server, try using UIDL
                if ($mailfetch_lmos == 'on') {
                    $msglist = $pop3->command_uidl();
                    if (is_bool($msglist)) {
                        $outMsg .= _("Server does not support UIDL.") . ' ' . sm_encode_html_special_chars($pop3->error);
                        // User asked to leave messages on server, but we can't do that.
                        $pop3->command_quit();
                        continue;
                        // $mailfetch_lmos = 'off';
                    } else {
                        // calculate number of new messages
                        for ($j = 1; $j <= sizeof($msglist); $j++) {
                            // do strict comparison ('1111.10' should not be equal to '1111.100')
                            if ($msglist[$j] === $mailfetch_uidl) {
                                $i = $j + 1;
                                break;
                            }
                        }
                    }
                }
                // fetch list of messages with LIST
                // we can use else control, but we can also set $mailfetch_lmos
                // to off if server does not support UIDL.
                if ($mailfetch_lmos != 'on') {
                    $msglist = $pop3->command_list();
                }
            }
            if ($Count < $i) {
                $pop3->command_quit();
                continue;
            }
            if ($Count == 0) {
                $pop3->command_quit();
                continue;
            }
            for (; $i <= $Count; $i++) {
                if (!ini_get('safe_mode')) {
                    set_time_limit(20);
                }
                // 20 seconds per message max
                $Message = $pop3->command_retr($i);
                if (is_bool($Message)) {
                    $outMsg .= _("Warning:") . ' ' . sm_encode_html_special_chars($pop3->error);
                    continue;
                }
                // check if mail folder is not null and subscribed (There is possible issue with /noselect mail folders)
                if ($mailfetch_subfolder == '' || !mail_fetch_check_folder($imap_stream, $mailfetch_subfolder)) {
                    fputs($imap_stream, "A3{$i} APPEND INBOX {" . strlen($Message) . "}\r\n");
                } else {
                    fputs($imap_stream, "A3{$i} APPEND {$mailfetch_subfolder} {" . strlen($Message) . "}\r\n");
                }
                $Line = fgets($imap_stream, 1024);
                if (substr($Line, 0, 1) == '+') {
                    fputs($imap_stream, $Message);
                    fputs($imap_stream, "\r\n");
                    sqimap_read_data($imap_stream, "A3{$i}", false, $response, $message);
                    // Check results of append command
                    $response = implode('', $response);
                    $message = implode('', $message);
                    if ($response != 'OK') {
                        $outMsg .= _("Error Appending Message!") . " " . sm_encode_html_special_chars($message);
                        if ($mailfetch_lmos == 'on') {
                            setPref($data_dir, $username, "mailfetch_uidl_{$i_loop}", $msglist[$i - 1]);
                        }
                        // Destroy msg list in order to prevent UIDL update
                        $msglist = false;
                        // if append fails, don't download other messages
                        break;
                    }
                    if ($mailfetch_lmos != 'on') {
                        $pop3->command_dele($i);
                    }
                } else {
                    echo "{$Line}";
                    $outMsg .= _("Error Appending Message!");
                }
            }
            $pop3->command_quit();
            sqimap_logout($imap_stream);
            if ($mailfetch_lmos == 'on' && is_array($msglist)) {
                setPref($data_dir, $username, "mailfetch_uidl_{$i_loop}", array_pop($msglist));
            }
        }
    }
    if (trim($outMsg) != '') {
        echo '<br /><font size="1">' . _("Mail Fetch Result:") . "<br />{$outMsg}</font>";
    }
    if ($mailfetch_newlog == 'on') {
        setPref($data_dir, $username, 'mailfetch_newlog', 'off');
    }
}
Example #20
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;
    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';
            logout_error(sprintf(_("Error connecting to IMAP server: %s."), $imap_server_address) . "<br />\r\n{$error_number} : {$error_string}<br />\r\n", sprintf(_("Error connecting to IMAP server: %s."), $imap_server_address));
        }
        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') {
        // this is a workaround to alert users of LOGINDISABLED, which is done "right" in
        // devel but requires functions not available in stable. RFC requires us to
        // not send LOGIN when LOGINDISABLED is advertised.
        if (stristr($server_info, 'LOGINDISABLED')) {
            $response = 'BAD';
            $message = _("The IMAP server is reporting that plain text logins are disabled.") . ' ' . _("Using CRAM-MD5 or DIGEST-MD5 authentication instead may work.") . ' ';
            if (!$use_imap_tls) {
                $message .= _("Also, the use of TLS may allow SquirrelMail to login.") . ' ';
            }
            $message .= _("Please contact your system administrator and report this error.");
        } else {
            // Original IMAP login code
            $query = 'LOGIN';
            if (sq_is8bit($username)) {
                $query .= ' {' . strlen($username) . "}\r\n{$username}";
            } else {
                $query .= ' "' . quoteimap($username) . '"';
            }
            if (sq_is8bit($password)) {
                $query .= ' {' . strlen($password) . "}\r\n{$password}";
            } else {
                $query .= ' "' . 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();
                /* terminate the session nicely */
                sqimap_logout($imap_stream);
                logout_error(_("Unknown user or password incorrect."));
                exit;
            }
        } else {
            exit;
        }
    }
    return $imap_stream;
}
Example #21
0
/**
 * Selects a mailbox
 */
function sqimap_mailbox_select($imap_stream, $mailbox)
{
    global $auto_expunge;
    if (empty($mailbox)) {
        return;
    }
    /**
     * Default UW IMAP server configuration allows to access other files
     * on server. $imap_server_type is not checked because interface can
     * be used with 'other' or any other server type setting. $mailbox
     * variable can be modified in any script that uses variable from GET 
     * or POST. This code blocks all standard SquirrelMail IMAP API requests 
     * that use mailbox with full path (/etc/passwd) or with ../ characters 
     * in path (../../etc/passwd)
     */
    if (strstr($mailbox, '../') || substr($mailbox, 0, 1) == '/') {
        global $color;
        include_once SM_PATH . 'functions/display_messages.php';
        error_box(sprintf(_("Invalid mailbox name: %s"), htmlspecialchars($mailbox)), $color);
        sqimap_logout($imap_stream);
        die('</body></html>');
    }
    // cleanup $mailbox in order to prevent IMAP injection attacks
    $mailbox = str_replace(array("\r", "\n"), array("", ""), $mailbox);
    $read = sqimap_run_command($imap_stream, "SELECT \"{$mailbox}\"", true, $response, $message);
    $result = array();
    for ($i = 0, $cnt = count($read); $i < $cnt; $i++) {
        if (preg_match('/^\\*\\s+OK\\s\\[(\\w+)\\s(\\w+)\\]/', $read[$i], $regs)) {
            $result[strtoupper($regs[1])] = $regs[2];
        } else {
            if (preg_match('/^\\*\\s([0-9]+)\\s(\\w+)/', $read[$i], $regs)) {
                $result[strtoupper($regs[2])] = $regs[1];
            } else {
                if (preg_match("/PERMANENTFLAGS(.*)/i", $read[$i], $regs)) {
                    $regs[1] = trim(preg_replace(array("/\\(/", "/\\)/", "/\\]/"), '', $regs[1]));
                    $result['PERMANENTFLAGS'] = $regs[1];
                } else {
                    if (preg_match("/FLAGS(.*)/i", $read[$i], $regs)) {
                        $regs[1] = trim(preg_replace(array("/\\(/", "/\\)/"), '', $regs[1]));
                        $result['FLAGS'] = $regs[1];
                    }
                }
            }
        }
    }
    if (preg_match('/^\\[(.+)\\]/', $message, $regs)) {
        $result['RIGHTS'] = $regs[1];
    }
    if ($auto_expunge) {
        $tmp = sqimap_run_command($imap_stream, 'EXPUNGE', false, $a, $b);
    }
    return $result;
}
Example #22
0
        }
        if ($use_folder == true) {
            $box[$q] = htmlspecialchars($boxes_all[$i]['unformatted-dm']);
            $box2[$q] = htmlspecialchars(imap_utf7_decode_local($boxes_all[$i]['unformatted-disp']));
            $q++;
        }
    }
    if ($box && $box2) {
        echo addForm('folders_subscribe.php?method=sub') . '<tt><select name="mailbox[]" multiple="multiple" size="8">';
        for ($q = 0; $q < count($box); $q++) {
            echo '         <option value="' . $box[$q] . '">' . $box2[$q] . "</option>\n";
        }
        echo '</select></tt><br /><br />' . '<input type="submit" value="' . _("Subscribe") . "\" />\n" . "</form></td></tr></table><br />\n";
    } else {
        echo _("No folders were found to subscribe to!") . '</td></tr></table>';
    }
} else {
    /* don't perform the list action -- this is much faster */
    echo addForm('folders_subscribe.php?method=sub') . _("Subscribe to:") . '<br />' . '<tt><input type="text" name="mailbox[]" size="35" />' . '<input type="submit" value="' . _("Subscribe") . "\" />\n" . "</form></td></tr></table><br />\n";
}
do_hook('folders_bottom');
?>
    </td></tr>
    </table>
</td></tr>
</table>
<?php 
sqimap_logout($imapConnection);
?>
</body></html>
Example #23
0
/**
 * Starts the filtering process
 * @param array $hook_args (since 1.5.2) do hook arguments. Is used to check
 * hook name, array key = 0.
 * @access private
 */
function start_filters($hook_args)
{
    global $imapServerAddress, $imapPort, $imap_stream_options, $imap_stream, $imapConnection, $UseSeparateImapConnection, $AllowSpamFilters, $filter_inbox_count, $username;
    // if there were filtering errors previously during
    // this login session, we won't try again
    //
    // (errors that this plugin was able to catch or a "NO"
    // response/failure from IMAP found in the current session,
    // which could have resulted from an attempted filter copy
    // (over quota), in which case execution halts before this
    // plugin can catch the problem -- note, however, that any
    // other IMAP "NO" failure (caused by unrelated actions) at
    // any time during the current session will cause this plugin
    // to effectively shut down)
    //
    sqgetGlobalVar('filters_error', $filters_error, SQ_SESSION, FALSE);
    sqgetGlobalVar('IMAP_FATAL_ERROR_TYPE', $imap_fatal_error, SQ_SESSION, '');
    if ($filters_error || $imap_fatal_error == 'NO') {
        return;
    }
    /**
     * check hook that calls filtering. If filters are called by right_main_after_header,
     * do filtering only when we are in INBOX folder.
     */
    if ($hook_args[0] == 'right_main_after_header' && (sqgetGlobalVar('mailbox', $mailbox, SQ_FORM) && $mailbox != 'INBOX')) {
        return;
    }
    $filters = load_filters();
    // No point running spam filters if there aren't any to run //
    if ($AllowSpamFilters) {
        $spamfilters = load_spam_filters();
        $AllowSpamFilters = false;
        foreach ($spamfilters as $value) {
            if ($value['enabled'] == SMPREF_ON) {
                $AllowSpamFilters = true;
                break;
            }
        }
    }
    // No user filters, and no spam filters, no need to continue //
    if (!$AllowSpamFilters && empty($filters)) {
        return;
    }
    // Detect if we have already connected to IMAP or not.
    // Also check if we are forced to use a separate IMAP connection
    if (!isset($imap_stream) && !isset($imapConnection) || $UseSeparateImapConnection) {
        $stream = sqimap_login($username, false, $imapServerAddress, $imapPort, 10, $imap_stream_options);
        $previously_connected = false;
    } else {
        if (isset($imapConnection)) {
            $stream = $imapConnection;
            $previously_connected = true;
        } else {
            $previously_connected = true;
            $stream = $imap_stream;
        }
    }
    if (!isset($filter_inbox_count)) {
        $aStatus = sqimap_status_messages($stream, 'INBOX', array('MESSAGES'));
        if (!empty($aStatus['MESSAGES'])) {
            $filter_inbox_count = $aStatus['MESSAGES'];
        } else {
            $filter_inbox_count = 0;
        }
    }
    if ($filter_inbox_count > 0) {
        sqimap_mailbox_select($stream, 'INBOX');
        // Filter spam from inbox before we sort them into folders
        if ($AllowSpamFilters) {
            spam_filters($stream);
        }
        // Sort into folders
        user_filters($stream);
    }
    if (!$previously_connected) {
        sqimap_logout($stream);
    }
}