df6209ccadd79814971bf71115596b3304884754
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 $message_title = _("Reason Given: ");
92 if (function_exists('sqimap_error_box'))
93 sqimap_error_box($title, $query, $message_title, $message);
94 else { //Straight copy of 1.5 imap_general.php:sqimap_error_box(). Can be removed at a later time
96 require_once(SM_PATH
. 'functions/display_messages.php');
97 $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
99 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
100 if ($message_title != '')
101 $string .= $message_title;
103 $string .= htmlspecialchars($message);
104 $string .= "</font><br>\n";
105 error_box($string,$color);
109 /* This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc! */
110 function asearch_nz(&$var)
117 /* This should give the same results as PHP 4 >= 4.3.0's html_entity_decode(), except it doesn't handle hex constructs */
118 function asearch_unhtmlentities($string) {
119 $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES
));
120 for ($i=127; $i<255; $i++
) /* Add &#<dec>; entities */
121 $trans_tbl['&#' . $i . ';'] = chr($i);
122 return strtr($string, $trans_tbl);
123 /* I think the one above is quicker, though it should be benchmarked
124 $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
125 return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
129 function s_debug_dump($var_name, $var_var)
131 global $imap_asearch_debug_dump;
132 if ($imap_asearch_debug_dump) {
133 if (function_exists('sm_print_r')) //Only exists since 1.4.2
134 sm_print_r($var_name, $var_var); //Better be the 'varargs' version ;)
137 echo htmlentities($var_name);
146 A quoted string is a sequence of zero or more 7-bit characters,
147 excluding CR and LF, with double quote (<">) characters at each end.
149 quoted-specials = DQUOTE / "\"
151 function sqimap_asearch_encode_string($what, $charset)
153 if (strtoupper($charset) == 'ISO-2022-JP') // This should be now handled in imap_utf7_local?
154 $what = mb_convert_encoding($what, 'JIS', 'auto');
155 //if (ereg("[\"\\\r\n\x80-\xff]", $what))
156 if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
157 return '{' . strlen($what) . "}\r\n" . $what; // 4.3 literal form
158 return '"' . $what . '"'; // 4.3 quoted string form
162 Parses a user date string into an rfc2060 date string (<day number>-<US month TLA>-<4 digit year>)
163 Returns a preg_match-style array: [0]: fully formatted date, [1]: day, [2]: month, [3]: year
164 Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
166 function sqimap_asearch_parse_date($what)
168 global $imap_asearch_months;
171 $what = ereg_replace('[ /\\.,]+', '-', $what);
173 preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
174 if (count($what_parts) == 4) {
175 $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
176 /* if (!in_array($what_month, $imap_asearch_months)) {*/
177 foreach ($imap_asearch_months as $month_number => $month_code) {
178 if (($what_month == $month_number)
179 ||
($what_month == $month_code)
180 ||
($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
181 ||
($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
183 $what_parts[2] = $month_number;
184 $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
192 $what_parts = array();
196 function sqimap_asearch_build_criteria($opcode, $what, $charset)
198 global $imap_asearch_opcodes;
201 switch ($imap_asearch_opcodes[$opcode]) {
204 /* $what = str_replace(' ', '', $what);*/
205 $what = ereg_replace('[^0-9]+', '', $what);
207 $criteria = $opcode . ' ' . $what . ' ';
210 $criteria = $opcode . ' ';
212 case 'afield': /* HEADER field-name: field-body */
213 preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
214 if (count($what_parts) == 3)
215 $criteria = $opcode . ' ' .
216 sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
217 sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
220 $what_parts = sqimap_asearch_parse_date($what);
221 if (isset($what_parts[0]))
222 $criteria = $opcode . ' ' . $what_parts[0] . ' ';
226 $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
229 $what = ereg_replace('[^0-9:\(\)]+', '', $what);
231 $criteria = $opcode . ' ' . $what . ' ';
237 function sqimap_run_search($imapConnection, $search_string, $search_charset)
241 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
242 if ($search_charset != '')
243 $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
245 $query = 'SEARCH ALL ' . $search_string;
246 s_debug_dump('C:', $query);
247 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
249 /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
250 if (($search_charset != '') && (strtoupper($response) == 'NO')) {
251 $query = 'SEARCH CHARSET US-ASCII ALL ' . $search_string;
252 s_debug_dump('C:', $query);
253 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
255 if (strtoupper($response) != 'OK') {
256 sqimap_asearch_error_box($response, $query, $message);
262 /* Keep going till we find the SEARCH response */
263 foreach ($readin as $readin_part) {
264 s_debug_dump('S:', $readin_part);
265 /* Check to see if a SEARCH response was received */
266 if (substr($readin_part, 0, 9) == '* SEARCH ') {
267 $messagelist = preg_split("/ /", substr($readin_part, 9));
268 break; // Should be the last anyway
272 $errors = $errors . $readin_part;
274 $errors = $readin_part;
278 /* If nothing is found * SEARCH should be the first error else echo errors */
279 /*if (isset($errors)) {
280 if (strstr($errors,'* SEARCH'))
282 echo '<!-- ' . htmlspecialchars($errors) . ' -->';
285 if (empty($messagelist)) //Empty search response, ie '* SEARCH'
288 $cnt = count($messagelist);
289 for ($q = 0; $q < $cnt; $q++
)
290 $id[$q] = trim($messagelist[$q]);
294 function sqimap_asearch_get_charset()
296 global $allow_charset_search, $languages, $squirrelmail_language;
298 if ($allow_charset_search)
299 return $languages[$squirrelmail_language]['CHARSET'];
303 /* replaces $mbox_msgs[$search_mailbox] = array_values(array_unique(array_merge($mbox_msgs[$search_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset))));*/
304 function sqimap_array_merge_unique($to, $from)
308 for ($i=0; $i<count($from); $i++
) {
309 if (!in_array($from[$i], $to))
315 function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $mboxes_array)
317 $search_charset = sqimap_asearch_get_charset();
318 $mbox_msgs = array();
320 $cur_mailbox = $mailbox_array[0];
321 $cur_biop = ''; /* Start with ALL */
322 /* We loop one more time than the real array count, so the last search gets fired */
323 for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++
) {
324 if (empty($exclude_array[$cur_crit])) {
325 $next_mailbox = $mailbox_array[$cur_crit];
326 if ($next_mailbox != $cur_mailbox) {
327 $search_string = trim($search_string); /* Trim out last space */
328 if (($cur_mailbox == 'All Folders') && (!empty($mboxes_array)))
329 $search_mboxes = $mboxes_array;
331 $search_mboxes = array($cur_mailbox);
332 foreach ($search_mboxes as $cur_mailbox) {
333 s_debug_dump('C:SELECT:', $cur_mailbox);
334 sqimap_mailbox_select($imapConnection, $cur_mailbox);
335 if (isset($mbox_msgs[$cur_mailbox])) {
336 if ($cur_biop == 'OR') /* Merge with previous results */
337 $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset));
338 else /* Intersect previous results */
339 $mbox_msgs[$cur_mailbox] = array_values(array_intersect(sqimap_run_search($imapConnection, $search_string, $search_charset), $mbox_msgs[$cur_mailbox]));
341 else /* No previous results */
342 $mbox_msgs[$cur_mailbox] = sqimap_run_search($imapConnection, $search_string, $search_charset);
343 if (empty($mbox_msgs[$cur_mailbox])) /* Can happen with intersect, and we need at the end a contiguous array */
344 unset($mbox_msgs[$cur_mailbox]);
346 $cur_mailbox = $next_mailbox;
349 if (isset($where_array[$cur_crit])) {
350 $criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset);
351 if (!empty($criteria)) {
352 $unop = $unop_array[$cur_crit];
354 $criteria = $unop . ' ' . $criteria;
355 /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
357 for ($next_crit = $cur_crit+
1; $next_crit <= count($where_array); $next_crit++
) {
358 if (empty($exclude_array[$next_crit])) {
359 if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox)
360 $next_biop = asearch_nz($biop_array[$next_crit]);
364 if ($next_biop == 'OR')
365 $criteria = $next_biop . ' ' . $criteria;
366 $search_string .= $criteria;
367 $cur_biop = asearch_nz($biop_array[$cur_crit]);