Fixed created search strings.

This commit is contained in:
stekkel 2004-06-06 01:43:35 +00:00
parent 3b616f3b8b
commit 73045ee858

View file

@ -1,131 +1,131 @@
<?php <?php
/** /**
* imap_search.php * imap_search.php
* *
* Copyright (c) 1999-2004 The SquirrelMail Project Team * Copyright (c) 1999-2004 The SquirrelMail Project Team
* Licensed under the GNU GPL. For full terms see the file COPYING. * Licensed under the GNU GPL. For full terms see the file COPYING.
* *
* IMAP asearch routines * IMAP asearch routines
* *
* Subfolder search idea from Patch #806075 by Thomas Pohl xraven at users.sourceforge.net. Thanks Thomas! * Subfolder search idea from Patch #806075 by Thomas Pohl xraven at users.sourceforge.net. Thanks Thomas!
* *
* @version $Id$ * @version $Id$
* @package squirrelmail * @package squirrelmail
* @subpackage imap * @subpackage imap
* @see search.php * @see search.php
* @link http://www.ietf.org/rfc/rfc3501.txt * @link http://www.ietf.org/rfc/rfc3501.txt
* @author Alex Lemaresquier - Brainstorm - alex at brainstorm.fr * @author Alex Lemaresquier - Brainstorm - alex at brainstorm.fr
*/ */
/** This functionality requires the IMAP and date functions /** This functionality requires the IMAP and date functions
*/ */
require_once(SM_PATH . 'functions/imap_general.php'); require_once(SM_PATH . 'functions/imap_general.php');
require_once(SM_PATH . 'functions/date.php'); require_once(SM_PATH . 'functions/date.php');
/** Set to TRUE to dump the imap dialogue /** Set to TRUE to dump the imap dialogue
* @global bool $imap_asearch_debug_dump * @global bool $imap_asearch_debug_dump
*/ */
$imap_asearch_debug_dump = FALSE; $imap_asearch_debug_dump = FALSE;
/** Imap SEARCH keys /** Imap SEARCH keys
* @global array $imap_asearch_opcodes * @global array $imap_asearch_opcodes
*/ */
$imap_asearch_opcodes = array( $imap_asearch_opcodes = array(
/* <sequence-set> => 'asequence', */ // Special handling, @see sqimap_asearch_build_criteria() /* <sequence-set> => 'asequence', */ // Special handling, @see sqimap_asearch_build_criteria()
/*'ALL' is binary operator */ /*'ALL' is binary operator */
'ANSWERED' => '', 'ANSWERED' => '',
'BCC' => 'astring', 'BCC' => 'astring',
'BEFORE' => 'adate', 'BEFORE' => 'adate',
'BODY' => 'astring', 'BODY' => 'astring',
'CC' => 'astring', 'CC' => 'astring',
'DELETED' => '', 'DELETED' => '',
'DRAFT' => '', 'DRAFT' => '',
'FLAGGED' => '', 'FLAGGED' => '',
'FROM' => 'astring', 'FROM' => 'astring',
'HEADER' => 'afield', // Special syntax for this one, @see sqimap_asearch_build_criteria() 'HEADER' => 'afield', // Special syntax for this one, @see sqimap_asearch_build_criteria()
'KEYWORD' => 'akeyword', 'KEYWORD' => 'akeyword',
'LARGER' => 'anum', 'LARGER' => 'anum',
'NEW' => '', 'NEW' => '',
/*'NOT' is unary operator */ /*'NOT' is unary operator */
'OLD' => '', 'OLD' => '',
'ON' => 'adate', 'ON' => 'adate',
/*'OR' is binary operator */ /*'OR' is binary operator */
'RECENT' => '', 'RECENT' => '',
'SEEN' => '', 'SEEN' => '',
'SENTBEFORE' => 'adate', 'SENTBEFORE' => 'adate',
'SENTON' => 'adate', 'SENTON' => 'adate',
'SENTSINCE' => 'adate', 'SENTSINCE' => 'adate',
'SINCE' => 'adate', 'SINCE' => 'adate',
'SMALLER' => 'anum', 'SMALLER' => 'anum',
'SUBJECT' => 'astring', 'SUBJECT' => 'astring',
'TEXT' => 'astring', 'TEXT' => 'astring',
'TO' => 'astring', 'TO' => 'astring',
'UID' => 'asequence', 'UID' => 'asequence',
'UNANSWERED' => '', 'UNANSWERED' => '',
'UNDELETED' => '', 'UNDELETED' => '',
'UNDRAFT' => '', 'UNDRAFT' => '',
'UNFLAGGED' => '', 'UNFLAGGED' => '',
'UNKEYWORD' => 'akeyword', 'UNKEYWORD' => 'akeyword',
'UNSEEN' => '' 'UNSEEN' => ''
); );
/** Imap SEARCH month names encoding /** Imap SEARCH month names encoding
* @global array $imap_asearch_months * @global array $imap_asearch_months
*/ */
$imap_asearch_months = array( $imap_asearch_months = array(
'01' => 'jan', '01' => 'jan',
'02' => 'feb', '02' => 'feb',
'03' => 'mar', '03' => 'mar',
'04' => 'apr', '04' => 'apr',
'05' => 'may', '05' => 'may',
'06' => 'jun', '06' => 'jun',
'07' => 'jul', '07' => 'jul',
'08' => 'aug', '08' => 'aug',
'09' => 'sep', '09' => 'sep',
'10' => 'oct', '10' => 'oct',
'11' => 'nov', '11' => 'nov',
'12' => 'dec' '12' => 'dec'
); );
/** Error message titles according to imap server returned code /** Error message titles according to imap server returned code
* @global array $imap_error_titles * @global array $imap_error_titles
*/ */
$imap_error_titles = array( $imap_error_titles = array(
'OK' => '', 'OK' => '',
'NO' => _("ERROR : Could not complete request."), 'NO' => _("ERROR : Could not complete request."),
'BAD' => _("ERROR : Bad or malformed request."), 'BAD' => _("ERROR : Bad or malformed request."),
'BYE' => _("ERROR : Imap server closed the connection."), 'BYE' => _("ERROR : Imap server closed the connection."),
'' => _("ERROR : Connection dropped by imap-server.") '' => _("ERROR : Connection dropped by imap-server.")
); );
/** /**
* Function to display an error related to an IMAP-query. * Function to display an error related to an IMAP-query.
* We need to do our own error management since we may receive NO responses on purpose (even BAD with SORT or THREAD) * We need to do our own error management since we may receive NO responses on purpose (even BAD with SORT or THREAD)
* so we call sqimap_error_box() if the function exists (sm >= 1.5) or use our own embedded code * so we call sqimap_error_box() if the function exists (sm >= 1.5) or use our own embedded code
* @global array imap_error_titles * @global array imap_error_titles
* @param string $response the imap server response code * @param string $response the imap server response code
* @param string $query the failed query * @param string $query the failed query
* @param string $message an optional error message * @param string $message an optional error message
* @param string $link an optional link to try again * @param string $link an optional link to try again
*/ */
//@global array color sm colors array //@global array color sm colors array
function sqimap_asearch_error_box($response, $query, $message, $link = '') function sqimap_asearch_error_box($response, $query, $message, $link = '')
{ {
global $imap_error_titles; global $imap_error_titles;
if (!array_key_exists($response, $imap_error_titles)) if (!array_key_exists($response, $imap_error_titles))
$title = _("ERROR : Unknown imap response."); $title = _("ERROR : Unknown imap response.");
else else
$title = $imap_error_titles[$response]; $title = $imap_error_titles[$response];
if ($link == '') if ($link == '')
$message_title = _("Reason Given: "); $message_title = _("Reason Given: ");
else else
$message_title = _("Possible reason : "); $message_title = _("Possible reason : ");
if (function_exists('sqimap_error_box')) if (function_exists('sqimap_error_box'))
sqimap_error_box($title, $query, $message_title, $message, $link); sqimap_error_box($title, $query, $message_title, $message, $link);
else { //Straight copy of 1.5 imap_general.php:sqimap_error_box(). Can be removed at a later time else { //Straight copy of 1.5 imap_general.php:sqimap_error_box(). Can be removed at a later time
global $color; global $color;
require_once(SM_PATH . 'functions/display_messages.php'); require_once(SM_PATH . 'functions/display_messages.php');
$string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n"; $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
if ($query != '') if ($query != '')
@ -138,333 +138,333 @@ function sqimap_asearch_error_box($response, $query, $message, $link = '')
$string .= $link; $string .= $link;
$string .= "</font><br>\n"; $string .= "</font><br>\n";
error_box($string,$color); error_box($string,$color);
} }
} }
/** /**
* This is a convenient way to avoid spreading if (isset(... all over the code * This is a convenient way to avoid spreading if (isset(... all over the code
* @param mixed $var any variable (reference) * @param mixed $var any variable (reference)
* @param mixed $def default value to return if unset (default is zls (''), pass 0 or array() when appropriate) * @param mixed $def default value to return if unset (default is zls (''), pass 0 or array() when appropriate)
* @return mixed $def if $var is unset, otherwise $var * @return mixed $def if $var is unset, otherwise $var
*/ */
function asearch_nz(&$var, $def = '') function asearch_nz(&$var, $def = '')
{ {
if (isset($var)) if (isset($var))
return $var; return $var;
return $def; return $def;
} }
/** /**
* This should give the same results as PHP 4 >= 4.3.0's html_entity_decode(), * This should give the same results as PHP 4 >= 4.3.0's html_entity_decode(),
* except it doesn't handle hex constructs * except it doesn't handle hex constructs
* @param string $string string to unhtmlentity() * @param string $string string to unhtmlentity()
* @return string decoded string * @return string decoded string
*/ */
function asearch_unhtmlentities($string) { function asearch_unhtmlentities($string) {
$trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES)); $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES));
for ($i=127; $i<255; $i++) /* Add &#<dec>; entities */ for ($i=127; $i<255; $i++) /* Add &#<dec>; entities */
$trans_tbl['&#' . $i . ';'] = chr($i); $trans_tbl['&#' . $i . ';'] = chr($i);
return strtr($string, $trans_tbl); return strtr($string, $trans_tbl);
/* I think the one above is quicker, though it should be benchmarked /* I think the one above is quicker, though it should be benchmarked
$string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES))); $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string); return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
*/ */
} }
/** /**
* Provide an easy way to dump the imap dialogue if $imap_asearch_debug_dump is TRUE * Provide an easy way to dump the imap dialogue if $imap_asearch_debug_dump is TRUE
* @global bool imap_asearch_debug_dump * @global bool imap_asearch_debug_dump
* @param string $var_name * @param string $var_name
* @param string $var_var * @param string $var_var
*/ */
function s_debug_dump($var_name, $var_var) function s_debug_dump($var_name, $var_var)
{ {
global $imap_asearch_debug_dump; global $imap_asearch_debug_dump;
if ($imap_asearch_debug_dump) { if ($imap_asearch_debug_dump) {
if (function_exists('sm_print_r')) //Only exists since 1.4.2 if (function_exists('sm_print_r')) //Only exists since 1.4.2
sm_print_r($var_name, $var_var); //Better be the 'varargs' version ;) sm_print_r($var_name, $var_var); //Better be the 'varargs' version ;)
else { else {
echo '<pre>'; echo '<pre>';
echo htmlentities($var_name); echo htmlentities($var_name);
print_r($var_var); print_r($var_var);
echo '</pre>'; echo '</pre>';
} }
} }
} }
/** Encode a string to quoted or literal as defined in rfc 3501 /** Encode a string to quoted or literal as defined in rfc 3501
* *
* - 4.3 String: * - 4.3 String:
* A quoted string is a sequence of zero or more 7-bit characters, * A quoted string is a sequence of zero or more 7-bit characters,
* excluding CR and LF, with double quote (<">) characters at each end. * excluding CR and LF, with double quote (<">) characters at each end.
* - 9. Formal Syntax: * - 9. Formal Syntax:
* quoted-specials = DQUOTE / "\" * quoted-specials = DQUOTE / "\"
* @param string $what string to encode * @param string $what string to encode
* @param string $charset search charset used * @param string $charset search charset used
* @return string encoded string * @return string encoded string
*/ */
function sqimap_asearch_encode_string($what, $charset) function sqimap_asearch_encode_string($what, $charset)
{ {
if (strtoupper($charset) == 'ISO-2022-JP') // This should be now handled in imap_utf7_local? if (strtoupper($charset) == 'ISO-2022-JP') // This should be now handled in imap_utf7_local?
$what = mb_convert_encoding($what, 'JIS', 'auto'); $what = mb_convert_encoding($what, 'JIS', 'auto');
if (preg_match('/["\\\\\r\n\x80-\xff]/', $what)) if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
return '{' . strlen($what) . "}\r\n" . $what; // 4.3 literal form return '{' . strlen($what) . "}\r\n" . $what; // 4.3 literal form
return '"' . $what . '"'; // 4.3 quoted string form return '"' . $what . '"'; // 4.3 quoted string form
} }
/** /**
* Parses a user date string into an rfc 3501 date string * Parses a user date string into an rfc 3501 date string
* Handles space, slash, backslash, dot and comma as separators (and dash of course ;=) * Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
* @global array imap_asearch_months * @global array imap_asearch_months
* @param string user date * @param string user date
* @return array a preg_match-style array: * @return array a preg_match-style array:
* - [0] = fully formatted rfc 3501 date string (<day number>-<US month TLA>-<4 digit year>) * - [0] = fully formatted rfc 3501 date string (<day number>-<US month TLA>-<4 digit year>)
* - [1] = day * - [1] = day
* - [2] = month * - [2] = month
* - [3] = year * - [3] = year
*/ */
function sqimap_asearch_parse_date($what) function sqimap_asearch_parse_date($what)
{ {
global $imap_asearch_months; global $imap_asearch_months;
$what = trim($what); $what = trim($what);
$what = ereg_replace('[ /\\.,]+', '-', $what); $what = ereg_replace('[ /\\.,]+', '-', $what);
if ($what) { if ($what) {
preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts); preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
if (count($what_parts) == 4) { if (count($what_parts) == 4) {
$what_month = strtolower(asearch_unhtmlentities($what_parts[2])); $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
/* if (!in_array($what_month, $imap_asearch_months)) {*/ /* if (!in_array($what_month, $imap_asearch_months)) {*/
foreach ($imap_asearch_months as $month_number => $month_code) { foreach ($imap_asearch_months as $month_number => $month_code) {
if (($what_month == $month_number) if (($what_month == $month_number)
|| ($what_month == $month_code) || ($what_month == $month_code)
|| ($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number)))) || ($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
|| ($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number)))) || ($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
) { ) {
$what_parts[2] = $month_number; $what_parts[2] = $month_number;
$what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3]; $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
break; break;
} }
} }
/* }*/ /* }*/
} }
} }
else else
$what_parts = array(); $what_parts = array();
return $what_parts; return $what_parts;
} }
/** /**
* Build one criteria sequence * Build one criteria sequence
* @global array imap_asearch_opcodes * @global array imap_asearch_opcodes
* @param string $opcode search opcode * @param string $opcode search opcode
* @param string $what opcode argument * @param string $what opcode argument
* @param string $charset search charset * @param string $charset search charset
* @return string one full criteria sequence * @return string one full criteria sequence
*/ */
function sqimap_asearch_build_criteria($opcode, $what, $charset) function sqimap_asearch_build_criteria($opcode, $what, $charset)
{ {
global $imap_asearch_opcodes; global $imap_asearch_opcodes;
$criteria = ''; $criteria = '';
switch ($imap_asearch_opcodes[$opcode]) { switch ($imap_asearch_opcodes[$opcode]) {
default: default:
case 'anum': case 'anum':
$what = str_replace(' ', '', $what); $what = str_replace(' ', '', $what);
$what = ereg_replace('[^0-9]+[^KMG]$', '', strtoupper($what)); $what = ereg_replace('[^0-9]+[^KMG]$', '', strtoupper($what));
if ($what != '') { if ($what != '') {
switch (substr($what, -1)) { switch (substr($what, -1)) {
case 'G': case 'G':
$what = substr($what, 0, -1) << 30; $what = substr($what, 0, -1) << 30;
break; break;
case 'M': case 'M':
$what = substr($what, 0, -1) << 20; $what = substr($what, 0, -1) << 20;
break; break;
case 'K': case 'K':
$what = substr($what, 0, -1) << 10; $what = substr($what, 0, -1) << 10;
break; break;
} }
$criteria = $opcode . ' ' . $what . ' '; $criteria = $opcode . ' ' . $what . ' ';
} }
break; break;
case '': //aflag case '': //aflag
$criteria = $opcode . ' '; $criteria = $opcode . ' ';
break; break;
case 'afield': /* HEADER field-name: field-body */ case 'afield': /* HEADER field-name: field-body */
preg_match('/^([^:]+):(.*)$/', $what, $what_parts); preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
if (count($what_parts) == 3) if (count($what_parts) == 3)
$criteria = $opcode . ' ' . $criteria = $opcode . ' ' .
sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' . sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
sqimap_asearch_encode_string($what_parts[2], $charset) . ' '; sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
break; break;
case 'adate': case 'adate':
$what_parts = sqimap_asearch_parse_date($what); $what_parts = sqimap_asearch_parse_date($what);
if (isset($what_parts[0])) if (isset($what_parts[0]))
$criteria = $opcode . ' ' . $what_parts[0] . ' '; $criteria = $opcode . ' ' . $what_parts[0] . ' ';
break; break;
case 'akeyword': case 'akeyword':
case 'astring': case 'astring':
$criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' '; $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
break; break;
case 'asequence': case 'asequence':
$what = ereg_replace('[^0-9:\(\)]+', '', $what); $what = ereg_replace('[^0-9:\(\)]+', '', $what);
if ($what != '') if ($what != '')
$criteria = $opcode . ' ' . $what . ' '; $criteria = $opcode . ' ' . $what . ' ';
break; break;
} }
return $criteria; return $criteria;
} }
/** /**
* Another way to do array_values(array_unique(array_merge($to, $from))); * Another way to do array_values(array_unique(array_merge($to, $from)));
* @param array $to to array (reference) * @param array $to to array (reference)
* @param array $from from array * @param array $from from array
* @return array uniquely merged array * @return array uniquely merged array
*/ */
function sqimap_array_merge_unique(&$to, $from) function sqimap_array_merge_unique(&$to, $from)
{ {
if (empty($to)) if (empty($to))
return $from; return $from;
$count = count($from); $count = count($from);
for ($i = 0; $i < $count; $i++) { for ($i = 0; $i < $count; $i++) {
if (!in_array($from[$i], $to)) if (!in_array($from[$i], $to))
$to[] = $from[$i]; $to[] = $from[$i];
} }
return $to; return $to;
} }
/** /**
* Run the imap SEARCH command as defined in rfc 3501 * Run the imap SEARCH command as defined in rfc 3501
* @link http://www.ietf.org/rfc/rfc3501.txt * @link http://www.ietf.org/rfc/rfc3501.txt
* @param resource $imapConnection the current imap stream * @param resource $imapConnection the current imap stream
* @param string $search_string the full search expression eg "ALL RECENT" * @param string $search_string the full search expression eg "ALL RECENT"
* @param string $search_charset charset to use or zls ('') * @param string $search_charset charset to use or zls ('')
* @return array an IDs or UIDs array of matching messages or an empty array * @return array an IDs or UIDs array of matching messages or an empty array
*/ */
function sqimap_run_search($imapConnection, $search_string, $search_charset) function sqimap_run_search($imapConnection, $search_string, $search_charset)
{ {
//For some reason, this seems to happen and forbids searching servers not allowing OPTIONAL [CHARSET] //For some reason, this seems to happen and forbids searching servers not allowing OPTIONAL [CHARSET]
if (strtoupper($search_charset) == 'US-ASCII') if (strtoupper($search_charset) == 'US-ASCII')
$search_charset = ''; $search_charset = '';
/* 6.4.4 try OPTIONAL [CHARSET] specification first */ /* 6.4.4 try OPTIONAL [CHARSET] specification first */
if ($search_charset != '') if ($search_charset != '')
$query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ' . $search_string; $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ' . $search_string;
else else
$query = 'SEARCH ' . $search_string; $query = 'SEARCH ' . $search_string;
s_debug_dump('C:', $query); s_debug_dump('C:', $query);
$readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE); $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]) */ /* 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')) { if (($search_charset != '') && (strtoupper($response) == 'NO')) {
$query = 'SEARCH CHARSET US-ASCII ' . $search_string; $query = 'SEARCH CHARSET US-ASCII ' . $search_string;
s_debug_dump('C:', $query); s_debug_dump('C:', $query);
$readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE); $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
} }
if (strtoupper($response) != 'OK') { if (strtoupper($response) != 'OK') {
sqimap_asearch_error_box($response, $query, $message); sqimap_asearch_error_box($response, $query, $message);
return array(); return array();
} }
$messagelist = parseUidList($readin,'SEARCH'); $messagelist = parseUidList($readin,'SEARCH');
if (empty($messagelist)) //Empty search response, ie '* SEARCH' if (empty($messagelist)) //Empty search response, ie '* SEARCH'
return array(); return array();
$cnt = count($messagelist); $cnt = count($messagelist);
for ($q = 0; $q < $cnt; $q++) for ($q = 0; $q < $cnt; $q++)
$id[$q] = trim($messagelist[$q]); $id[$q] = trim($messagelist[$q]);
return $id; return $id;
} }
/** /**
* @global bool allow_charset_search user setting * @global bool allow_charset_search user setting
* @global array languages sm languages array * @global array languages sm languages array
* @global string squirrelmail_language user language setting * @global string squirrelmail_language user language setting
* @return string the user defined charset if $allow_charset_search is TRUE else zls ('') * @return string the user defined charset if $allow_charset_search is TRUE else zls ('')
*/ */
function sqimap_asearch_get_charset() function sqimap_asearch_get_charset()
{ {
global $allow_charset_search, $languages, $squirrelmail_language; global $allow_charset_search, $languages, $squirrelmail_language;
if ($allow_charset_search) if ($allow_charset_search)
return $languages[$squirrelmail_language]['CHARSET']; return $languages[$squirrelmail_language]['CHARSET'];
return ''; return '';
} }
/** /**
* Convert sm internal sort to imap sort taking care of: * Convert sm internal sort to imap sort taking care of:
* - user defined date sorting (ARRIVAL vs DATE) * - user defined date sorting (ARRIVAL vs DATE)
* - if the searched mailbox is the sent folder then TO is being used instead of FROM * - if the searched mailbox is the sent folder then TO is being used instead of FROM
* - reverse order by using REVERSE * - reverse order by using REVERSE
* @param string $mailbox mailbox name to sort * @param string $mailbox mailbox name to sort
* @param integer $sort_by sm sort criteria index * @param integer $sort_by sm sort criteria index
* @global bool internal_date_sort sort by arrival date instead of message date * @global bool internal_date_sort sort by arrival date instead of message date
* @global string sent_folder sent folder name * @global string sent_folder sent folder name
* @return string imap sort criteria * @return string imap sort criteria
*/ */
function sqimap_asearch_get_sort_criteria($mailbox, $sort_by) function sqimap_asearch_get_sort_criteria($mailbox, $sort_by)
{ {
global $internal_date_sort, $sent_folder; global $internal_date_sort, $sent_folder;
$sort_opcodes = array ('DATE', 'FROM', 'SUBJECT', 'SIZE'); $sort_opcodes = array ('DATE', 'FROM', 'SUBJECT', 'SIZE');
if ($internal_date_sort == true) if ($internal_date_sort == true)
$sort_opcodes[0] = 'ARRIVAL'; $sort_opcodes[0] = 'ARRIVAL';
// if (handleAsSent($mailbox)) // if (handleAsSent($mailbox))
// if (isSentFolder($mailbox)) // if (isSentFolder($mailbox))
if ($mailbox == $sent_folder) if ($mailbox == $sent_folder)
$sort_opcodes[1] = 'TO'; $sort_opcodes[1] = 'TO';
return (($sort_by % 2) ? '' : 'REVERSE ') . $sort_opcodes[($sort_by >> 1) & 3]; return (($sort_by % 2) ? '' : 'REVERSE ') . $sort_opcodes[($sort_by >> 1) & 3];
} }
/** /**
* @param string $cur_mailbox unformatted mailbox name * @param string $cur_mailbox unformatted mailbox name
* @param array $boxes_unformatted selectable mailbox unformatted names array (reference) * @param array $boxes_unformatted selectable mailbox unformatted names array (reference)
* @return array sub mailboxes unformatted names * @return array sub mailboxes unformatted names
*/ */
function sqimap_asearch_get_sub_mailboxes($cur_mailbox, &$mboxes_array) function sqimap_asearch_get_sub_mailboxes($cur_mailbox, &$mboxes_array)
{ {
$sub_mboxes_array = array(); $sub_mboxes_array = array();
$boxcount = count($mboxes_array); $boxcount = count($mboxes_array);
for ($boxnum=0; $boxnum < $boxcount; $boxnum++) { for ($boxnum=0; $boxnum < $boxcount; $boxnum++) {
if (isBoxBelow($mboxes_array[$boxnum], $cur_mailbox)) if (isBoxBelow($mboxes_array[$boxnum], $cur_mailbox))
$sub_mboxes_array[] = $mboxes_array[$boxnum]; $sub_mboxes_array[] = $mboxes_array[$boxnum];
} }
return $sub_mboxes_array; return $sub_mboxes_array;
} }
/** /**
* Create the search query strings for all given criteria and merge results for every mailbox * Create the search query strings for all given criteria and merge results for every mailbox
* @param resource $imapConnection * @param resource $imapConnection
* @param array $mailbox_array (reference) * @param array $mailbox_array (reference)
* @param array $biop_array (reference) * @param array $biop_array (reference)
* @param array $unop_array (reference) * @param array $unop_array (reference)
* @param array $where_array (reference) * @param array $where_array (reference)
* @param array $what_array (reference) * @param array $what_array (reference)
* @param array $exclude_array (reference) * @param array $exclude_array (reference)
* @param array $sub_array (reference) * @param array $sub_array (reference)
* @param array $mboxes_array selectable unformatted mailboxes names (reference) * @param array $mboxes_array selectable unformatted mailboxes names (reference)
* @return array array(mailbox => array(UIDs)) * @return array array(mailbox => array(UIDs))
*/ */
function sqimap_asearch($imapConnection, &$mailbox_array, &$biop_array, &$unop_array, &$where_array, &$what_array, &$exclude_array, &$sub_array, &$mboxes_array) function sqimap_asearch($imapConnection, &$mailbox_array, &$biop_array, &$unop_array, &$where_array, &$what_array, &$exclude_array, &$sub_array, &$mboxes_array)
{ {
$search_charset = sqimap_asearch_get_charset(); $search_charset = sqimap_asearch_get_charset();
$mbox_msgs = array(); $mbox_msgs = array();
$mbox_search = array(); $mbox_search = array();
$search_string = ''; $search_string = '';
$cur_mailbox = $mailbox_array[0]; $cur_mailbox = $mailbox_array[0];
$cur_biop = ''; /* Start with ALL */ $cur_biop = ''; /* Start with ALL */
/* We loop one more time than the real array count, so the last search gets fired */ /* We loop one more time than the real array count, so the last search gets fired */
for ($cur_crit=0,$iCnt=count($where_array); $cur_crit <= $iCnt; ++$cur_crit) { for ($cur_crit=0,$iCnt=count($where_array); $cur_crit <= $iCnt; ++$cur_crit) {
if (empty($exclude_array[$cur_crit])) { if (empty($exclude_array[$cur_crit])) {
$next_mailbox = $mailbox_array[$cur_crit]; $next_mailbox = (isset($mailbox_array[$cur_crit])) ? $mailbox_array[$cur_crit] : false;
if ($next_mailbox != $cur_mailbox) { if ($next_mailbox != $cur_mailbox) {
$search_string = trim($search_string); /* Trim out last space */ $search_string = trim($search_string); /* Trim out last space */
if ($cur_mailbox == 'All Folders') if ($cur_mailbox == 'All Folders')
$search_mboxes = $mboxes_array; $search_mboxes = $mboxes_array;
else if ((!empty($sub_array[$cur_crit - 1])) || (!in_array($cur_mailbox, $mboxes_array))) else if ((!empty($sub_array[$cur_crit - 1])) || (!in_array($cur_mailbox, $mboxes_array)))
$search_mboxes = sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array); $search_mboxes = sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array);
else else
$search_mboxes = array($cur_mailbox); $search_mboxes = array($cur_mailbox);
foreach ($search_mboxes as $cur_mailbox) { foreach ($search_mboxes as $cur_mailbox) {
if (isset($mbox_search[$cur_mailbox])) { if (isset($mbox_search[$cur_mailbox])) {
$mbox_search[$cur_mailbox]['search'] .= ' ' . $search_string; $mbox_search[$cur_mailbox]['search'] .= ' ' . $search_string;
} else { } else {
@ -472,44 +472,60 @@ function sqimap_asearch($imapConnection, &$mailbox_array, &$biop_array, &$unop_a
} }
$mbox_search[$cur_mailbox]['charset'] = $search_charset; $mbox_search[$cur_mailbox]['charset'] = $search_charset;
} }
$cur_mailbox = $next_mailbox; $cur_mailbox = $next_mailbox;
$search_string = ''; $search_string = '';
} }
if (isset($where_array[$cur_crit]) && empty($exclude_array[$cur_crit])) { if (isset($where_array[$cur_crit]) && empty($exclude_array[$cur_crit])) {
$criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset); for ($crit = $cur_crit; $crit < count($where_array); $crit++) {
if (!empty($criteria)) { $criteria = trim(sqimap_asearch_build_criteria($where_array[$crit], $what_array[$crit], $search_charset));
//$criteria = 'ALL '. $criteria; if (!empty($criteria) && empty($exclude_array[$crit])) {
$unop = $unop_array[$cur_crit]; if (asearch_nz($mailbox_array[$crit]) == $cur_mailbox) {
if (!empty($unop)) { $unop = $unop_array[$crit];
$criteria = $unop . ' ' . $criteria; if (!empty($unop)) {
} else { $criteria = $unop . ' ' . $criteria;
$criteria = 'ALL ' . $criteria; }
$aCriteria[] = array($biop_array[$crit], $criteria);
}
} }
/* We need to infix the next non-excluded criteria's biop if it's the same mailbox */ // unset something
$next_biop = ''; $exclude_array[$crit] = true;
for ($next_crit = $cur_crit+1; $next_crit <= count($where_array); $next_crit++) { }
if (empty($exclude_array[$next_crit])) { $aSearch = array();
if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox) { for($i=0,$iCnt=count($aCriteria);$i<$iCnt;++$i) {
$next_biop = asearch_nz($biop_array[$next_crit]); $cur_biop = $aCriteria[$i][0];
if ($next_biop == 'OR' || $next_biop == 'ALL') { $next_biop = (isset($aCriteria[$i+1][0])) ? $aCriteria[$i+1][0] : false;
$next_criterium = sqimap_asearch_build_criteria($where_array[$next_crit], $what_array[$next_crit], $search_charset); if ($next_biop != $cur_biop && $next_biop == 'OR') {
// unset something $aSearch[] = 'OR '.$aCriteria[$i][1];
$exclude_array[$next_crit] = true; } else if ($cur_biop != 'OR') {
$criteria .= $next_biop . ' '. $next_criterium; $aSearch[] = 'ALL '.$aCriteria[$i][1];
} else { // or only supports 2 search keys so we need to create a parenthized list
$prev_biop = (isset($aCriteria[$i-1][0])) ? $aCriteria[$i-1][0] : false;
if ($prev_biop == $cur_biop) {
$last = $aSearch[$i-1];
if (!substr($last,-1) == ')') {
$aSearch[$i-1] = "(OR $last";
$aSearch[] = $aCriteria[$i][1].')';
} else {
$sEnd = '';
while ($last && substr($last,-1) == ')') {
$last = substr($last,0,-1);
$sEnd .= ')';
} }
} $aSearch[$i-1] = "(OR $last";
} $aSearch[] = $aCriteria[$i][1].$sEnd.')';
} }
//if ($next_biop == 'OR') } else {
// $criteria = $next_biop . ' ' . $criteria; $aSearch[] = $aCriteria[$i][1];
$search_string .= $criteria; }
//$cur_biop = asearch_nz($biop_array[$cur_crit]); }
}
}
} }
} $search_string .= implode(' ',$aSearch);
}
}
}
return ($mbox_search); return ($mbox_search);
} }