d2555578a603a25aa1a83584994bba773a2b5d80
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 // why can't this just use sqimap_error_box() ?
85 function sqimap_asearch_error_box($response, $query, $message)
87 global $imap_error_titles;
89 //if (!array_key_exists($response, $imap_error_titles)) //php 4.0.6 compatibility
90 if (!in_array($response, array_keys($imap_error_titles)))
91 $title = _("ERROR : Unknown imap response.");
93 $title = $imap_error_titles[$response];
94 $message_title = _("Reason Given: ");
95 if (function_exists('sqimap_error_box'))
96 sqimap_error_box($title, $query, $message_title, $message);
97 else { //Straight copy of 1.5 imap_general.php:sqimap_error_box(). Can be removed at a later time
99 require_once(SM_PATH
. 'functions/display_messages.php');
100 $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
102 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
103 if ($message_title != '')
104 $string .= $message_title;
106 $string .= htmlspecialchars($message);
107 $string .= "</font><br>\n";
108 error_box($string,$color);
113 * This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc!
115 function asearch_nz(&$var)
123 * This should give the same results as PHP 4 >= 4.3.0's html_entity_decode(),
124 * except it doesn't handle hex constructs
126 function asearch_unhtmlentities($string) {
127 $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES
));
128 for ($i=127; $i<255; $i++
) /* Add &#<dec>; entities */
129 $trans_tbl['&#' . $i . ';'] = chr($i);
130 return strtr($string, $trans_tbl);
131 /* I think the one above is quicker, though it should be benchmarked
132 $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
133 return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
137 function s_debug_dump($var_name, $var_var)
139 global $imap_asearch_debug_dump;
140 if ($imap_asearch_debug_dump) {
141 if (function_exists('sm_print_r')) //Only exists since 1.4.2
142 sm_print_r($var_name, $var_var); //Better be the 'varargs' version ;)
145 echo htmlentities($var_name);
154 A quoted string is a sequence of zero or more 7-bit characters,
155 excluding CR and LF, with double quote (<">) characters at each end.
157 quoted-specials = DQUOTE / "\"
159 function sqimap_asearch_encode_string($what, $charset)
161 if (strtoupper($charset) == 'ISO-2022-JP') // This should be now handled in imap_utf7_local?
162 $what = mb_convert_encoding($what, 'JIS', 'auto');
163 //if (ereg("[\"\\\r\n\x80-\xff]", $what))
164 if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
165 return '{' . strlen($what) . "}\r\n" . $what; // 4.3 literal form
166 return '"' . $what . '"'; // 4.3 quoted string form
170 * Parses a user date string into an rfc2060 date string
171 * (<day number>-<US month TLA>-<4 digit year>).
172 * Returns a preg_match-style array: [0]: fully formatted date,
173 * [1]: day, [2]: month, [3]: year
174 * Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
176 function sqimap_asearch_parse_date($what)
178 global $imap_asearch_months;
181 $what = ereg_replace('[ /\\.,]+', '-', $what);
183 preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
184 if (count($what_parts) == 4) {
185 $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
186 /* if (!in_array($what_month, $imap_asearch_months)) {*/
187 foreach ($imap_asearch_months as $month_number => $month_code) {
188 if (($what_month == $month_number)
189 ||
($what_month == $month_code)
190 ||
($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
191 ||
($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
193 $what_parts[2] = $month_number;
194 $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
202 $what_parts = array();
206 function sqimap_asearch_build_criteria($opcode, $what, $charset)
208 global $imap_asearch_opcodes;
211 switch ($imap_asearch_opcodes[$opcode]) {
214 /* $what = str_replace(' ', '', $what);*/
215 $what = ereg_replace('[^0-9]+', '', $what);
217 $criteria = $opcode . ' ' . $what . ' ';
220 $criteria = $opcode . ' ';
222 case 'afield': /* HEADER field-name: field-body */
223 preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
224 if (count($what_parts) == 3)
225 $criteria = $opcode . ' ' .
226 sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
227 sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
230 $what_parts = sqimap_asearch_parse_date($what);
231 if (isset($what_parts[0]))
232 $criteria = $opcode . ' ' . $what_parts[0] . ' ';
236 $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
239 $what = ereg_replace('[^0-9:\(\)]+', '', $what);
241 $criteria = $opcode . ' ' . $what . ' ';
247 function sqimap_run_search($imapConnection, $search_string, $search_charset)
251 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
252 if ($search_charset != '')
253 $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
255 $query = 'SEARCH ALL ' . $search_string;
256 s_debug_dump('C:', $query);
257 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
259 /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
260 if (($search_charset != '') && (strtoupper($response) == 'NO')) {
261 $query = 'SEARCH CHARSET US-ASCII ALL ' . $search_string;
262 s_debug_dump('C:', $query);
263 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
265 if (strtoupper($response) != 'OK') {
266 sqimap_asearch_error_box($response, $query, $message);
272 /* Keep going till we find the SEARCH response */
273 foreach ($readin as $readin_part) {
274 s_debug_dump('S:', $readin_part);
275 /* Check to see if a SEARCH response was received */
276 if (substr($readin_part, 0, 9) == '* SEARCH ') {
277 $messagelist = preg_split("/ /", substr($readin_part, 9));
278 break; // Should be the last anyway
282 $errors = $errors . $readin_part;
284 $errors = $readin_part;
288 /* If nothing is found * SEARCH should be the first error else echo errors */
289 /*if (isset($errors)) {
290 if (strstr($errors,'* SEARCH'))
292 echo '<!-- ' . htmlspecialchars($errors) . ' -->';
295 if (empty($messagelist)) //Empty search response, ie '* SEARCH'
298 $cnt = count($messagelist);
299 for ($q = 0; $q < $cnt; $q++
)
300 $id[$q] = trim($messagelist[$q]);
304 function sqimap_asearch_get_charset()
306 global $allow_charset_search, $languages, $squirrelmail_language;
308 if ($allow_charset_search)
309 return $languages[$squirrelmail_language]['CHARSET'];
313 /* replaces $mbox_msgs[$search_mailbox] = array_values(array_unique(array_merge($mbox_msgs[$search_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset))));*/
314 function sqimap_array_merge_unique($to, $from)
318 for ($i=0; $i<count($from); $i++
) {
319 if (!in_array($from[$i], $to))
325 function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $mboxes_array)
327 $search_charset = sqimap_asearch_get_charset();
328 $mbox_msgs = array();
330 $cur_mailbox = $mailbox_array[0];
331 $cur_biop = ''; /* Start with ALL */
332 /* We loop one more time than the real array count, so the last search gets fired */
333 for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++
) {
334 if (empty($exclude_array[$cur_crit])) {
335 $next_mailbox = $mailbox_array[$cur_crit];
336 if ($next_mailbox != $cur_mailbox) {
337 $search_string = trim($search_string); /* Trim out last space */
338 if (($cur_mailbox == 'All Folders') && (!empty($mboxes_array)))
339 $search_mboxes = $mboxes_array;
341 $search_mboxes = array($cur_mailbox);
342 foreach ($search_mboxes as $cur_mailbox) {
343 s_debug_dump('C:SELECT:', $cur_mailbox);
344 sqimap_mailbox_select($imapConnection, $cur_mailbox);
345 if (isset($mbox_msgs[$cur_mailbox])) {
346 if ($cur_biop == 'OR') /* Merge with previous results */
347 $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset));
348 else /* Intersect previous results */
349 $mbox_msgs[$cur_mailbox] = array_values(array_intersect(sqimap_run_search($imapConnection, $search_string, $search_charset), $mbox_msgs[$cur_mailbox]));
351 else /* No previous results */
352 $mbox_msgs[$cur_mailbox] = sqimap_run_search($imapConnection, $search_string, $search_charset);
353 if (empty($mbox_msgs[$cur_mailbox])) /* Can happen with intersect, and we need at the end a contiguous array */
354 unset($mbox_msgs[$cur_mailbox]);
356 $cur_mailbox = $next_mailbox;
359 if (isset($where_array[$cur_crit])) {
360 $criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset);
361 if (!empty($criteria)) {
362 $unop = $unop_array[$cur_crit];
364 $criteria = $unop . ' ' . $criteria;
365 /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
367 for ($next_crit = $cur_crit+
1; $next_crit <= count($where_array); $next_crit++
) {
368 if (empty($exclude_array[$next_crit])) {
369 if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox)
370 $next_biop = asearch_nz($biop_array[$next_crit]);
374 if ($next_biop == 'OR')
375 $criteria = $next_biop . ' ' . $criteria;
376 $search_string .= $criteria;
377 $cur_biop = asearch_nz($biop_array[$cur_crit]);