Example #1
0
function getMessage_RFC822_Attachment($message, $composeMessage, $passed_id, $passed_ent_id = '', $imapConnection)
{
    global $attachments, $attachment_dir, $username, $data_dir, $uid_support;
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
    if (!$passed_ent_id) {
        $body_a = sqimap_run_command($imapConnection, 'FETCH ' . $passed_id . ' RFC822', TRUE, $response, $readmessage, $uid_support);
    } else {
        $body_a = sqimap_run_command($imapConnection, 'FETCH ' . $passed_id . ' BODY[' . $passed_ent_id . ']', TRUE, $response, $readmessage, $uid_support);
        $message = $message->parent;
    }
    if ($response == 'OK') {
        $subject = encodeHeader($message->rfc822_header->subject);
        array_shift($body_a);
        $body = implode('', $body_a) . "\r\n";
        $localfilename = GenerateRandomString(32, 'FILE', 7);
        $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
        $fp = fopen($full_localfilename, 'w');
        fwrite($fp, $body);
        fclose($fp);
        /* dirty relative dir fix */
        if (substr($attachment_dir, 0, 3) == '../') {
            $attachment_dir = substr($attachment_dir, 3);
            $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
        }
        $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
        $composeMessage->initAttachment('message/rfc822', 'email.txt', $full_localfilename);
    }
    return $composeMessage;
}
function attachSelectedMessages($msg, $imapConnection)
{
    global $username, $attachment_dir, $startMessage, $data_dir, $composesession, $uid_support, $msgs, $thread_sort_messages, $allow_server_sort, $show_num, $compose_messages;
    if (!isset($compose_messages)) {
        $compose_messages = array();
        sqsession_register($compose_messages, 'compose_messages');
    }
    if (!$composesession) {
        $composesession = 1;
        sqsession_register($composesession, 'composesession');
    } else {
        $composesession++;
        sqsession_register($composesession, 'composesession');
    }
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir, $composesession);
    if ($thread_sort_messages || $allow_server_sort) {
        $start_index = 0;
    } else {
        $start_index = ($startMessage - 1) * $show_num;
    }
    $i = 0;
    $j = 0;
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
    $composeMessage = new Message();
    $rfc822_header = new Rfc822Header();
    $composeMessage->rfc822_header = $rfc822_header;
    $composeMessage->reply_rfc822_header = '';
    while ($j < count($msg)) {
        if (isset($msg[$i])) {
            $id = $msg[$i];
            $body_a = sqimap_run_command($imapConnection, "FETCH {$id} RFC822", true, $response, $readmessage, $uid_support);
            if ($response == 'OK') {
                // fetch the subject for the message with $id from msgs.
                // is there a more efficient way to do this?
                foreach ($msgs as $k => $vals) {
                    if ($vals['ID'] == $id) {
                        $subject = $msgs[$k]['SUBJECT'];
                        break;
                    }
                }
                array_shift($body_a);
                array_pop($body_a);
                $body = implode('', $body_a);
                $body .= "\r\n";
                $localfilename = GenerateRandomString(32, 'FILE', 7);
                $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
                $fp = fopen($full_localfilename, 'wb');
                fwrite($fp, $body);
                fclose($fp);
                $composeMessage->initAttachment('message/rfc822', $subject . '.msg', $full_localfilename);
            }
            $j++;
        }
        $i++;
    }
    $compose_messages[$composesession] = $composeMessage;
    sqsession_register($compose_messages, 'compose_messages');
    session_write_close();
    return $composesession;
}
Example #3
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;
}
Example #4
0
function parse_viewheader($imapConnection, $id, $passed_ent_id)
{
    global $uid_support;
    $header_full = array();
    $header_output = array();
    $second = array();
    $first = array();
    if (!$passed_ent_id) {
        $read = sqimap_run_command($imapConnection, "FETCH {$id} BODY[HEADER]", true, $a, $b, $uid_support);
    } else {
        $query = "FETCH {$id} BODY[" . $passed_ent_id . '.HEADER]';
        $read = sqimap_run_command($imapConnection, $query, true, $a, $b, $uid_support);
    }
    $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);
        }
    }
    return $header_output;
}
function sqimap_mailbox_tree($imap_stream)
{
    global $default_folder_prefix, $unseen_notify, $unseen_type;
    if (true) {
        global $data_dir, $username, $list_special_folders_first, $folder_prefix, $delimiter, $trash_folder, $move_to_trash, $imap_server_type;
        $inbox_in_list = false;
        $inbox_subscribed = false;
        $noselect = false;
        $noinferiors = false;
        require_once SM_PATH . 'include/load_prefs.php';
        /* LSUB array */
        $lsub_ary = sqimap_run_command($imap_stream, "LSUB \"{$folder_prefix}\" \"*\"", true, $response, $message);
        $lsub_ary = compact_mailboxes_response($lsub_ary);
        /* Check to see if we have an INBOX */
        $has_inbox = false;
        for ($i = 0, $cnt = count($lsub_ary); $i < $cnt; $i++) {
            if (preg_match("/^\\*\\s+LSUB.*\\s\"?INBOX\"?[^(\\/\\.)].*\$/i", $lsub_ary[$i])) {
                $lsub_ary[$i] = strtoupper($lsub_ary[$i]);
                // in case of an unsubscribed inbox an imap server can
                // return the inbox in the lsub results with a \NoSelect
                // flag.
                if (!preg_match("/\\*\\s+LSUB\\s+\\(.*\\\\NoSelect.*\\).*/i", $lsub_ary[$i])) {
                    $has_inbox = true;
                } else {
                    // remove the result and request it again  with a list
                    // response at a later stage.
                    unset($lsub_ary[$i]);
                    // re-index the array otherwise the addition of the LIST
                    // response will fail in PHP 4.1.2 and probably other older versions
                    $lsub_ary = array_values($lsub_ary);
                }
                break;
            }
        }
        if ($has_inbox == false) {
            // do a list request for inbox because we should always show
            // inbox even if the user isn't subscribed to it.
            $inbox_ary = sqimap_run_command($imap_stream, 'LIST "" INBOX', true, $response, $message);
            $inbox_ary = compact_mailboxes_response($inbox_ary);
            if (count($inbox_ary)) {
                $lsub_ary[] = $inbox_ary[0];
            }
        }
        /*
         * Section about removing the last element was removed
         * We don't return "* OK" anymore from sqimap_read_data
         */
        $sorted_lsub_ary = array();
        $cnt = count($lsub_ary);
        for ($i = 0; $i < $cnt; $i++) {
            $mbx = find_mailbox_name($lsub_ary[$i]);
            // only do the noselect test if !uw, is checked later. FIX ME see conf.pl setting
            if ($imap_server_type != "uw") {
                $noselect = check_is_noselect($lsub_ary[$i]);
                $noinferiors = check_is_noinferiors($lsub_ary[$i]);
            }
            if (substr($mbx, -1) == $delimiter) {
                $mbx = substr($mbx, 0, strlen($mbx) - 1);
            }
            $sorted_lsub_ary[] = array('mbx' => $mbx, 'noselect' => $noselect, 'noinferiors' => $noinferiors);
        }
        // FIX ME this requires a config setting inside conf.pl instead of checking on server type
        if ($imap_server_type == "uw") {
            $aQuery = array();
            $aTag = array();
            // prepare an array with queries
            foreach ($sorted_lsub_ary as $aMbx) {
                $mbx = stripslashes($aMbx['mbx']);
                sqimap_prepare_pipelined_query('LIST "" ' . sqimap_encode_mailbox_name($mbx), $tag, $aQuery, false);
                $aTag[$tag] = $mbx;
            }
            $sorted_lsub_ary = array();
            // execute all the queries at once
            $aResponse = sqimap_run_pipelined_command($imap_stream, $aQuery, false, $aServerResponse, $aServerMessage);
            foreach ($aTag as $tag => $mbx) {
                if ($aServerResponse[$tag] == 'OK') {
                    $sResponse = implode('', $aResponse[$tag]);
                    $noselect = check_is_noselect($sResponse);
                    $noinferiors = check_is_noinferiors($sResponse);
                    $sorted_lsub_ary[] = array('mbx' => $mbx, 'noselect' => $noselect, 'noinferiors' => $noinferiors);
                }
            }
            $cnt = count($sorted_lsub_ary);
        }
        $sorted_lsub_ary = array_values($sorted_lsub_ary);
        usort($sorted_lsub_ary, 'mbxSort');
        $boxestree = sqimap_fill_mailbox_tree($sorted_lsub_ary, false, $imap_stream);
        return $boxestree;
    }
}
Example #6
0
function sqimap_toggle_flag($imap_stream, $id, $flag, $set, $handle_errors)
{
    global $uid_support;
    $msgs_id = sqimap_message_list_squisher($id);
    $set_string = $set ? '+' : '-';
    $read = sqimap_run_command($imap_stream, "STORE {$msgs_id} " . $set_string . "FLAGS ({$flag})", $handle_errors, $response, $message, $uid_support);
}
/**
 * Attach messages to a compose session
 *
 * @param  resource $imapConnection imap connection
 * @param  array $aMsgHeaders
 * @return int $composesession unique compose_session_id where the attached messages belong to
 * @author Marc Groot Koerkamp
 */
function attachSelectedMessages($imapConnection, $aMsgHeaders)
{
    sqgetGlobalVar('composesession', $composesession, SQ_SESSION);
    sqgetGlobalVar('compose_messages', $compose_messages, SQ_SESSION);
    if (!isset($compose_messages) || is_null($compose_messages)) {
        $compose_messages = array();
        sqsession_register($compose_messages, 'compose_messages');
    }
    if (!$composesession) {
        $composesession = 1;
        sqsession_register($composesession, 'composesession');
    } else {
        $composesession++;
        sqsession_register($composesession, 'composesession');
    }
    $composeMessage = new Message();
    $rfc822_header = new Rfc822Header();
    $composeMessage->rfc822_header = $rfc822_header;
    $composeMessage->reply_rfc822_header = '';
    foreach ($aMsgHeaders as $iUid => $aMsgHeader) {
        /**
         * Retrieve the full message
         */
        $body_a = sqimap_run_command($imapConnection, "FETCH {$iUid} RFC822", true, $response, $readmessage, TRUE);
        if ($response == 'OK') {
            $subject = isset($aMsgHeader['subject']) ? $aMsgHeader['subject'] : $iUid;
            array_shift($body_a);
            array_pop($body_a);
            $body = implode('', $body_a);
            $body .= "\r\n";
            global $username, $attachment_dir;
            $filename = sq_get_attach_tempfile();
            $fullpath = getHashedDir($username, $attachment_dir) . '/' . $filename;
            $fp = fopen($fullpath, 'wb');
            fwrite($fp, $body);
            fclose($fp);
            $composeMessage->initAttachment('message/rfc822', $subject . '.eml', $filename);
            // create subject for new message
            //
            $subject = decodeHeader($subject, false, false, true);
            $subject = str_replace('"', "'", $subject);
            $subject = trim($subject);
            if (substr(strtolower($subject), 0, 4) != 'fwd:') {
                $subject = 'Fwd: ' . $subject;
            }
            $composeMessage->rfc822_header->subject = $subject;
        }
    }
    $compose_messages[$composesession] = $composeMessage;
    sqsession_register($compose_messages, 'compose_messages');
    return $composesession;
}
Example #8
0
/**
 * FIXME: Undocumented function
 * @access private
 */
function spam_filters($imap_stream)
{
    global $data_dir, $username, $uid_support;
    global $SpamFilters_YourHop;
    global $SpamFilters_DNScache;
    global $SpamFilters_SharedCache;
    global $SpamFilters_BulkQuery;
    $filters_spam_scan = getPref($data_dir, $username, 'filters_spam_scan');
    $filters_spam_folder = getPref($data_dir, $username, 'filters_spam_folder');
    $filters = load_spam_filters();
    if ($SpamFilters_SharedCache) {
        filters_LoadCache();
    }
    $run = 0;
    foreach ($filters as $Key => $Value) {
        if ($Value['enabled']) {
            $run++;
        }
    }
    // short-circuit
    if ($run == 0) {
        return;
    }
    sqimap_mailbox_select($imap_stream, 'INBOX');
    // Ask for a big list of all "Received" headers in the inbox with
    // flags for each message.  Kinda big.
    if ($filters_spam_scan != 'new') {
        $read = sqimap_run_command($imap_stream, 'FETCH 1:* (FLAGS BODY.PEEK[HEADER.FIELDS ' . '(RECEIVED)])', true, $response, $message, $uid_support);
    } else {
        $read = sqimap_run_command($imap_stream, 'SEARCH UNSEEN', true, $response, $message, $uid_support);
        if ($response != 'OK' || trim($read[0]) == '* SEARCH') {
            $read = sqimap_run_command($imap_stream, 'FETCH 1:* (FLAGS BODY.PEEK[HEADER.FIELDS ' . '(RECEIVED)])', true, $response, $message, $uid_support);
        } else {
            if (isset($read[0])) {
                if (preg_match("/^\\* SEARCH (.+)\$/", $read[0], $regs)) {
                    $search_array = preg_split("/ /", trim($regs[1]));
                }
            }
            $msgs_str = sqimap_message_list_squisher($search_array);
            $imap_query = 'FETCH ' . $msgs_str;
            $imap_query .= ' (FLAGS BODY.PEEK[HEADER.FIELDS ';
            $imap_query .= '(RECEIVED)])';
            $read = sqimap_run_command($imap_stream, $imap_query, true, $response, $message, $uid_support);
        }
    }
    if (isset($response) && $response != 'OK') {
        return;
    }
    if (strlen($SpamFilters_BulkQuery) > 0) {
        filters_bulkquery($filters_spam_scan, $filters, $read);
    }
    $i = 0;
    while ($i < count($read)) {
        // EIMS will give funky results
        $Chunks = explode(' ', $read[$i]);
        if ($Chunks[0] != '*') {
            $i++;
            continue;
        }
        $MsgNum = $Chunks[1];
        $IPs = array();
        $i++;
        $IsSpam = 0;
        // Look through all of the Received headers for IP addresses
        // Stop when I get ")" on a line
        // Stop if I get "*" on a line (don't advance)
        // and above all, stop if $i is bigger than the total # of lines
        while ($i < count($read) && ($read[$i][0] != ')' && $read[$i][0] != '*' && $read[$i][0] != "\n") && !$IsSpam) {
            // Check to see if this line is the right "Received from" line
            // to check
            if (is_int(strpos($read[$i], $SpamFilters_YourHop))) {
                // short-circuit and skip work if we don't scan this one
                $read[$i] = ereg_replace('[^0-9\\.]', ' ', $read[$i]);
                $elements = explode(' ', $read[$i]);
                foreach ($elements as $value) {
                    if ($value != '' && ereg('[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}', $value, $regs)) {
                        $Chunks = explode('.', $value);
                        if (filters_spam_check_site($Chunks[0], $Chunks[1], $Chunks[2], $Chunks[3], $filters)) {
                            $IsSpam++;
                            break;
                            // no sense in checking more IPs
                        }
                        // If we've checked one IP and YourHop is
                        // just a space
                        if ($SpamFilters_YourHop == ' ') {
                            break;
                            // don't check any more
                        }
                    }
                }
            }
            $i++;
        }
        // Lookie!  It's spam!  Yum!
        if ($IsSpam) {
            if (sqimap_mailbox_exists($imap_stream, $filters_spam_folder)) {
                // check if message copy was successful
                if (sqimap_messages_copy($imap_stream, $MsgNum, $MsgNum, $filters_spam_folder, false)) {
                    sqimap_messages_flag($imap_stream, $MsgNum, $MsgNum, 'Deleted', false);
                }
            }
        } else {
        }
    }
    sqimap_mailbox_expunge($imap_stream, 'INBOX');
    if ($SpamFilters_SharedCache) {
        filters_SaveCache();
    } else {
        sqsession_register($SpamFilters_DNScache, 'SpamFilters_DNScache');
    }
}
Example #9
0
/**
 * Gets the list of mailboxes for sqimap_maolbox_tree and sqimap_mailbox_list
 *
 * This is because both of those functions had duplicated logic, but with slightly different
 * implementations. This will make both use the same implementation, which should make it
 * easier to maintain and easier to modify in the future
 * @param stream $imap_stream imap connection resource
 * @param bool $force force a reload and ignore cache
 * @param bool $show_only_subscribed controls listing of visible or all folders
 * @param bool $session_register controls registration of retrieved data in session.
 * @return object boxesnew - array of mailboxes and their attributes
 * @since 1.5.1
 */
function sqimap_get_mailboxes($imap_stream, $force = false, $show_only_subscribed = true, $session_register = true)
{
    global $show_only_subscribed_folders, $noselect_fix_enable, $folder_prefix, $list_special_folders_first, $imap_server_type;
    $inbox_subscribed = false;
    $listsubscribed = sqimap_capability($imap_stream, 'LIST-SUBSCRIBED');
    if ($show_only_subscribed) {
        $show_only_subscribed = $show_only_subscribed_folders;
    }
    //require_once(SM_PATH . 'include/load_prefs.php');
    /**
     * There are three main listing commands we can use in IMAP:
     * LSUB        shows just the list of subscribed folders
     *            may include flags, but these are not necessarily accurate or authoratative
     *            \NoSelect has special meaning: the folder does not exist -OR- it means this
     *            folder is not subscribed but children may be
     *            [RFC-2060]
     * LIST        this shows every mailbox on the system
     *            flags are always included and are accurate and authoratative
     *            \NoSelect means folder should not be selected
     *            [RFC-2060]
     * LIST (SUBSCRIBED)    implemented with LIST-SUBSCRIBED extension
     *            this is like list but returns only subscribed folders
     *            flag meanings are like LIST, not LSUB
     *            \NonExistent means mailbox doesn't exist
     *            \PlaceHolder means parent is not valid (selectable), but one or more children are
     *            \NoSelect indeed means that the folder should not be selected
     *            IMAPEXT-LIST-EXTENSIONS-04 August 2003 B. Leiba
     */
    if (!$show_only_subscribed) {
        $lsub = 'LIST';
        $sub_cache_name = 'list_cache';
    } elseif ($listsubscribed) {
        $lsub = 'LIST (SUBSCRIBED)';
        $sub_cache_name = 'listsub_cache';
    } else {
        $lsub = 'LSUB';
        $sub_cache_name = 'lsub_cache';
    }
    // Some IMAP servers allow subfolders to exist even if the parent folders do not
    // This fixes some problems with the folder list when this is the case, causing the
    // NoSelect folders to be displayed
    if ($noselect_fix_enable) {
        $lsub_args = "{$lsub} \"{$folder_prefix}\" \"*%\"";
        $list_args = "LIST \"{$folder_prefix}\" \"*%\"";
    } else {
        $lsub_args = "{$lsub} \"{$folder_prefix}\" \"*\"";
        $list_args = "LIST \"{$folder_prefix}\" \"*\"";
    }
    // get subscribed mailbox list from cache (session)
    // if not there, then get it from the imap server and store in cache
    if (!$force) {
        sqgetGlobalVar($sub_cache_name, $lsub_cache, SQ_SESSION);
    }
    $lsub_assoc_ary = array();
    if (!empty($lsub_cache)) {
        $lsub_assoc_ary = $lsub_cache;
    } else {
        $lsub_ary = sqimap_run_command($imap_stream, $lsub_args, true, $response, $message);
        $lsub_ary = compact_mailboxes_response($lsub_ary);
        if (!empty($lsub_ary)) {
            foreach ($lsub_ary as $rawline) {
                $temp_mailbox_name = find_mailbox_name($rawline);
                $lsub_assoc_ary[$temp_mailbox_name] = $rawline;
            }
            unset($lsub_ary);
            sqsession_register($lsub_assoc_ary, $sub_cache_name);
        }
    }
    // Now to get the mailbox flags
    // The LSUB response may return \NoSelect flags, etc. but it is optional
    // according to RFC3501, and even when returned it may not be accurate
    // or authoratative. LIST will always return accurate results.
    if ($lsub == 'LIST' || $lsub == 'LIST (SUBSCRIBED)') {
        // we've already done a LIST or LIST (SUBSCRIBED)
        // and NOT a LSUB, so no need to do it again
        $list_assoc_ary = $lsub_assoc_ary;
    } else {
        // we did a LSUB so now we need to do a LIST
        // first see if it is in cache
        $list_cache_name = 'list_cache';
        if (!$force) {
            sqgetGlobalVar($list_cache_name, $list_cache, SQ_SESSION);
        }
        if (!empty($list_cache)) {
            $list_assoc_ary = $list_cache;
            // we could store this in list_cache_name but not necessary
        } else {
            // not in cache so we need to go get it from the imap server
            $list_assoc_ary = array();
            $list_ary = sqimap_run_command($imap_stream, $list_args, true, $response, $message);
            $list_ary = compact_mailboxes_response($list_ary);
            if (!empty($list_ary)) {
                foreach ($list_ary as $rawline) {
                    $temp_mailbox_name = find_mailbox_name($rawline);
                    $list_assoc_ary[$temp_mailbox_name] = $rawline;
                }
                unset($list_ary);
                sqsession_register($list_assoc_ary, $list_cache_name);
            }
        }
    }
    // If they aren't subscribed to the inbox, then add it anyway (if its in LIST)
    $inbox_subscribed = false;
    if (!empty($lsub_assoc_ary)) {
        foreach ($lsub_assoc_ary as $temp_mailbox_name => $rawline) {
            if (strtoupper($temp_mailbox_name) == 'INBOX') {
                $inbox_subscribed = true;
            }
        }
    }
    if (!$inbox_subscribed) {
        if (!empty($list_assoc_ary)) {
            foreach ($list_assoc_ary as $temp_mailbox_name => $rawline) {
                if (strtoupper($temp_mailbox_name) == 'INBOX') {
                    $lsub_assoc_ary[$temp_mailbox_name] = $rawline;
                }
            }
        }
    }
    // Now we have the raw output, we need to create an array of mailbox names we will return
    if (!$show_only_subscribed) {
        $final_folders_assoc_ary = $list_assoc_ary;
    } else {
        /**
         * only show subscribed folders
         * we need to merge the folders here... we can't trust the flags, etc. from the lsub_assoc_array
         * so we use the lsub_assoc_array as the list of folders and the values come from list_assoc_array
         */
        if (!empty($lsub_assoc_ary)) {
            foreach ($lsub_assoc_ary as $temp_mailbox_name => $rawline) {
                if (!empty($list_assoc_ary[$temp_mailbox_name])) {
                    $final_folders_assoc_ary[$temp_mailbox_name] = $list_assoc_ary[$temp_mailbox_name];
                }
            }
        }
    }
    // Now produce a flat, sorted list
    if (!empty($final_folders_assoc_ary)) {
        uksort($final_folders_assoc_ary, 'strnatcasecmp');
        foreach ($final_folders_assoc_ary as $temp_mailbox_name => $rawline) {
            $final_folders_ary[] = $rawline;
        }
    }
    // this will put it into an array we can use later
    // containing:
    // raw    - Raw LIST/LSUB response from the IMAP server
    // formatted - formatted folder name
    // unformatted - unformatted, but with the delimiter at the end removed
    // unformated-dm - folder name as it appears in raw response
    // unformatted-disp - unformatted without $folder_prefix
    // id - the array element number (0, 1, 2, etc.)
    // flags - mailbox flags
    if (!empty($final_folders_ary)) {
        $boxesall = sqimap_mailbox_parse($final_folders_ary);
    } else {
        // they have no mailboxes
        $boxesall = array();
    }
    /* Now, lets sort for special folders */
    $boxesnew = $used = array();
    /* Find INBOX */
    $cnt = count($boxesall);
    $used = array_pad($used, $cnt, false);
    $has_inbox = false;
    for ($k = 0; $k < $cnt; ++$k) {
        if (strtoupper($boxesall[$k]['unformatted']) == 'INBOX') {
            $boxesnew[] = $boxesall[$k];
            $used[$k] = true;
            $has_inbox = true;
            break;
        }
    }
    if ($has_inbox == false) {
        // do a list request for inbox because we should always show
        // inbox even if the user isn't subscribed to it.
        $inbox_ary = sqimap_run_command($imap_stream, 'LIST "" "INBOX"', true, $response, $message);
        $inbox_ary = compact_mailboxes_response($inbox_ary);
        if (count($inbox_ary)) {
            $inbox_entry = sqimap_mailbox_parse($inbox_ary);
            // add it on top of the list
            if (!empty($boxesnew)) {
                array_unshift($boxesnew, $inbox_entry[0]);
            } else {
                $boxesnew[] = $inbox_entry[0];
            }
            /* array_unshift($used,true); */
        }
    }
    /* List special folders and their subfolders, if requested. */
    if ($list_special_folders_first) {
        for ($k = 0; $k < $cnt; ++$k) {
            if (!$used[$k] && isSpecialMailbox($boxesall[$k]['unformatted'])) {
                $boxesnew[] = $boxesall[$k];
                $used[$k] = true;
            }
        }
    }
    /* Find INBOX's children */
    for ($k = 0; $k < $cnt; ++$k) {
        $isboxbelow = isBoxBelow(strtoupper($boxesall[$k]['unformatted']), 'INBOX');
        if (strtoupper($boxesall[$k]['unformatted']) == 'INBOX') {
            $is_inbox = 1;
        } else {
            $is_inbox = 0;
        }
        if (!$used[$k] && $isboxbelow && $is_inbox) {
            $boxesnew[] = $boxesall[$k];
            $used[$k] = true;
        }
    }
    /* Rest of the folders */
    for ($k = 0; $k < $cnt; $k++) {
        if (!$used[$k]) {
            $boxesnew[] = $boxesall[$k];
        }
    }
    /**
     * Don't register boxes in session, if $session_register is set to false
     * Prevents registration of sqimap_mailbox_list_all() results.
     */
    if ($session_register) {
        sqsession_register($boxesnew, 'boxesnew');
    }
    return $boxesnew;
}
Example #10
0
function getMessage_RFC822_Attachment($message, $composeMessage, $passed_id, $passed_ent_id = '', $imapConnection)
{
    if (!$passed_ent_id) {
        $body_a = sqimap_run_command($imapConnection, 'FETCH ' . $passed_id . ' RFC822', TRUE, $response, $readmessage, TRUE);
    } else {
        $body_a = sqimap_run_command($imapConnection, 'FETCH ' . $passed_id . ' BODY[' . $passed_ent_id . ']', TRUE, $response, $readmessage, TRUE);
        $message = $message->parent;
    }
    if ($response == 'OK') {
        $subject = encodeHeader($message->rfc822_header->subject);
        array_shift($body_a);
        array_pop($body_a);
        $body = implode('', $body_a) . "\r\n";
        global $username, $attachment_dir;
        $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
        $localfilename = sq_get_attach_tempfile();
        $fp = fopen($hashed_attachment_dir . '/' . $localfilename, 'wb');
        fwrite($fp, $body);
        fclose($fp);
        $composeMessage->initAttachment('message/rfc822', $subject . '.eml', $localfilename);
    }
    return $composeMessage;
}
function sqimap_get_mime_ent_header($imap_stream, $id, $mailbox, $ent)
{
    global $uid_support;
    $read = sqimap_run_command($imap_stream, "FETCH {$id}:{$id} BODY[{$ent}.MIME]", true, $response, $message, $uid_support);
    $header = sqimap_get_header($imap_stream, $read);
    $header->id = $id;
    $header->mailbox = $mailbox;
    return $header;
}
function attachSelectedMessages($imapConnection, $aMsgHeaders)
{
    global $username, $attachment_dir, $data_dir, $composesession, $compose_messages;
    if (!isset($compose_messages)) {
        $compose_messages = array();
        sqsession_register($compose_messages, 'compose_messages');
    }
    if (!$composesession) {
        $composesession = 1;
        sqsession_register($composesession, 'composesession');
    } else {
        $composesession++;
        sqsession_register($composesession, 'composesession');
    }
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
    $composeMessage = new Message();
    $rfc822_header = new Rfc822Header();
    $composeMessage->rfc822_header = $rfc822_header;
    $composeMessage->reply_rfc822_header = '';
    foreach ($aMsgHeaders as $iUid => $aMsgHeader) {
        /**
         * Retrieve the full message
         */
        $body_a = sqimap_run_command($imapConnection, "FETCH {$iUid} RFC822", true, $response, $readmessage, TRUE);
        if ($response == 'OK') {
            $subject = isset($aMsgHeader['SUBJECT']) ? $aMsgHeader['SUBJECT'] : $iUid;
            array_shift($body_a);
            array_pop($body_a);
            $body = implode('', $body_a);
            $body .= "\r\n";
            $localfilename = GenerateRandomString(32, 'FILE', 7);
            $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
            $fp = fopen($full_localfilename, 'wb');
            fwrite($fp, $body);
            fclose($fp);
            $composeMessage->initAttachment('message/rfc822', $subject . '.msg', $full_localfilename);
        }
    }
    $compose_messages[$composesession] = $composeMessage;
    sqsession_register($compose_messages, 'compose_messages');
    return $composesession;
}
Example #13
0
function attachSelectedMessages($msg, $imapConnection)
{
    global $username, $attachment_dir, $startMessage, $data_dir, $composesession, $uid_support, $mailbox, $msgs, $thread_sort_messages, $allow_server_sort, $show_num, $compose_messages;
    if (!isset($compose_messages)) {
        $compose_messages = array();
        sqsession_register($compose_messages, 'compose_messages');
    }
    if (!$composesession) {
        $composesession = 1;
        sqsession_register($composesession, 'composesession');
    } else {
        $composesession++;
        sqsession_register($composesession, 'composesession');
    }
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir, $composesession);
    if ($thread_sort_messages || $allow_server_sort) {
        $start_index = 0;
    } else {
        $start_index = ($startMessage - 1) * $show_num;
    }
    $i = 0;
    $j = 0;
    $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
    $composeMessage = new Message();
    $rfc822_header = new Rfc822Header();
    $composeMessage->rfc822_header = $rfc822_header;
    $composeMessage->reply_rfc822_header = '';
    while ($j < count($msg)) {
        if (isset($msg[$i])) {
            $id = $msg[$i];
            $body_a = sqimap_run_command($imapConnection, "FETCH {$id} RFC822", true, $response, $readmessage, $uid_support);
            if ($response == 'OK') {
                $message = sqimap_get_message($imapConnection, $id, $mailbox);
                // fetch the subject for the message from the object
                $filename = $message->rfc822_header->subject;
                if (empty($filename)) {
                    $filename = "untitled-" . $message->entity_id;
                }
                $filename .= '.msg';
                $filename = decodeHeader($filename, false, false);
                array_shift($body_a);
                array_pop($body_a);
                $body = implode('', $body_a);
                $body .= "\r\n";
                $localfilename = GenerateRandomString(32, 'FILE', 7);
                $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
                while (file_exists($full_localfilename)) {
                    $localfilename = GenerateRandomString(32, 'FILE', 7);
                    $full_localfilename = "{$hashed_attachment_dir}/{$localfilename}";
                }
                $fp = fopen($full_localfilename, 'wb');
                fwrite($fp, $body);
                fclose($fp);
                $composeMessage->initAttachment('message/rfc822', $filename, $localfilename);
            }
            $j++;
        }
        $i++;
    }
    $compose_messages[$composesession] = $composeMessage;
    sqsession_register($compose_messages, 'compose_messages');
    session_write_close();
    return $composesession;
}
Example #14
0
function mime_print_body_lines($imap_stream, $id, $ent_id = 1, $encoding)
{
    /* Don't kill the connection if the browser is over a dialup
     * and it would take over 30 seconds to download it.
     * Don't call set_time_limit in safe mode.
     */
    if (!ini_get('safe_mode')) {
        set_time_limit(0);
    }
    /* in case of base64 encoded attachments, do not buffer them.
       Instead, echo the decoded attachment directly to screen */
    if (strtolower($encoding) == 'base64') {
        if (!$ent_id) {
            $query = "FETCH {$id} BODY[]";
        } else {
            $query = "FETCH {$id} BODY[{$ent_id}]";
        }
        sqimap_run_command($imap_stream, $query, true, $response, $message, TRUE, 'sqimap_base64_decode', 'php://stdout', true);
    } else {
        $body = mime_fetch_body($imap_stream, $id, $ent_id);
        echo decodeBody($body, $encoding);
    }
    /*
       TODO, use the same method for quoted printable.
       However, I assume that quoted printable attachments aren't that large
       so the performancegain / memory usage drop will be minimal.
       If we decide to add that then we need to adapt sqimap_fread because
       we need to split te result on \n and fread doesn't stop at \n. That
       means we also should provide $results from sqimap_fread (by ref) to
       te function and set $no_return to false. The $filter function for
       quoted printable should handle unsetting of $results.
    */
    /*
       TODO 2: find out how we write to the output stream php://stdout. fwrite
       doesn't work because 'php://stdout isn't a stream.
    */
    return;
    /*
        fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
        $cnt = 0;
        $continue = true;
        $read = fgets ($imap_stream,8192);
    
    
        // This could be bad -- if the section has sqimap_session_id() . ' OK'
        // or similar, it will kill the download.
        while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
            if (trim($read) == ')==') {
                $read1 = $read;
                $read = fgets ($imap_stream,4096);
                if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
                    return;
                } else {
                    echo decodeBody($read1, $encoding) .
                         decodeBody($read, $encoding);
                }
            } else if ($cnt) {
                echo decodeBody($read, $encoding);
            }
            $read = fgets ($imap_stream,4096);
            $cnt++;
    //      break;
        }
    */
}
/**
 * Deprecated !!!!!!! DO NOT USE THIS, use sqimap_toggle_flag instead
 * Set a flag on the provided uid list
 * @param  resource imap connection
 */
function sqimap_messages_flag($imap_stream, $start, $end, $flag, $handle_errors)
{
    $read = sqimap_run_command($imap_stream, "STORE {$start}:{$end} +FLAGS (\\{$flag})", $handle_errors, $response, $message, TRUE);
}
/**
 * Returns the status items of a mailbox.
 * Default it returns MESSAGES,UNSEEN and RECENT
 * Supported status items are MESSAGES, UNSEEN, RECENT, UIDNEXT and UIDVALIDITY
 */
function sqimap_status_messages($imap_stream, $mailbox, $aStatusItems = array('MESSAGES', 'UNSEEN', 'RECENT'))
{
    $aStatusItems = implode(' ', $aStatusItems);
    $read_ary = sqimap_run_command($imap_stream, 'STATUS ' . sqimap_encode_mailbox_name($mailbox) . " ({$aStatusItems})", false, $result, $message);
    $i = 0;
    $messages = $unseen = $recent = $uidnext = $uidvalidity = false;
    $regs = array(false, false);
    while (isset($read_ary[$i])) {
        if (preg_match('/UNSEEN\\s+([0-9]+)/i', $read_ary[$i], $regs)) {
            $unseen = $regs[1];
        }
        if (preg_match('/MESSAGES\\s+([0-9]+)/i', $read_ary[$i], $regs)) {
            $messages = $regs[1];
        }
        if (preg_match('/RECENT\\s+([0-9]+)/i', $read_ary[$i], $regs)) {
            $recent = $regs[1];
        }
        if (preg_match('/UIDNEXT\\s+([0-9]+)/i', $read_ary[$i], $regs)) {
            $uidnext = $regs[1];
        }
        if (preg_match('/UIDVALIDITY\\s+([0-9]+)/i', $read_ary[$i], $regs)) {
            $uidvalidity = $regs[1];
        }
        $i++;
    }
    return array('MESSAGES' => $messages, 'UNSEEN' => $unseen, 'RECENT' => $recent, 'UIDNEXT' => $uidnext, 'UIDVALIDITY' => $uidvalidity);
}
Example #17
0
/**
 * Stores message in attachment directory, when email based reports are used
 * @access private
 * @todo Duplicate code in src/compose.php
 */
function spamcop_getMessage_RFC822_Attachment($message, $composeMessage, $passed_id, $passed_ent_id = '', $imapConnection)
{
    global $username, $attachment_dir;
    if (!$passed_ent_id) {
        $body_a = sqimap_run_command($imapConnection, 'FETCH ' . $passed_id . ' RFC822', TRUE, $response, $readmessage, TRUE);
    } else {
        $body_a = sqimap_run_command($imapConnection, 'FETCH ' . $passed_id . ' BODY[' . $passed_ent_id . ']', TRUE, $response, $readmessage, TRUE);
        $message = $message->parent;
    }
    if ($response == 'OK') {
        array_shift($body_a);
        $body = implode('', $body_a) . "\r\n";
        $filename = sq_get_attach_tempfile();
        $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
        $fp = fopen("{$hashed_attachment_dir}/{$filename}", 'wb');
        fwrite($fp, $body);
        fclose($fp);
        $composeMessage->initAttachment('message/rfc822', 'email.txt', $filename);
    }
    return $composeMessage;
}
function bayesspam_filters($imap_stream, $use_mailbox = 0)
{
    $spam_stats = 0;
    $ham_stats = 0;
    $unsure_stats = 0;
    $total_messages = 0;
    $run_folders = array();
    $boxes = sqimap_mailbox_list($imap_stream);
    foreach ($boxes as $box) {
        if ($GLOBALS['bayesspam_inboxonly'] != 1 || $GLOBALS['bayesspam_inboxonly'] == 1 && 'INBOX' == $box['unformatted-dm']) {
            if ($use_mailbox == 1 && $box['unformatted-dm'] == $GLOBALS['mailbox'] && !in_array($box['unformatted-dm'], $GLOBALS['bayesspam_ignore_folders']) || $use_mailbox == 0 && !in_array($box['unformatted-dm'], $GLOBALS['bayesspam_ignore_folders'])) {
                if ((array_search('noselect', $box['flags']) === FALSE || array_search('noselect', $box['flags']) === NULL) && $GLOBALS['sent_folder'] != $box['unformatted-dm'] && sqimap_unseen_messages($imap_stream, $box['unformatted-dm']) > 0) {
                    $run_folders[] = $box['unformatted-dm'];
                }
            }
        }
    }
    foreach ($run_folders as $box) {
        $spam_messages = array();
        $uncertain_messages = array();
        $mbxresponse = sqimap_mailbox_select($imap_stream, $box);
        $messages = array();
        $search = "SEARCH UNSEEN UNDELETED";
        if (isset($_SESSION['bayesspam_last_filter'])) {
            $search .= " SINCE " . date('d-M-Y', $_SESSION['bayesspam_last_filter']);
        }
        $_SESSION['bayesspam_last_filter'] = time();
        $read = sqimap_run_command($imap_stream, $search, TRUE, $response, $message, TRUE);
        if (isset($read[0])) {
            for ($i = 0, $iCnt = count($read); $i < $iCnt; ++$i) {
                if (preg_match("/^\\* SEARCH (.+)\$/", $read[$i], $regs)) {
                    $messages = preg_split("/ /", trim($regs[1]));
                    break;
                }
            }
        }
        foreach ($messages as $passed_id) {
            bayesspam_set_message_id($imap_stream, $passed_id);
            $bayesspam_check_messageid = bayesspam_check_messageid();
            if ($GLOBALS['bayesspam_do_stats'] && $GLOBALS['bayesspam_do_user_stats']) {
                $bayesspam_old_message_score = bayesspam_get_old_message_score();
            }
            $is_spam = bayesspam_get_probability($imap_stream, $passed_id, 1);
            if ($is_spam > 0.9) {
                $spam_messages[] = $passed_id;
            } elseif ($is_spam >= 0.1) {
                $uncertain_messages[] = $passed_id;
            }
            if ($GLOBALS['bayesspam_do_stats'] && $GLOBALS['bayesspam_do_user_stats'] && $bayesspam_old_message_score === FALSE) {
                if ($is_spam > 0.9) {
                    $spam_stats++;
                    $total_messages++;
                }
                if ($is_spam <= 0.9 && $is_spam >= 0.1) {
                    $unsure_stats++;
                    $total_messages++;
                }
                if ($is_spam < 0.1) {
                    $ham_stats++;
                    $total_messages++;
                }
            }
        }
        if ($spam_messages) {
            $message_str = sqimap_message_list_squisher($spam_messages);
            if ($GLOBALS['bayesspam_delete']) {
                sqimap_run_command($imap_stream, 'STORE ' . $message_str . ' +FLAGS (\\Deleted)', true, $response, $message, $GLOBALS['uid_support']);
            } elseif (sqimap_mailbox_exists($imap_stream, $GLOBALS['bayesspam_folder'])) {
                sqimap_run_command($imap_stream, 'COPY ' . $message_str . ' "' . $GLOBALS['bayesspam_folder'] . '"', true, $response, $message, $GLOBALS['uid_support']);
                sqimap_run_command($imap_stream, 'STORE ' . $message_str . ' +FLAGS (\\Deleted)', true, $response, $message, $GLOBALS['uid_support']);
            }
            sqimap_mailbox_expunge($imap_stream, $box);
        }
        if ($uncertain_messages && $GLOBALS['bayesspam_do_uncertain_filtering']) {
            $message_str = sqimap_message_list_squisher($uncertain_messages);
            if (sqimap_mailbox_exists($imap_stream, $GLOBALS['bayesspam_uncertain_folder'])) {
                sqimap_run_command($imap_stream, 'COPY ' . $message_str . ' "' . $GLOBALS['bayesspam_uncertain_folder'] . '"', true, $response, $message, $GLOBALS['uid_support']);
                sqimap_run_command($imap_stream, 'STORE ' . $message_str . ' +FLAGS (\\Deleted)', true, $response, $message, $GLOBALS['uid_support']);
            }
            sqimap_mailbox_expunge($imap_stream, $box);
        }
    }
    if ($GLOBALS['bayesspam_do_stats'] && $GLOBALS['bayesspam_do_user_stats'] && $total_messages) {
        $res = $GLOBALS['bayesdbhandle']->query('SELECT UserName FROM ' . $GLOBALS['bayesdbprefix'] . 'stats WHERE UserName=\'' . $GLOBALS['bayes_username'] . '\'');
        if (!DB::isError($res) && !($row = $res->fetchRow())) {
            $GLOBALS['bayesdbhandle']->query('INSERT INTO ' . $GLOBALS['bayesdbprefix'] . 'stats SET StatsStart=NOW(),UserName=\'' . $GLOBALS['bayes_username'] . '\',TotalMessages=' . $total_messages . ',HamMessages=' . $ham_stats . ',SpamMessages=' . $spam_stats . ',UnsureMessages=' . $unsure_stats . ($GLOBALS['bayesspam_do_timing'] ? ',TimedMessages=' . $GLOBALS['bayes_parsed_messages'] . ',TotalParseTime=' . $GLOBALS['bayes_parse_time'] : ''));
        } else {
            $GLOBALS['bayesdbhandle']->query('UPDATE ' . $GLOBALS['bayesdbprefix'] . 'stats SET TotalMessages=TotalMessages+' . $total_messages . ',HamMessages=HamMessages+' . $ham_stats . ',SpamMessages=SpamMessages+' . $spam_stats . ', UnsureMessages=UnsureMessages+' . $unsure_stats . ($GLOBALS['bayesspam_do_timing'] ? ',TimedMessages=TimedMessages+' . $GLOBALS['bayes_parsed_messages'] . ',TotalParseTime=TotalParseTime+' . $GLOBALS['bayes_parse_time'] : '') . ' WHERE UserName=\'' . $GLOBALS['bayes_username'] . '\'');
        }
    }
}
Example #19
0
function ToggleMDNflag($set, $imapConnection, $mailbox, $passed_id, $uid_support)
{
    $sg = $set ? '+' : '-';
    $cmd = 'STORE ' . $passed_id . ' ' . $sg . 'FLAGS ($MDNSent)';
    $read = sqimap_run_command($imapConnection, $cmd, true, $response, $readmessage, $uid_support);
}
Example #20
0
/**
 * Recursively parse embedded messages (if any) in the given
 * message, building correct rfc822 headers for each one
 *
 * @param object $msg The message object to scan for attached messages
 *                    NOTE: this is passed by reference!  Changes made
 *                    within will affect the caller's copy of $msg!
 * @param int $id The top-level message UID on the IMAP server, even
 *                if the $msg being passed in is only an attached entity
 *                thereof.
 * @param resource $imap_stream A live connection to the IMAP server.
 *
 * @return void
 *
 * @since 1.5.2
 *
 */
function parse_message_entities(&$msg, $id, $imap_stream)
{
    if (!empty($msg->entities)) {
        foreach ($msg->entities as $i => $entity) {
            if (is_object($entity) && strtolower(get_class($entity)) == 'message') {
                if (!empty($entity->rfc822_header)) {
                    $read = sqimap_run_command($imap_stream, "FETCH {$id} BODY[" . $entity->entity_id . ".HEADER]", true, $response, $message, TRUE);
                    $rfc822_header = new Rfc822Header();
                    $rfc822_header->parseHeader($read);
                    $msg->entities[$i]->rfc822_header = $rfc822_header;
                }
                parse_message_entities($msg->entities[$i], $id, $imap_stream);
            }
        }
    }
}
function sqimap_search($imapConnection, $search_where, $search_what, $mailbox, $color, $search_position = '', $search_all, $count_all)
{
    global $message_highlight_list, $squirrelmail_language, $languages, $index_order, $pos, $allow_charset_search, $imap_server_type;
    $pos = $search_position;
    $urlMailbox = urlencode($mailbox);
    /* construct the search query, taking multiple search terms into account */
    $multi_search = array();
    $search_what = trim($search_what);
    $search_what = ereg_replace('[ ]{2,}', ' ', $search_what);
    $multi_search = explode(' ', $search_what);
    $search_string = '';
    /* it seems macosx does not support the prefered search
       syntax so we fall back to the older style. This IMAP
       server has a problem with multiple search terms. Instead
       of returning the messages that match all the terms it
       returns the messages that match each term. Could be fixed
       on the client side, but should be fixed on the server
       as per the RFC */
    if ($imap_server_type == 'macosx') {
        foreach ($multi_search as $multi_search_part) {
            if (strtoupper($languages[$squirrelmail_language]['CHARSET']) == 'ISO-2022-JP') {
                $multi_search_part = mb_convert_encoding($multi_search_part, 'JIS', 'auto');
            }
            $search_string .= $search_where . ' ' . $multi_search_part . ' ';
        }
    } else {
        foreach ($multi_search as $multi_search_part) {
            if (strtoupper($languages[$squirrelmail_language]['CHARSET']) == 'ISO-2022-JP') {
                $multi_search_part = mb_convert_encoding($multi_search_part, 'JIS', 'auto');
            }
            $search_string .= $search_where . ' {' . strlen($multi_search_part) . "}\r\n" . $multi_search_part . ' ';
        }
    }
    $search_string = trim($search_string);
    /* now use $search_string in the imap search */
    if ($allow_charset_search && isset($languages[$squirrelmail_language]['CHARSET']) && $languages[$squirrelmail_language]['CHARSET']) {
        $ss = "SEARCH CHARSET " . strtoupper($languages[$squirrelmail_language]['CHARSET']) . " ALL {$search_string}";
    } else {
        $ss = "SEARCH ALL {$search_string}";
    }
    /* read data back from IMAP */
    $readin = sqimap_run_command($imapConnection, $ss, false, $result, $message, TRUE);
    /* try US-ASCII charset if search fails */
    if (isset($languages[$squirrelmail_language]['CHARSET']) && strtolower($result) == 'no') {
        $ss = "SEARCH CHARSET \"US-ASCII\" ALL {$search_string}";
        $readin = sqimap_run_command($imapConnection, $ss, true, $result, $message);
    }
    unset($messagelist);
    /* Keep going till we find the SEARCH response */
    foreach ($readin as $readin_part) {
        /* Check to see if a SEARCH response was received */
        if (substr($readin_part, 0, 9) == '* SEARCH ') {
            $messagelist = preg_split("/ /", substr($readin_part, 9));
        } else {
            if (isset($errors)) {
                $errors = $errors . $readin_part;
            } else {
                $errors = $readin_part;
            }
        }
    }
    /* If nothing is found * SEARCH should be the first error else echo errors */
    if (isset($errors)) {
        if (strstr($errors, '* SEARCH')) {
            return array();
        }
        echo '<!-- ' . htmlspecialchars($errors) . ' -->';
    }
    global $sent_folder;
    $cnt = count($messagelist);
    for ($q = 0; $q < $cnt; $q++) {
        $id[$q] = trim($messagelist[$q]);
    }
    $issent = $mailbox == $sent_folder;
    $msgs = fillMessageArray($imapConnection, $id, $cnt);
    return $msgs;
}
function sqimap_mailbox_tree($imap_stream)
{
    global $boxesnew, $default_folder_prefix, $unseen_notify, $unseen_type;
    if (!isset($boxesnew)) {
        global $data_dir, $username, $list_special_folders_first, $folder_prefix, $delimiter, $trash_folder, $move_to_trash;
        $inbox_in_list = false;
        $inbox_subscribed = false;
        require_once SM_PATH . 'include/load_prefs.php';
        /* LSUB array */
        $lsub_ary = sqimap_run_command($imap_stream, "LSUB \"{$folder_prefix}\" \"*\"", true, $response, $message);
        /*
         * Section about removing the last element was removed 
         * We don't return "* OK" anymore from sqimap_read_data
         */
        $sorted_lsub_ary = array();
        $cnt = count($lsub_ary);
        for ($i = 0; $i < $cnt; $i++) {
            /*
             * Workaround for EIMS
             * Doesn't work if the mailbox name is multiple lines
             */
            if (isset($lsub_ary[$i + 1]) && ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)\$", $lsub_ary[$i], $regs)) {
                $i++;
                $lsub_ary[$i] = $regs[1] . '"' . addslashes(trim($lsub_ary[$i])) . '"' . $regs[2];
            }
            /*
            if (preg_match("/^\*\s+LSUB\s+\((.*)\)\s+\"(.*)\"\s+\"?(.+(?=\")|.+).*$/",$lsub_ary[$i],$regs)) {
                $flag = $regs[1];
                $mbx = trim($regs[3]);
                $sorted_lsub_ary[] = array ('mbx' => $mbx, 'flag' => $flag); 
            }
            */
            $mbx = find_mailbox_name($lsub_ary[$i]);
            $noselect = check_is_noselect($lsub_ary[$i]);
            if (substr($mbx, -1) == $delimiter) {
                $mbx = substr($mbx, 0, strlen($mbx) - 1);
            }
            $sorted_lsub_ary[] = array('mbx' => $mbx, 'noselect' => $noselect);
        }
        array_multisort($sorted_lsub_ary, SORT_ASC, SORT_REGULAR);
        for ($i = 0; $i < $cnt; $i++) {
            if ($sorted_lsub_ary[$i]['mbx'] == 'INBOX') {
                $inbox_in_list = true;
                break;
            }
        }
        /*
         * Just in case they're not subscribed to their inbox,
         * we'll get it for them anyway
         */
        if (!$inbox_in_list) {
            $inbox_ary = sqimap_run_command($imap_stream, "LIST \"\" \"INBOX\"", true, $response, $message);
            /* Another workaround for EIMS */
            if (isset($inbox_ary[1]) && ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)\$", $inbox_ary[0], $regs)) {
                $inbox_ary[0] = $regs[1] . '"' . addslashes(trim($inbox_ary[1])) . '"' . $regs[2];
            }
            $mbx = find_mailbox_name($inbox_ary[0]);
            if (substr($mbx, -1) == $delimiter) {
                $mbx = substr($mbx, 0, strlen($mbx) - 1);
            }
            if ($mbx == 'INBOX') {
                $sorted_lsub_ary[] = array('mbx' => $mbx, 'flag' => '');
                sqimap_subscribe($imap_stream, 'INBOX');
                $cnt++;
            }
            /*
            if (preg_match("/^\*\s+LIST\s+\((.*)\)\s+\"(.*)\"\s+\"?(.+(?=\")|.+).*$/",$inbox_ary[0],$regs)) {
                $flag = $regs[1];
                $mbx = trim($regs[3]);
                if (substr($mbx, -1) == $delimiter) {
                    $mbx = substr($mbx, 0, strlen($mbx) - 1);
                }
                $sorted_lsub_ary[] = array ('mbx' => $mbx, 'flag' => $flag); 
            }
            */
        }
        for ($i = 0; $i < $cnt; $i++) {
            $mbx = $sorted_lsub_ary[$i]['mbx'];
            if ($unseen_notify == 2 && $mbx == 'INBOX' || $unseen_notify == 3 || $move_to_trash && $mbx == $trash_folder) {
                if ($sorted_lsub_ary[$i]['noselect']) {
                    $sorted_lsub_ary[$i]['unseen'] = 0;
                } else {
                    $sorted_lsub_ary[$i]['unseen'] = sqimap_unseen_messages($imap_stream, $mbx);
                }
                if ($unseen_type == 2 || $move_to_trash && $mbx == $trash_folder || $mbx == $trash_folder) {
                    if ($sorted_lsub_ary[$i]['noselect']) {
                        $sorted_lsub_ary[$i]['nummessages'] = 0;
                    } else {
                        $sorted_lsub_ary[$i]['nummessages'] = sqimap_get_num_messages($imap_stream, $mbx);
                    }
                }
            }
        }
        $boxesnew = sqimap_fill_mailbox_tree($sorted_lsub_ary);
        return $boxesnew;
    }
}
Example #23
0
function mime_print_body_lines($imap_stream, $id, $ent_id = 1, $encoding, $rStream = 'php://stdout')
{
    global $uid_support;
    /* Don't kill the connection if the browser is over a dialup
     * and it would take over 30 seconds to download it.
     * Don't call set_time_limit in safe mode.
     */
    if (!ini_get('safe_mode')) {
        set_time_limit(0);
    }
    /* in case of base64 encoded attachments, do not buffer them.
       Instead, echo the decoded attachment directly to screen */
    if (strtolower($encoding) == 'base64') {
        if (!$ent_id) {
            $query = "FETCH {$id} BODY[]";
        } else {
            $query = "FETCH {$id} BODY[{$ent_id}]";
        }
        sqimap_run_command($imap_stream, $query, true, $response, $message, $uid_support, 'sqimap_base64_decode', $rStream, true);
    } else {
        $body = mime_fetch_body($imap_stream, $id, $ent_id);
        if ($rStream !== 'php://stdout') {
            fwrite($rStream, decodeBody($body, $encoding));
        } else {
            echo decodeBody($body, $encoding);
        }
    }
    return;
}
function bayesspam_get_tokens(&$imap_stream, $passed_id)
{
    if ($GLOBALS['bayesdbhandle'] == null) {
        return;
    }
    $tokens = array();
    $headers = sqimap_get_small_header_list($imap_stream, array($passed_id));
    $version_array = split('\\.', $GLOBALS['version']);
    bayesspam_set_message_id($imap_stream, $passed_id);
    $lines1 = sqimap_run_command($imap_stream, 'FETCH ' . $passed_id . ':' . $passed_id . ' BODY[HEADER]<0.' . $GLOBALS['bayesspam_scan_size'] . '>', true, $response, $msg, $GLOBALS['uid_support']);
    $response = array_shift($lines1);
    preg_match('/\\{(\\d+)\\}/', $response, $matches);
    $lines2 = sqimap_run_command($imap_stream, 'FETCH ' . $passed_id . ':' . $passed_id . ' BODY[TEXT]<0.' . ($GLOBALS['bayesspam_scan_size'] - $matches[1]) . '>', true, $response, $msg, $GLOBALS['uid_support']);
    if ($version_array[0] == 1 && $version_array[1] <= 2) {
        if (!$headers[0]['FLAG_SEEN']) {
            sqimap_messages_remove_flag($imap_stream, $passed_id, $passed_id, 'Seen');
        }
    } else {
        if ($version_array[0] == 1 && $version_array[1] == 5) {
            if (!isset($headers[$passed_id]['FLAGS']['\\seen'])) {
                sqimap_toggle_flag($imap_stream, $passed_id, '\\Seen', FALSE, TRUE);
            }
        } else {
            if (!$headers[0]['FLAG_SEEN']) {
                sqimap_messages_remove_flag($imap_stream, $passed_id, $passed_id, 'Seen', FALSE);
            }
        }
    }
    array_shift($lines2);
    $lines = array_merge($lines1, $lines2);
    $hdr_lines = count($lines1);
    unset($lines1);
    unset($lines2);
    $mime = '';
    $encoding = '';
    $decoded = '';
    $content_type = '';
    $in_html_tag = 0;
    for ($i = 0; $i < count($lines); $i++) {
        $line = $lines[$i];
        if ($line == '') {
            continue;
        }
        if ($mime != '' && preg_match('/' . $mime . '/', $line)) {
            $encoding = '';
            continue;
        }
        if (preg_match('/base64/i', $encoding)) {
            $decoded = '';
            while (preg_match('/^([A-Za-z0-9+\\/]{4}){1,48}[\\n\\r]*/', $line) || preg_match('/^[A-Za-z0-9+\\/]+=+?[\\n\\r]*/', $line)) {
                $decoded .= base64_decode($line);
                if (preg_match('/[^a-zA-Z\\-\\.]$/', $decoded)) {
                    $temp_tokens = bayesspam_parse_line($decoded, 'ENCODED');
                    foreach ($temp_tokens as $token) {
                        $tokens[] = $token;
                    }
                    $decoded = '';
                }
                $i++;
                if ($i < count($lines)) {
                    $line = $lines[$i];
                } else {
                    break;
                }
            }
            $temp_tokens = bayesspam_parse_line($decoded, 'ENCODED');
            foreach ($temp_tokens as $token) {
                $tokens[] = $token;
            }
        }
        if ($i == count($lines)) {
            break;
        }
        if (preg_match('/<html>/i', $line)) {
            $content_type = 'text/html';
        }
        if (preg_match('/quoted\\-printable/', $encoding)) {
            $line = preg_replace('/=[\\r\\n]*$/', "=\n", $line);
            while (preg_match('/=\\n$/', $line)) {
                $tokens[] = 'CHEATER: Line Break';
                $i++;
                $line = preg_replace('/=\\n$/', '', $line);
                $line = $line . $lines[$i];
            }
            $line = quoted_printable_decode($line);
        }
        $oldline = $line;
        while ($oldline != ($line = preg_replace('/<!--.*?-->/', '', $line))) {
            $tokens[] = 'HTML: CHEATER';
            $oldline = $line;
        }
        unset($oldline);
        if (preg_match('/html/', $content_type)) {
            if ($in_html_tag) {
                if (preg_match('/(.*?)>/', $line, $matches)) {
                    $line = preg_replace('/(.*?)>/', ' ', $line);
                    $html_arg .= $matches[1];
                    $in_html_tag = 0;
                    if (preg_match('/quoted\\-printable/', $line)) {
                        $html_tag = preg_replace('/=\\n ?/', '', $html_tag);
                        $html_arg = preg_replace('/=\\n ?/', '', $html_arg);
                    }
                    $tokens[] = bayesspam_parse_html_tag($html_tag, $html_arg);
                    $tokens[] = 'HTMLTAG: ' . $html_tag;
                    $html_tag = '';
                    $html_arg = '';
                } else {
                    $html_arg .= ' ' . $line;
                    $line = '';
                    continue;
                }
            }
            while (preg_match('/<[\\/]?([A-Za-z]+)([^>]*?)>/', $line, $matches)) {
                $line = preg_replace('/<[\\/]?([A-Za-z]+)([^>]*?)>/', '', $line, 1);
                $tokens[] = bayesspam_parse_html_tag($matches[1], $matches[2]);
                $tokens[] = 'HTMLTAG: ' . $matches[1];
            }
            if (preg_match('/<([^ >]+)([^>]*)$/', $line, $matches)) {
                $line = preg_replace('/<([^ >]+)([^>]*)$/', '', $line);
                $html_tag = $matches[1];
                $html_arg = $matches[2];
                $in_html_tag = 1;
            }
        }
        if (preg_match('/^([A-Za-z-]+): ?([^\\n\\r]*)/', $line, $matches)) {
            $header = $matches[1];
            $arguement = $matches[2];
            $tokens[] = 'HEADERTYPE: ' . $header;
            if (preg_match('/(From|To|Cc)/i', $header)) {
                if (preg_match('/From/i', $header)) {
                    $encoding = '';
                    $content_type = '';
                }
                while (preg_match('/<([a-zA-Z0-9\\-_\\.]+?@([a-zA-Z0-9\\-_\\.]+?))>/', $arguement, $matches)) {
                    $arguement = preg_replace('/<[a-zA-Z0-9\\-_\\.]+?@[a-zA-Z0-9\\-_\\.]+?>/', '', $arguement, 1);
                    if ($matches[1]) {
                        $tokens[] = 'EMAIL: ' . $matches[1];
                    }
                    if ($matches[2]) {
                        $tokens[] = 'DOMAIN: ' . $matches[2];
                    }
                }
                while (preg_match('/([a-zA-Z0-9\\-_\\.]+?@([a-zA-Z0-9\\-_\\.]+))/', $arguement, $matches)) {
                    $arguement = preg_replace('/([a-zA-Z0-9\\-_\\.]+?@([a-zA-Z0-9\\-_\\.]+))/', '', $arguement);
                    if ($matches[1]) {
                        $tokens[] = 'EMAIL: ' . $matches[1];
                    }
                    if ($matches[2]) {
                        $tokens[] = 'DOMAIN: ' . $matches[2];
                    }
                }
                $temp_tokens = bayesspam_parse_line($arguement, 'HEADER');
                foreach ($temp_tokens as $token) {
                    $tokens[] = $token;
                }
                continue;
            }
            if (preg_match('/Subject/i', $header)) {
                $temp_tokens = bayesspam_parse_line($arguement, 'SUBJECT');
                foreach ($temp_tokens as $token) {
                    $tokens[] = $token;
                }
                continue;
            }
            if (preg_match('/Content-Type/i', $header)) {
                if (preg_match('/multipart\\//i', $arguement)) {
                    $boundary = $arguement;
                    if (preg_match('/boundary="(.*)"/', $arguement)) {
                        $i++;
                        $boundary = $lines[$i];
                    }
                    if (preg_match('/boundary="(.*)"/', $boundary, $matches)) {
                        $mime = $matches[1];
                        $mime = preg_replace('/(\\+|\\/|\\?|\\*|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\^|\\$|\\.)/', $matches[1], $mime);
                    }
                }
                $content_type = $arguement;
                continue;
            }
            if (preg_match('/Content-Transfer-Encoding/i', $header)) {
                $encoding = $arguement;
                continue;
            }
            if (preg_match('/X-Text-Classification/', $header)) {
                $tokens[] = 'TEXTCLASS: ' . $arguement;
                continue;
            }
            if (preg_match('/(Thread-Index|X-UIDL|Message-ID|X-Text-Classification|X-Mime-Key)/i', $header)) {
                continue;
            }
            $temp_tokens = bayesspam_parse_line($arguement, 'HEADER');
            foreach ($temp_tokens as $token) {
                $tokens[] = $token;
            }
        } else {
            if ($i < $hdr_lines) {
                $temp_tokens = bayesspam_parse_line($arguement, 'HEADER');
            } else {
                $temp_tokens = bayesspam_parse_line($arguement, 'BODY');
            }
            foreach ($temp_tokens as $token) {
                $tokens[] = $token;
            }
        }
    }
    return $tokens;
}
Example #25
0
/**
 * FIXME: Undocumented function
 * @access private
 */
function spam_filters($imap_stream)
{
    global $data_dir, $username, $uid_support;
    global $SpamFilters_YourHop;
    global $SpamFilters_DNScache;
    global $SpamFilters_SharedCache;
    global $SpamFilters_BulkQuery;
    $filters_spam_scan = getPref($data_dir, $username, 'filters_spam_scan');
    $filters_spam_folder = getPref($data_dir, $username, 'filters_spam_folder');
    $filters = load_spam_filters();
    if ($SpamFilters_SharedCache) {
        filters_LoadCache();
    }
    $run = false;
    foreach ($filters as $Key => $Value) {
        if ($Value['enabled']) {
            $run = true;
            break;
        }
    }
    // short-circuit
    if (!$run) {
        return;
    }
    sqimap_mailbox_select($imap_stream, 'INBOX');
    $search_array = array();
    if ($filters_spam_scan == 'new') {
        $read = sqimap_run_command($imap_stream, 'SEARCH UNSEEN', true, $response, $message, $uid_support);
        if (isset($read[0])) {
            for ($i = 0, $iCnt = count($read); $i < $iCnt; ++$i) {
                if (preg_match("/^\\* SEARCH (.+)\$/", $read[$i], $regs)) {
                    $search_array = explode(' ', trim($regs[1]));
                    break;
                }
            }
        }
    }
    if ($filters_spam_scan == 'new' && count($search_array)) {
        $msg_str = sqimap_message_list_squisher($search_array);
        $imap_query = 'FETCH ' . $msg_str . ' (FLAGS BODY.PEEK[HEADER.FIELDS (RECEIVED)])';
    } else {
        if ($filters_spam_scan != 'new') {
            $imap_query = 'FETCH 1:* (FLAGS BODY.PEEK[HEADER.FIELDS (RECEIVED)])';
        } else {
            return;
        }
    }
    $read = sqimap_run_command_list($imap_stream, $imap_query, true, $response, $message, $uid_support);
    if (isset($response) && $response != 'OK') {
        return;
    }
    $messages = parseFetch($read);
    $bulkquery = strlen($SpamFilters_BulkQuery) > 0 ? true : false;
    $aSpamIds = array();
    foreach ($messages as $id => $message) {
        if (isset($message['UID'])) {
            $MsgNum = $message['UID'];
        } else {
            $MsgNum = $id;
        }
        if (isset($message['received'])) {
            foreach ($message['received'] as $received) {
                if (is_int(strpos($received, $SpamFilters_YourHop))) {
                    if (preg_match('/([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})/', $received, $matches)) {
                        $IsSpam = false;
                        if (filters_spam_check_site($matches[1], $matches[2], $matches[3], $matches[4], $filters)) {
                            $aSpamIds[] = $MsgNum;
                            $IsSpam = true;
                        }
                        if ($bulkquery) {
                            array_shift($matches);
                            $IP = explode('.', $matches);
                            foreach ($filters as $key => $value) {
                                if ($filters[$key]['enabled'] && $filters[$key]['dns']) {
                                    if (strlen($SpamFilters_DNScache[$IP . '.' . $filters[$key]['dns']]) == 0) {
                                        $IPs[$IP] = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if ($SpamFilters_YourHop == ' ' || $IsSpam) {
                            break;
                        }
                    }
                }
            }
        }
    }
    if (count($aSpamIds) && sqimap_mailbox_exists($imap_stream, $filters_spam_folder)) {
        sqimap_msgs_list_move($imap_stream, $aSpamIds, $filters_spam_folder);
        sqimap_mailbox_expunge($imap_stream, 'INBOX', true, $aSpamIds);
    }
    if ($bulkquery && count($IPs)) {
        filters_bulkquery($filters, $IPs);
    }
    if ($SpamFilters_SharedCache) {
        filters_SaveCache();
    } else {
        sqsession_register($SpamFilters_DNScache, 'SpamFilters_DNScache');
    }
}
Example #26
0
/**
 * Returns sorted mailbox lists in several different ways.
 * See comment on sqimap_mailbox_parse() for info about the returned array.
 */
function sqimap_mailbox_list($imap_stream, $force = false)
{
    global $default_folder_prefix;
    if (!sqgetGlobalVar('boxesnew', $boxesnew, SQ_SESSION) || $force) {
        global $data_dir, $username, $list_special_folders_first, $folder_prefix, $trash_folder, $sent_folder, $draft_folder, $move_to_trash, $move_to_sent, $save_as_draft, $delimiter, $noselect_fix_enable;
        $inbox_in_list = false;
        $inbox_subscribed = false;
        require_once SM_PATH . 'include/load_prefs.php';
        if ($noselect_fix_enable) {
            $lsub_args = "LSUB \"{$folder_prefix}\" \"*%\"";
        } else {
            $lsub_args = "LSUB \"{$folder_prefix}\" \"*\"";
        }
        /* LSUB array */
        $lsub_ary = sqimap_run_command($imap_stream, $lsub_args, true, $response, $message);
        $sorted_lsub_ary = array();
        for ($i = 0, $cnt = count($lsub_ary); $i < $cnt; $i++) {
            /*
             * Workaround for mailboxes returned as literal
             * Doesn't work if the mailbox name is multiple lines
             * (larger then fgets buffer)
             */
            if (isset($lsub_ary[$i + 1]) && substr($lsub_ary[$i], -3) == "}\r\n") {
                if (ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)\$", $lsub_ary[$i], $regs)) {
                    $i++;
                    $lsub_ary[$i] = $regs[1] . '"' . addslashes(trim($lsub_ary[$i])) . '"' . $regs[2];
                }
            }
            $temp_mailbox_name = find_mailbox_name($lsub_ary[$i]);
            $sorted_lsub_ary[] = $temp_mailbox_name;
            if (!$inbox_subscribed && strtoupper($temp_mailbox_name) == 'INBOX') {
                $inbox_subscribed = true;
            }
        }
        /* remove duplicates */
        $sorted_lsub_ary = array_unique($sorted_lsub_ary);
        /* natural sort mailboxes */
        if (isset($sorted_lsub_ary)) {
            mailtree_sort($sorted_lsub_ary);
        }
        /*
         * The LSUB response doesn't provide us information about \Noselect
         * mail boxes. The LIST response does, that's why we need to do a LIST
         * call to retrieve the flags for the mailbox
         * Note: according RFC2060 an imap server may provide \NoSelect flags in the LSUB response.
         * in other words, we cannot rely on it.
         */
        $sorted_list_ary = array();
        for ($i = 0; $i < count($sorted_lsub_ary); $i++) {
            if (substr($sorted_lsub_ary[$i], -1) == $delimiter) {
                $mbx = substr($sorted_lsub_ary[$i], 0, strlen($sorted_lsub_ary[$i]) - 1);
            } else {
                $mbx = $sorted_lsub_ary[$i];
            }
            $read = sqimap_run_command($imap_stream, "LIST \"\" \"{$mbx}\"", true, $response, $message);
            /* Another workaround for literals */
            if (isset($read[1]) && substr($read[1], -3) == "}\r\n") {
                if (ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)\$", $read[0], $regs)) {
                    $read[0] = $regs[1] . '"' . addslashes(trim($read[1])) . '"' . $regs[2];
                }
            }
            if (isset($read[0])) {
                $sorted_list_ary[$i] = $read[0];
            } else {
                $sorted_list_ary[$i] = '';
            }
        }
        /*
         * Just in case they're not subscribed to their inbox,
         * we'll get it for them anyway
         */
        if (!$inbox_subscribed) {
            $inbox_ary = sqimap_run_command($imap_stream, "LIST \"\" \"INBOX\"", true, $response, $message);
            /* Another workaround for literals */
            if (isset($inbox_ary[1]) && substr($inbox_ary[0], -3) == "}\r\n") {
                if (ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)\$", $inbox_ary[0], $regs)) {
                    $inbox_ary[0] = $regs[1] . '"' . addslashes(trim($inbox_ary[1])) . '"' . $regs[2];
                }
            }
            $sorted_list_ary[] = $inbox_ary[0];
            $sorted_lsub_ary[] = find_mailbox_name($inbox_ary[0]);
        }
        $boxesall = sqimap_mailbox_parse($sorted_list_ary, $sorted_lsub_ary);
        /* Now, lets sort for special folders */
        $boxesnew = $used = array();
        /* Find INBOX */
        $cnt = count($boxesall);
        $used = array_pad($used, $cnt, false);
        for ($k = 0; $k < $cnt; ++$k) {
            if (strtolower($boxesall[$k]['unformatted']) == 'inbox') {
                $boxesnew[] = $boxesall[$k];
                $used[$k] = true;
                break;
            }
        }
        /* List special folders and their subfolders, if requested. */
        if ($list_special_folders_first) {
            for ($k = 0; $k < $cnt; ++$k) {
                if (!$used[$k] && isSpecialMailbox($boxesall[$k]['unformatted'])) {
                    $boxesnew[] = $boxesall[$k];
                    $used[$k] = true;
                }
            }
        }
        /* Find INBOX's children */
        for ($k = 0; $k < $cnt; ++$k) {
            if (!$used[$k] && isBoxBelow(strtolower($boxesall[$k]['unformatted']), 'inbox') && strtolower($boxesall[$k]['unformatted']) != 'inbox') {
                $boxesnew[] = $boxesall[$k];
                $used[$k] = true;
            }
        }
        /* Rest of the folders */
        for ($k = 0; $k < $cnt; $k++) {
            if (!$used[$k]) {
                $boxesnew[] = $boxesall[$k];
            }
        }
        sqsession_register($boxesnew, 'boxesnew');
    }
    return $boxesnew;
}
Example #27
0
File: tree.php Project: jprice/EHCP
/**
 * Recursively walk a tree of folders to create them under the trash folder.
 */
function walkTreeInPostOrderCreatingFoldersUnderTrash($index, $imap_stream, $tree, $topFolderName)
{
    global $trash_folder, $delimiter;
    $position = strrpos($topFolderName, $delimiter);
    if ($position !== FALSE) {
        $position++;
    }
    $subFolderName = substr($tree[$index]['value'], $position);
    if ($tree[$index]['doIHaveChildren']) {
        sqimap_mailbox_create($imap_stream, $trash_folder . $delimiter . $subFolderName, "");
        $mbx_response = sqimap_mailbox_select($imap_stream, $tree[$index]['value']);
        $messageCount = $mbx_response['EXISTS'];
        if ($messageCount > 0) {
            sqimap_msgs_list_copy($imap_stream, '1:*', $trash_folder . $delimiter . $subFolderName);
        }
        // after copy close the mailbox to get in unselected state
        sqimap_run_command($imap_stream, 'CLOSE', false, $response, $message);
        for ($j = 0; $j < count($tree[$index]['subNodes']); $j++) {
            walkTreeInPostOrderCreatingFoldersUnderTrash($tree[$index]['subNodes'][$j], $imap_stream, $tree, $topFolderName);
        }
    } else {
        sqimap_mailbox_create($imap_stream, $trash_folder . $delimiter . $subFolderName, '');
        $mbx_response = sqimap_mailbox_select($imap_stream, $tree[$index]['value']);
        $messageCount = $mbx_response['EXISTS'];
        if ($messageCount > 0) {
            sqimap_msgs_list_copy($imap_stream, '1:*', $trash_folder . $delimiter . $subFolderName);
        }
        // after copy close the mailbox to get in unselected state
        sqimap_run_command($imap_stream, 'CLOSE', false, $response, $message);
    }
}
                $sublevel = substr($entString, $pos + 1);
                $sublevel++;
                $result = "{$level}" . '.' . "{$sublevel}";
            }
            break;
        case 1:
            $result = "{$entString}" . ".0";
            break;
        default:
            break;
    }
    return $result;
}
$imapConnection = sqimap_login($username, $key, $imapServerAddress, $imapPort, 0);
$read = sqimap_mailbox_select($imapConnection, $mailbox);
$body = sqimap_run_command($imapConnection, "FETCH {$passed_id} RFC822", true, $response, $readmessage, $uid_support);
$message_body = '';
$header = false;
$mimepart = false;
$bnd_end = false;
$messageheader = true;
$messageheaderstart = false;
$boundaries = array();
$entities = array();
session_unregister("entities");
$pre = '<b>';
$end = '</b>';
$entStr = '';
$bla = '';
$content = array();
$content_indx = -1;
function sqimap_status_messages($imap_stream, $mailbox)
{
    $read_ary = sqimap_run_command($imap_stream, "STATUS \"{$mailbox}\" (MESSAGES UNSEEN RECENT)", false, $result, $message);
    $i = 0;
    $messages = $unseen = $recent = false;
    $regs = array(false, false);
    while (isset($read_ary[$i])) {
        if (preg_match('/UNSEEN\\s+([0-9]+)/i', $read_ary[$i], $regs)) {
            $unseen = $regs[1];
        }
        if (preg_match('/MESSAGES\\s+([0-9]+)/i', $read_ary[$i], $regs)) {
            $messages = $regs[1];
        }
        if (preg_match('/RECENT\\s+([0-9]+)/i', $read_ary[$i], $regs)) {
            $recent = $regs[1];
        }
        $i++;
    }
    return array('MESSAGES' => $messages, 'UNSEEN' => $unseen, 'RECENT' => $recent);
}
/**
* Run the imap SEARCH command as defined in rfc 3501
* @link http://www.ietf.org/rfc/rfc3501.txt
* @param resource $imapConnection the current imap stream
* @param string $search_string the full search expression eg "ALL RECENT"
* @param string $search_charset charset to use or zls ('')
* @return array an IDs or UIDs array of matching messages or an empty array
*/
function sqimap_run_search($imapConnection, $search_string, $search_charset)
{
    //For some reason, this seems to happen and forbids searching servers not allowing OPTIONAL [CHARSET]
    if (strtoupper($search_charset) == 'US-ASCII') {
        $search_charset = '';
    }
    /* 6.4.4 try OPTIONAL [CHARSET] specification first */
    if ($search_charset != '') {
        $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ' . $search_string;
    } else {
        $query = 'SEARCH ' . $search_string;
    }
    s_debug_dump('C:', $query);
    $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
    /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
    if ($search_charset != '' && strtoupper($response) == 'NO') {
        $query = 'SEARCH CHARSET US-ASCII ' . $search_string;
        s_debug_dump('C:', $query);
        $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
    }
    if (strtoupper($response) != 'OK') {
        sqimap_asearch_error_box($response, $query, $message);
        return array();
    }
    $messagelist = parseUidList($readin, 'SEARCH');
    if (empty($messagelist)) {
        //Empty search response, ie '* SEARCH'
        return array();
    }
    $cnt = count($messagelist);
    for ($q = 0; $q < $cnt; $q++) {
        $id[$q] = trim($messagelist[$q]);
    }
    return $id;
}