d2555578a603a25aa1a83584994bba773a2b5d80
[squirrelmail.git] / functions / imap_asearch.php
1 <?php
2
3 /**
4 * imap_search.php
5 *
6 * Copyright (c) 1999-2003 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * IMAP asearch routines
10 * @author Alex Lemaresquier - Brainstorm - alex at brainstorm.fr
11 * See README file for infos.
12 * @package squirrelmail
13 *
14 */
15
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');
19
20 /** Set to TRUE to dump the imap dialogue */
21 $imap_asearch_debug_dump = FALSE;
22
23 $imap_asearch_opcodes = array(
24 /* <message set> => 'asequence', */
25 /*'ALL' is binary operator */
26 'ANSWERED' => '',
27 'BCC' => 'astring',
28 'BEFORE' => 'adate',
29 'BODY' => 'astring',
30 'CC' => 'astring',
31 'DELETED' => '',
32 'DRAFT' => '',
33 'FLAGGED' => '',
34 'FROM' => 'astring',
35 'HEADER' => 'afield', /* Special syntax for this one, see below */
36 'KEYWORD' => 'akeyword',
37 'LARGER' => 'anum',
38 'NEW' => '',
39 /*'NOT' is unary operator */
40 'OLD' => '',
41 'ON' => 'adate',
42 /*'OR' is binary operator */
43 'RECENT' => '',
44 'SEEN' => '',
45 'SENTBEFORE' => 'adate',
46 'SENTON' => 'adate',
47 'SENTSINCE' => 'adate',
48 'SINCE' => 'adate',
49 'SMALLER' => 'anum',
50 'SUBJECT' => 'astring',
51 'TEXT' => 'astring',
52 'TO' => 'astring',
53 'UID' => 'asequence',
54 'UNANSWERED' => '',
55 'UNDELETED' => '',
56 'UNDRAFT' => '',
57 'UNFLAGGED' => '',
58 'UNKEYWORD' => 'akeyword',
59 'UNSEEN' => ''
60 );
61
62 $imap_asearch_months = array(
63 '01' => 'jan',
64 '02' => 'feb',
65 '03' => 'mar',
66 '04' => 'apr',
67 '05' => 'may',
68 '06' => 'jun',
69 '07' => 'jul',
70 '08' => 'aug',
71 '09' => 'sep',
72 '10' => 'oct',
73 '11' => 'nov',
74 '12' => 'dec'
75 );
76
77 $imap_error_titles = array(
78 'OK' => '',
79 'NO' => _("ERROR : Could not complete request."),
80 'BAD' => _("ERROR : Bad or malformed request."),
81 'BYE' => _("ERROR : Imap server closed the connection.")
82 );
83
84 // why can't this just use sqimap_error_box() ?
85 function sqimap_asearch_error_box($response, $query, $message)
86 {
87 global $imap_error_titles;
88
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.");
92 else
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
98 global $color;
99 require_once(SM_PATH . 'functions/display_messages.php');
100 $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
101 if ($query != '')
102 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
103 if ($message_title != '')
104 $string .= $message_title;
105 if ($message != '')
106 $string .= htmlspecialchars($message);
107 $string .= "</font><br>\n";
108 error_box($string,$color);
109 }
110 }
111
112 /**
113 * This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc!
114 */
115 function asearch_nz(&$var)
116 {
117 if (isset($var))
118 return $var;
119 return '';
120 }
121
122 /**
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
125 */
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);
134 */
135 }
136
137 function s_debug_dump($var_name, $var_var)
138 {
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 ;)
143 else {
144 echo '<pre>';
145 echo htmlentities($var_name);
146 print_r($var_var);
147 echo '</pre>';
148 }
149 }
150 }
151
152 /*
153 4.3 String:
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.
156 9. Formal Syntax:
157 quoted-specials = DQUOTE / "\"
158 */
159 function sqimap_asearch_encode_string($what, $charset)
160 {
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
167 }
168
169 /**
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 ;=)
175 */
176 function sqimap_asearch_parse_date($what)
177 {
178 global $imap_asearch_months;
179
180 $what = trim($what);
181 $what = ereg_replace('[ /\\.,]+', '-', $what);
182 if ($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))))
192 ) {
193 $what_parts[2] = $month_number;
194 $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
195 break;
196 }
197 }
198 /* }*/
199 }
200 }
201 else
202 $what_parts = array();
203 return $what_parts;
204 }
205
206 function sqimap_asearch_build_criteria($opcode, $what, $charset)
207 {
208 global $imap_asearch_opcodes;
209
210 $criteria = '';
211 switch ($imap_asearch_opcodes[$opcode]) {
212 default:
213 case 'anum':
214 /* $what = str_replace(' ', '', $what);*/
215 $what = ereg_replace('[^0-9]+', '', $what);
216 if ($what != '')
217 $criteria = $opcode . ' ' . $what . ' ';
218 break;
219 case '': /* aflag */
220 $criteria = $opcode . ' ';
221 break;
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) . ' ';
228 break;
229 case 'adate':
230 $what_parts = sqimap_asearch_parse_date($what);
231 if (isset($what_parts[0]))
232 $criteria = $opcode . ' ' . $what_parts[0] . ' ';
233 break;
234 case 'akeyword':
235 case 'astring':
236 $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
237 break;
238 case 'asequence':
239 $what = ereg_replace('[^0-9:\(\)]+', '', $what);
240 if ($what != '')
241 $criteria = $opcode . ' ' . $what . ' ';
242 break;
243 }
244 return $criteria;
245 }
246
247 function sqimap_run_search($imapConnection, $search_string, $search_charset)
248 {
249 global $uid_support;
250
251 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
252 if ($search_charset != '')
253 $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
254 else
255 $query = 'SEARCH ALL ' . $search_string;
256 s_debug_dump('C:', $query);
257 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
258
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);
264 }
265 if (strtoupper($response) != 'OK') {
266 sqimap_asearch_error_box($response, $query, $message);
267 return array();
268 }
269
270 unset($messagelist);
271
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
279 }
280 /* else {
281 if (isset($errors))
282 $errors = $errors . $readin_part;
283 else
284 $errors = $readin_part;
285 }*/
286 }
287
288 /* If nothing is found * SEARCH should be the first error else echo errors */
289 /*if (isset($errors)) {
290 if (strstr($errors,'* SEARCH'))
291 return array();
292 echo '<!-- ' . htmlspecialchars($errors) . ' -->';
293 }*/
294
295 if (empty($messagelist)) //Empty search response, ie '* SEARCH'
296 return array();
297
298 $cnt = count($messagelist);
299 for ($q = 0; $q < $cnt; $q++)
300 $id[$q] = trim($messagelist[$q]);
301 return $id;
302 }
303
304 function sqimap_asearch_get_charset()
305 {
306 global $allow_charset_search, $languages, $squirrelmail_language;
307
308 if ($allow_charset_search)
309 return $languages[$squirrelmail_language]['CHARSET'];
310 return '';
311 }
312
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)
315 {
316 if (empty($to))
317 return $from;
318 for ($i=0; $i<count($from); $i++) {
319 if (!in_array($from[$i], $to))
320 $to[] = $from[$i];
321 }
322 return $to;
323 }
324
325 function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $mboxes_array)
326 {
327 $search_charset = sqimap_asearch_get_charset();
328 $mbox_msgs = array();
329 $search_string = '';
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;
340 else
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]));
350 }
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]);
355 }
356 $cur_mailbox = $next_mailbox;
357 $search_string = '';
358 }
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];
363 if (!empty($unop))
364 $criteria = $unop . ' ' . $criteria;
365 /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
366 $next_biop = '';
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]);
371 break;
372 }
373 }
374 if ($next_biop == 'OR')
375 $criteria = $next_biop . ' ' . $criteria;
376 $search_string .= $criteria;
377 $cur_biop = asearch_nz($biop_array[$cur_crit]);
378 }
379 }
380 }
381 }
382 return $mbox_msgs;
383 }
384
385 ?>