6 * Copyright (c) 1999-2003 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * IMAP asearch routines
10 * Alex Lemaresquier - Brainstorm - alex at brainstorm.fr
11 * See README file for infos.
15 require_once(SM_PATH
. 'functions/imap_general.php');
16 require_once(SM_PATH
. 'functions/date.php');
18 /* Set to TRUE to dump the imap dialogue */
19 $imap_asearch_debug_dump = FALSE;
21 $imap_asearch_opcodes = array(
22 /* <message set> => 'asequence', */
23 /*'ALL' is binary operator */
33 'HEADER' => 'afield', /* Special syntax for this one, see below */
34 'KEYWORD' => 'akeyword',
37 /*'NOT' is unary operator */
40 /*'OR' is binary operator */
43 'SENTBEFORE' => 'adate',
45 'SENTSINCE' => 'adate',
48 'SUBJECT' => 'astring',
56 'UNKEYWORD' => 'akeyword',
60 $imap_asearch_months = array(
75 $imap_error_titles = array(
77 'NO' => _("ERROR : Could not complete request."),
78 'BAD' => _("ERROR : Bad or malformed request."),
79 'BYE' => _("ERROR : Imap server closed the connection.")
82 function sqimap_asearch_error_box($response, $query, $message)
84 global $imap_error_titles;
86 //if (!array_key_exists($response, $imap_error_titles)) //php 4.0.6 compatibility
87 if (!in_array($response, array_keys($imap_error_titles)))
88 $title = _("ERROR : Unknown imap response.");
90 $title = $imap_error_titles[$response];
91 sqimap_error_box($title, $query, _("Reason Given: "), $message);
94 /* This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc! */
95 function asearch_nz(&$var)
102 /* This should give the same results as PHP 4 >= 4.3.0's html_entity_decode() */
103 function asearch_unhtmlentities($string) {
104 $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES
));
105 for ($i=127; $i<255; $i++
) /* Add &#<dec>; entities */
106 $trans_tbl['&#' . $i . ';'] = chr($i);
107 return strtr($string, $trans_tbl);
108 /* I think the one above is quicker, though it should be benchmarked
109 $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
110 return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
114 function s_debug_dump($var_name, $var_var)
116 global $imap_asearch_debug_dump;
117 if ($imap_asearch_debug_dump) {
118 if (function_exists('sm_print_r'))
119 sm_print_r($var_name, $var_var); //Better be the 'varargs' version ;)
122 echo htmlentities($var_name);
131 A quoted string is a sequence of zero or more 7-bit characters,
132 excluding CR and LF, with double quote (<">) characters at each end.
134 quoted-specials = DQUOTE / "\"
136 function sqimap_asearch_encode_string($what, $search_charset)
138 if (strtoupper($search_charset) == 'ISO-2022-JP')
139 $what = mb_convert_encoding($what, 'JIS', 'auto');
140 //if (ereg("[\"\\\r\n\x80-\xff]", $what))
141 if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
142 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
143 return '"' . $what . '"'; /* 4.3 quoted string form */
147 Parses a user date string into an rfc2060 date string (<day number>-<US month TLA>-<4 digit year>)
148 Returns a preg_match-style array: [0]: fully formatted date, [1]: day, [2]: month, [3]: year
149 Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
151 function sqimap_asearch_parse_date($what)
153 global $imap_asearch_months;
156 $what = ereg_replace('[ /\\.,]+', '-', $what);
158 preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
159 if (count($what_parts) == 4) {
160 $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
161 /* if (!in_array($what_month, $imap_asearch_months)) {*/
162 foreach ($imap_asearch_months as $month_number => $month_code) {
163 if (($what_month == $month_number)
164 ||
($what_month == $month_code)
165 ||
($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
166 ||
($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
168 $what_parts[2] = $month_number;
169 $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
177 $what_parts = array();
181 function sqimap_asearch_build_criteria($opcode, $what, $search_charset)
183 global $imap_asearch_opcodes;
186 switch ($imap_asearch_opcodes[$opcode]) {
189 /* $what = str_replace(' ', '', $what);*/
190 $what = ereg_replace('[^0-9]+', '', $what);
192 $criteria = $opcode . ' ' . $what . ' ';
195 $criteria = $opcode . ' ';
197 case 'afield': /* HEADER field-name: field-body */
198 preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
199 if (count($what_parts) == 3)
200 $criteria = $opcode . ' ' .
201 sqimap_asearch_encode_string($what_parts[1], $search_charset) . ' ' .
202 sqimap_asearch_encode_string($what_parts[2], $search_charset) . ' ';
205 $what_parts = sqimap_asearch_parse_date($what);
206 if (isset($what_parts[0]))
207 $criteria = $opcode . ' ' . $what_parts[0] . ' ';
211 $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $search_charset) . ' ';
214 $what = ereg_replace('[^0-9:\(\)]+', '', $what);
216 $criteria = $opcode . ' ' . $what . ' ';
222 function sqimap_run_search($imapConnection, $search_string, $search_charset)
224 global $allow_charset_search, $uid_support;
226 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
227 if ($allow_charset_search && (!empty($search_charset)))
228 $query = 'SEARCH CHARSET ' . strtoupper($search_charset) . ' ALL ' . $search_string;
230 $query = 'SEARCH ALL ' . $search_string;
231 s_debug_dump('C:', $query);
233 /* read data back from IMAP */
234 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
236 /* 6.4.4 try US-ASCII charset if we receive a tagged NO response */
237 if ((!empty($charset)) && (strtoupper($response) == 'NO')) {
238 $query = 'SEARCH CHARSET "US-ASCII" ALL ' . $search_string;
239 s_debug_dump('C:', $query);
240 $readin = sqimap_run_command ($imapConnection, $query, false, $response, $message, $uid_support); /* added $uid_support */
242 if (strtoupper($response) != 'OK') {
243 sqimap_asearch_error_box($response, $query, $message);
249 /* Keep going till we find the SEARCH response */
250 foreach ($readin as $readin_part) {
251 s_debug_dump('S:', $readin_part);
252 /* Check to see if a SEARCH response was received */
253 if (substr($readin_part, 0, 9) == '* SEARCH ') {
254 $messagelist = preg_split("/ /", substr($readin_part, 9));
255 break; // Should be the last anyway
259 $errors = $errors . $readin_part;
261 $errors = $readin_part;
265 /* If nothing is found * SEARCH should be the first error else echo errors */
266 /*if (isset($errors)) {
267 if (strstr($errors,'* SEARCH'))
269 echo '<!-- ' . htmlspecialchars($errors) . ' -->';
272 if (empty($messagelist)) //Empty search response, ie '* SEARCH'
275 $cnt = count($messagelist);
276 for ($q = 0; $q < $cnt; $q++
)
277 $id[$q] = trim($messagelist[$q]);
281 /* replaces $mbox_msgs[$search_mailbox] = array_values(array_unique(array_merge($mbox_msgs[$search_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset))));*/
282 function sqimap_array_merge_unique($to, $from)
286 for ($i=0; $i<count($from); $i++
) {
287 if (!in_array($from[$i], $to))
293 function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $mboxes_array)
295 global $languages, $squirrelmail_language;
297 /* ??? what are those for ?? */
298 /* $pos = $search_position;*/
300 $mbox_msgs = array();
301 $search_charset = $languages[$squirrelmail_language]['CHARSET'];
303 $cur_mailbox = $mailbox_array[0];
304 $cur_biop = ''; /* Start with ALL */
305 /* We loop one more time than the real array count, so the last search gets fired */
306 for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++
) {
307 if (empty($exclude_array[$cur_crit])) {
308 $next_mailbox = $mailbox_array[$cur_crit];
309 if ($next_mailbox != $cur_mailbox) {
310 $search_string = trim($search_string); /* Trim out last space */
311 if (($cur_mailbox == 'All Folders') && (!empty($mboxes_array)))
312 $search_mboxes = $mboxes_array;
314 $search_mboxes = array($cur_mailbox);
315 foreach ($search_mboxes as $cur_mailbox) {
316 s_debug_dump('C:SELECT:', $cur_mailbox);
317 sqimap_mailbox_select($imapConnection, $cur_mailbox);
318 if (isset($mbox_msgs[$cur_mailbox])) {
319 if ($cur_biop == 'OR') /* Merge with previous results */
320 $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset));
321 else /* Intersect previous results */
322 $mbox_msgs[$cur_mailbox] = array_values(array_intersect(sqimap_run_search($imapConnection, $search_string, $search_charset), $mbox_msgs[$cur_mailbox]));
324 else /* No previous results */
325 $mbox_msgs[$cur_mailbox] = sqimap_run_search($imapConnection, $search_string, $search_charset);
326 if (empty($mbox_msgs[$cur_mailbox])) /* Can happen with intersect, and we need at the end a contiguous array */
327 unset($mbox_msgs[$cur_mailbox]);
329 $cur_mailbox = $next_mailbox;
332 if (isset($where_array[$cur_crit])) {
333 $criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset);
334 if (!empty($criteria)) {
335 $unop = $unop_array[$cur_crit];
337 $criteria = $unop . ' ' . $criteria;
338 /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
340 for ($next_crit = $cur_crit+
1; $next_crit <= count($where_array); $next_crit++
) {
341 if (empty($exclude_array[$next_crit])) {
342 if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox)
343 $next_biop = asearch_nz($biop_array[$next_crit]);
347 if ($next_biop == 'OR')
348 $criteria = $next_biop . ' ' . $criteria;
349 $search_string .= $criteria;
350 $cur_biop = asearch_nz($biop_array[$cur_crit]);