Today Cyrus 2.2.2-BETA with SASL Initial Client response was released so it
[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 * Alex Lemaresquier - Brainstorm - alex at brainstorm.fr
11 * See README file for infos.
12 *
13 */
14
15 require_once(SM_PATH . 'functions/imap_general.php');
16 require_once(SM_PATH . 'functions/date.php');
17
18 /* Set to TRUE to dump the imap dialogue */
19 $imap_asearch_debug_dump = FALSE;
20
21 $imap_asearch_opcodes = array(
22 /* <message set> => 'asequence', */
23 /*'ALL' is binary operator */
24 'ANSWERED' => '',
25 'BCC' => 'astring',
26 'BEFORE' => 'adate',
27 'BODY' => 'astring',
28 'CC' => 'astring',
29 'DELETED' => '',
30 'DRAFT' => '',
31 'FLAGGED' => '',
32 'FROM' => 'astring',
33 'HEADER' => 'afield', /* Special syntax for this one, see below */
34 'KEYWORD' => 'akeyword',
35 'LARGER' => 'anum',
36 'NEW' => '',
37 /*'NOT' is unary operator */
38 'OLD' => '',
39 'ON' => 'adate',
40 /*'OR' is binary operator */
41 'RECENT' => '',
42 'SEEN' => '',
43 'SENTBEFORE' => 'adate',
44 'SENTON' => 'adate',
45 'SENTSINCE' => 'adate',
46 'SINCE' => 'adate',
47 'SMALLER' => 'anum',
48 'SUBJECT' => 'astring',
49 'TEXT' => 'astring',
50 'TO' => 'astring',
51 'UID' => 'asequence',
52 'UNANSWERED' => '',
53 'UNDELETED' => '',
54 'UNDRAFT' => '',
55 'UNFLAGGED' => '',
56 'UNKEYWORD' => 'akeyword',
57 'UNSEEN' => ''
58 );
59
60 $imap_asearch_months = array(
61 '01' => 'jan',
62 '02' => 'feb',
63 '03' => 'mar',
64 '04' => 'apr',
65 '05' => 'may',
66 '06' => 'jun',
67 '07' => 'jul',
68 '08' => 'aug',
69 '09' => 'sep',
70 '10' => 'oct',
71 '11' => 'nov',
72 '12' => 'dec'
73 );
74
75 $imap_error_titles = array(
76 'OK' => '',
77 'NO' => _("ERROR : Could not complete request."),
78 'BAD' => _("ERROR : Bad or malformed request."),
79 'BYE' => _("ERROR : Imap server closed the connection.")
80 );
81
82 function sqimap_asearch_error_box($response, $query, $message)
83 {
84 global $imap_error_titles;
85
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.");
89 else
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
95 global $color;
96 require_once(SM_PATH . 'functions/display_messages.php');
97 $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
98 if ($query != '')
99 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
100 if ($message_title != '')
101 $string .= $message_title;
102 if ($message != '')
103 $string .= htmlspecialchars($message);
104 $string .= "</font><br>\n";
105 error_box($string,$color);
106 }
107 }
108
109 /* This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc! */
110 function asearch_nz(&$var)
111 {
112 if (isset($var))
113 return $var;
114 return '';
115 }
116
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);
126 */
127 }
128
129 function s_debug_dump($var_name, $var_var)
130 {
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 ;)
135 else {
136 echo '<pre>';
137 echo htmlentities($var_name);
138 print_r($var_var);
139 echo '</pre>';
140 }
141 }
142 }
143
144 /*
145 4.3 String:
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.
148 9. Formal Syntax:
149 quoted-specials = DQUOTE / "\"
150 */
151 function sqimap_asearch_encode_string($what, $charset)
152 {
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
159 }
160
161 /*
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 ;=)
165 */
166 function sqimap_asearch_parse_date($what)
167 {
168 global $imap_asearch_months;
169
170 $what = trim($what);
171 $what = ereg_replace('[ /\\.,]+', '-', $what);
172 if ($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))))
182 ) {
183 $what_parts[2] = $month_number;
184 $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
185 break;
186 }
187 }
188 /* }*/
189 }
190 }
191 else
192 $what_parts = array();
193 return $what_parts;
194 }
195
196 function sqimap_asearch_build_criteria($opcode, $what, $charset)
197 {
198 global $imap_asearch_opcodes;
199
200 $criteria = '';
201 switch ($imap_asearch_opcodes[$opcode]) {
202 default:
203 case 'anum':
204 /* $what = str_replace(' ', '', $what);*/
205 $what = ereg_replace('[^0-9]+', '', $what);
206 if ($what != '')
207 $criteria = $opcode . ' ' . $what . ' ';
208 break;
209 case '': /* aflag */
210 $criteria = $opcode . ' ';
211 break;
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) . ' ';
218 break;
219 case 'adate':
220 $what_parts = sqimap_asearch_parse_date($what);
221 if (isset($what_parts[0]))
222 $criteria = $opcode . ' ' . $what_parts[0] . ' ';
223 break;
224 case 'akeyword':
225 case 'astring':
226 $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
227 break;
228 case 'asequence':
229 $what = ereg_replace('[^0-9:\(\)]+', '', $what);
230 if ($what != '')
231 $criteria = $opcode . ' ' . $what . ' ';
232 break;
233 }
234 return $criteria;
235 }
236
237 function sqimap_run_search($imapConnection, $search_string, $search_charset)
238 {
239 global $uid_support;
240
241 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
242 if ($search_charset != '')
243 $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
244 else
245 $query = 'SEARCH ALL ' . $search_string;
246 s_debug_dump('C:', $query);
247 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
248
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);
254 }
255 if (strtoupper($response) != 'OK') {
256 sqimap_asearch_error_box($response, $query, $message);
257 return array();
258 }
259
260 unset($messagelist);
261
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
269 }
270 /* else {
271 if (isset($errors))
272 $errors = $errors . $readin_part;
273 else
274 $errors = $readin_part;
275 }*/
276 }
277
278 /* If nothing is found * SEARCH should be the first error else echo errors */
279 /*if (isset($errors)) {
280 if (strstr($errors,'* SEARCH'))
281 return array();
282 echo '<!-- ' . htmlspecialchars($errors) . ' -->';
283 }*/
284
285 if (empty($messagelist)) //Empty search response, ie '* SEARCH'
286 return array();
287
288 $cnt = count($messagelist);
289 for ($q = 0; $q < $cnt; $q++)
290 $id[$q] = trim($messagelist[$q]);
291 return $id;
292 }
293
294 function sqimap_asearch_get_charset()
295 {
296 global $allow_charset_search, $languages, $squirrelmail_language;
297
298 if ($allow_charset_search)
299 return $languages[$squirrelmail_language]['CHARSET'];
300 return '';
301 }
302
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)
305 {
306 if (empty($to))
307 return $from;
308 for ($i=0; $i<count($from); $i++) {
309 if (!in_array($from[$i], $to))
310 $to[] = $from[$i];
311 }
312 return $to;
313 }
314
315 function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $mboxes_array)
316 {
317 $search_charset = sqimap_asearch_get_charset();
318 $mbox_msgs = array();
319 $search_string = '';
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;
330 else
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]));
340 }
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]);
345 }
346 $cur_mailbox = $next_mailbox;
347 $search_string = '';
348 }
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];
353 if (!empty($unop))
354 $criteria = $unop . ' ' . $criteria;
355 /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
356 $next_biop = '';
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]);
361 break;
362 }
363 }
364 if ($next_biop == 'OR')
365 $criteria = $next_biop . ' ' . $criteria;
366 $search_string .= $criteria;
367 $cur_biop = asearch_nz($biop_array[$cur_crit]);
368 }
369 }
370 }
371 }
372 return $mbox_msgs;
373 }
374
375 ?>