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 * @author Alex Lemaresquier - Brainstorm - alex at brainstorm.fr
11 * See README file for infos.
12 * @package squirrelmail
16 /** This functionality requires the IMAP and date functions */
17 require_once(SM_PATH
. 'functions/imap_general.php');
18 require_once(SM_PATH
. 'functions/date.php');
20 /** Set to TRUE to dump the imap dialogue */
21 $imap_asearch_debug_dump = FALSE;
23 $imap_asearch_opcodes = array(
24 /* <message set> => 'asequence', */
25 /*'ALL' is binary operator */
35 'HEADER' => 'afield', /* Special syntax for this one, see below */
36 'KEYWORD' => 'akeyword',
39 /*'NOT' is unary operator */
42 /*'OR' is binary operator */
45 'SENTBEFORE' => 'adate',
47 'SENTSINCE' => 'adate',
50 'SUBJECT' => 'astring',
58 'UNKEYWORD' => 'akeyword',
62 $imap_asearch_months = array(
77 $imap_error_titles = array(
79 'NO' => _("ERROR : Could not complete request."),
80 'BAD' => _("ERROR : Bad or malformed request."),
81 'BYE' => _("ERROR : Imap server closed the connection.")
84 function sqimap_asearch_error_box($response, $query, $message)
86 global $imap_error_titles;
88 //if (!array_key_exists($response, $imap_error_titles)) //php 4.0.6 compatibility
89 if (!in_array($response, array_keys($imap_error_titles)))
90 $title = _("ERROR : Unknown imap response.");
92 $title = $imap_error_titles[$response];
93 $message_title = _("Reason Given: ");
94 if (function_exists('sqimap_error_box'))
95 sqimap_error_box($title, $query, $message_title, $message);
96 else { //Straight copy of 1.5 imap_general.php:sqimap_error_box(). Can be removed at a later time
98 require_once(SM_PATH
. 'functions/display_messages.php');
99 $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
101 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
102 if ($message_title != '')
103 $string .= $message_title;
105 $string .= htmlspecialchars($message);
106 $string .= "</font><br>\n";
107 error_box($string,$color);
111 /* This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc! */
112 function asearch_nz(&$var)
119 /* This should give the same results as PHP 4 >= 4.3.0's html_entity_decode(), except it doesn't handle hex constructs */
120 function asearch_unhtmlentities($string) {
121 $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES
));
122 for ($i=127; $i<255; $i++
) /* Add &#<dec>; entities */
123 $trans_tbl['&#' . $i . ';'] = chr($i);
124 return strtr($string, $trans_tbl);
125 /* I think the one above is quicker, though it should be benchmarked
126 $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
127 return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
131 function s_debug_dump($var_name, $var_var)
133 global $imap_asearch_debug_dump;
134 if ($imap_asearch_debug_dump) {
135 if (function_exists('sm_print_r')) //Only exists since 1.4.2
136 sm_print_r($var_name, $var_var); //Better be the 'varargs' version ;)
139 echo htmlentities($var_name);
148 A quoted string is a sequence of zero or more 7-bit characters,
149 excluding CR and LF, with double quote (<">) characters at each end.
151 quoted-specials = DQUOTE / "\"
153 function sqimap_asearch_encode_string($what, $charset)
155 if (strtoupper($charset) == 'ISO-2022-JP') // This should be now handled in imap_utf7_local?
156 $what = mb_convert_encoding($what, 'JIS', 'auto');
157 //if (ereg("[\"\\\r\n\x80-\xff]", $what))
158 if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
159 return '{' . strlen($what) . "}\r\n" . $what; // 4.3 literal form
160 return '"' . $what . '"'; // 4.3 quoted string form
164 Parses a user date string into an rfc2060 date string (<day number>-<US month TLA>-<4 digit year>)
165 Returns a preg_match-style array: [0]: fully formatted date, [1]: day, [2]: month, [3]: year
166 Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
168 function sqimap_asearch_parse_date($what)
170 global $imap_asearch_months;
173 $what = ereg_replace('[ /\\.,]+', '-', $what);
175 preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
176 if (count($what_parts) == 4) {
177 $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
178 /* if (!in_array($what_month, $imap_asearch_months)) {*/
179 foreach ($imap_asearch_months as $month_number => $month_code) {
180 if (($what_month == $month_number)
181 ||
($what_month == $month_code)
182 ||
($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
183 ||
($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
185 $what_parts[2] = $month_number;
186 $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
194 $what_parts = array();
198 function sqimap_asearch_build_criteria($opcode, $what, $charset)
200 global $imap_asearch_opcodes;
203 switch ($imap_asearch_opcodes[$opcode]) {
206 /* $what = str_replace(' ', '', $what);*/
207 $what = ereg_replace('[^0-9]+', '', $what);
209 $criteria = $opcode . ' ' . $what . ' ';
212 $criteria = $opcode . ' ';
214 case 'afield': /* HEADER field-name: field-body */
215 preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
216 if (count($what_parts) == 3)
217 $criteria = $opcode . ' ' .
218 sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
219 sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
222 $what_parts = sqimap_asearch_parse_date($what);
223 if (isset($what_parts[0]))
224 $criteria = $opcode . ' ' . $what_parts[0] . ' ';
228 $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
231 $what = ereg_replace('[^0-9:\(\)]+', '', $what);
233 $criteria = $opcode . ' ' . $what . ' ';
239 function sqimap_run_search($imapConnection, $search_string, $search_charset)
243 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
244 if ($search_charset != '')
245 $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
247 $query = 'SEARCH ALL ' . $search_string;
248 s_debug_dump('C:', $query);
249 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
251 /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
252 if (($search_charset != '') && (strtoupper($response) == 'NO')) {
253 $query = 'SEARCH CHARSET US-ASCII ALL ' . $search_string;
254 s_debug_dump('C:', $query);
255 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
257 if (strtoupper($response) != 'OK') {
258 sqimap_asearch_error_box($response, $query, $message);
264 /* Keep going till we find the SEARCH response */
265 foreach ($readin as $readin_part) {
266 s_debug_dump('S:', $readin_part);
267 /* Check to see if a SEARCH response was received */
268 if (substr($readin_part, 0, 9) == '* SEARCH ') {
269 $messagelist = preg_split("/ /", substr($readin_part, 9));
270 break; // Should be the last anyway
274 $errors = $errors . $readin_part;
276 $errors = $readin_part;
280 /* If nothing is found * SEARCH should be the first error else echo errors */
281 /*if (isset($errors)) {
282 if (strstr($errors,'* SEARCH'))
284 echo '<!-- ' . htmlspecialchars($errors) . ' -->';
287 if (empty($messagelist)) //Empty search response, ie '* SEARCH'
290 $cnt = count($messagelist);
291 for ($q = 0; $q < $cnt; $q++
)
292 $id[$q] = trim($messagelist[$q]);
296 function sqimap_asearch_get_charset()
298 global $allow_charset_search, $languages, $squirrelmail_language;
300 if ($allow_charset_search)
301 return $languages[$squirrelmail_language]['CHARSET'];
305 /* replaces $mbox_msgs[$search_mailbox] = array_values(array_unique(array_merge($mbox_msgs[$search_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset))));*/
306 function sqimap_array_merge_unique($to, $from)
310 for ($i=0; $i<count($from); $i++
) {
311 if (!in_array($from[$i], $to))
317 function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $mboxes_array)
319 $search_charset = sqimap_asearch_get_charset();
320 $mbox_msgs = array();
322 $cur_mailbox = $mailbox_array[0];
323 $cur_biop = ''; /* Start with ALL */
324 /* We loop one more time than the real array count, so the last search gets fired */
325 for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++
) {
326 if (empty($exclude_array[$cur_crit])) {
327 $next_mailbox = $mailbox_array[$cur_crit];
328 if ($next_mailbox != $cur_mailbox) {
329 $search_string = trim($search_string); /* Trim out last space */
330 if (($cur_mailbox == 'All Folders') && (!empty($mboxes_array)))
331 $search_mboxes = $mboxes_array;
333 $search_mboxes = array($cur_mailbox);
334 foreach ($search_mboxes as $cur_mailbox) {
335 s_debug_dump('C:SELECT:', $cur_mailbox);
336 sqimap_mailbox_select($imapConnection, $cur_mailbox);
337 if (isset($mbox_msgs[$cur_mailbox])) {
338 if ($cur_biop == 'OR') /* Merge with previous results */
339 $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset));
340 else /* Intersect previous results */
341 $mbox_msgs[$cur_mailbox] = array_values(array_intersect(sqimap_run_search($imapConnection, $search_string, $search_charset), $mbox_msgs[$cur_mailbox]));
343 else /* No previous results */
344 $mbox_msgs[$cur_mailbox] = sqimap_run_search($imapConnection, $search_string, $search_charset);
345 if (empty($mbox_msgs[$cur_mailbox])) /* Can happen with intersect, and we need at the end a contiguous array */
346 unset($mbox_msgs[$cur_mailbox]);
348 $cur_mailbox = $next_mailbox;
351 if (isset($where_array[$cur_crit])) {
352 $criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset);
353 if (!empty($criteria)) {
354 $unop = $unop_array[$cur_crit];
356 $criteria = $unop . ' ' . $criteria;
357 /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
359 for ($next_crit = $cur_crit+
1; $next_crit <= count($where_array); $next_crit++
) {
360 if (empty($exclude_array[$next_crit])) {
361 if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox)
362 $next_biop = asearch_nz($biop_array[$next_crit]);
366 if ($next_biop == 'OR')
367 $criteria = $next_biop . ' ' . $criteria;
368 $search_string .= $criteria;
369 $cur_biop = asearch_nz($biop_array[$cur_crit]);