Removed the last code dependency on a specific version
[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 require_once(SM_PATH . 'functions/display_messages.php');
96 $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
97 if ($query != '')
98 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
99 if ($message_title != '')
100 $string .= $message_title;
101 if ($message != '')
102 $string .= htmlspecialchars($message);
103 $string .= "</font><br>\n";
104 error_box($string,$color);
105 }
106 }
107
108 /* This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc! */
109 function asearch_nz(&$var)
110 {
111 if (isset($var))
112 return $var;
113 return '';
114 }
115
116 /* This should give the same results as PHP 4 >= 4.3.0's html_entity_decode(), except it doesn't handle hex constructs */
117 function asearch_unhtmlentities($string) {
118 $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES));
119 for ($i=127; $i<255; $i++) /* Add &#<dec>; entities */
120 $trans_tbl['&#' . $i . ';'] = chr($i);
121 return strtr($string, $trans_tbl);
122 /* I think the one above is quicker, though it should be benchmarked
123 $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
124 return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
125 */
126 }
127
128 function s_debug_dump($var_name, $var_var)
129 {
130 global $imap_asearch_debug_dump;
131 if ($imap_asearch_debug_dump) {
132 if (function_exists('sm_print_r')) //Only exists since 1.4.2
133 sm_print_r($var_name, $var_var); //Better be the 'varargs' version ;)
134 else {
135 echo '<pre>';
136 echo htmlentities($var_name);
137 print_r($var_var);
138 echo '</pre>';
139 }
140 }
141 }
142
143 /*
144 4.3 String:
145 A quoted string is a sequence of zero or more 7-bit characters,
146 excluding CR and LF, with double quote (<">) characters at each end.
147 9. Formal Syntax:
148 quoted-specials = DQUOTE / "\"
149 */
150 function sqimap_asearch_encode_string($what, $charset)
151 {
152 if (strtoupper($charset) == 'ISO-2022-JP') // This should be now handled in imap_utf7_local?
153 $what = mb_convert_encoding($what, 'JIS', 'auto');
154 //if (ereg("[\"\\\r\n\x80-\xff]", $what))
155 if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
156 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
157 return '"' . $what . '"'; /* 4.3 quoted string form */
158 }
159
160 /*
161 Parses a user date string into an rfc2060 date string (<day number>-<US month TLA>-<4 digit year>)
162 Returns a preg_match-style array: [0]: fully formatted date, [1]: day, [2]: month, [3]: year
163 Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
164 */
165 function sqimap_asearch_parse_date($what)
166 {
167 global $imap_asearch_months;
168
169 $what = trim($what);
170 $what = ereg_replace('[ /\\.,]+', '-', $what);
171 if ($what) {
172 preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
173 if (count($what_parts) == 4) {
174 $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
175 /* if (!in_array($what_month, $imap_asearch_months)) {*/
176 foreach ($imap_asearch_months as $month_number => $month_code) {
177 if (($what_month == $month_number)
178 || ($what_month == $month_code)
179 || ($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
180 || ($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
181 ) {
182 $what_parts[2] = $month_number;
183 $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
184 break;
185 }
186 }
187 /* }*/
188 }
189 }
190 else
191 $what_parts = array();
192 return $what_parts;
193 }
194
195 function sqimap_asearch_build_criteria($opcode, $what, $charset)
196 {
197 global $imap_asearch_opcodes;
198
199 $criteria = '';
200 switch ($imap_asearch_opcodes[$opcode]) {
201 default:
202 case 'anum':
203 /* $what = str_replace(' ', '', $what);*/
204 $what = ereg_replace('[^0-9]+', '', $what);
205 if ($what != '')
206 $criteria = $opcode . ' ' . $what . ' ';
207 break;
208 case '': /* aflag */
209 $criteria = $opcode . ' ';
210 break;
211 case 'afield': /* HEADER field-name: field-body */
212 preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
213 if (count($what_parts) == 3)
214 $criteria = $opcode . ' ' .
215 sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
216 sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
217 break;
218 case 'adate':
219 $what_parts = sqimap_asearch_parse_date($what);
220 if (isset($what_parts[0]))
221 $criteria = $opcode . ' ' . $what_parts[0] . ' ';
222 break;
223 case 'akeyword':
224 case 'astring':
225 $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
226 break;
227 case 'asequence':
228 $what = ereg_replace('[^0-9:\(\)]+', '', $what);
229 if ($what != '')
230 $criteria = $opcode . ' ' . $what . ' ';
231 break;
232 }
233 return $criteria;
234 }
235
236 function sqimap_run_search($imapConnection, $search_string, $search_charset)
237 {
238 global $uid_support;
239
240 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
241 if ($search_charset != '')
242 $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
243 else
244 $query = 'SEARCH ALL ' . $search_string;
245 s_debug_dump('C:', $query);
246 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
247
248 /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
249 if (($search_charset != '') && (strtoupper($response) == 'NO')) {
250 $query = 'SEARCH CHARSET US-ASCII ALL ' . $search_string;
251 s_debug_dump('C:', $query);
252 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
253 }
254 if (strtoupper($response) != 'OK') {
255 sqimap_asearch_error_box($response, $query, $message);
256 return array();
257 }
258
259 unset($messagelist);
260
261 /* Keep going till we find the SEARCH response */
262 foreach ($readin as $readin_part) {
263 s_debug_dump('S:', $readin_part);
264 /* Check to see if a SEARCH response was received */
265 if (substr($readin_part, 0, 9) == '* SEARCH ') {
266 $messagelist = preg_split("/ /", substr($readin_part, 9));
267 break; // Should be the last anyway
268 }
269 /* else {
270 if (isset($errors))
271 $errors = $errors . $readin_part;
272 else
273 $errors = $readin_part;
274 }*/
275 }
276
277 /* If nothing is found * SEARCH should be the first error else echo errors */
278 /*if (isset($errors)) {
279 if (strstr($errors,'* SEARCH'))
280 return array();
281 echo '<!-- ' . htmlspecialchars($errors) . ' -->';
282 }*/
283
284 if (empty($messagelist)) //Empty search response, ie '* SEARCH'
285 return array();
286
287 $cnt = count($messagelist);
288 for ($q = 0; $q < $cnt; $q++)
289 $id[$q] = trim($messagelist[$q]);
290 return $id;
291 }
292
293 function sqimap_asearch_get_charset()
294 {
295 global $allow_charset_search, $languages, $squirrelmail_language;
296
297 if ($allow_charset_search)
298 return $languages[$squirrelmail_language]['CHARSET'];
299 return '';
300 }
301
302 /* replaces $mbox_msgs[$search_mailbox] = array_values(array_unique(array_merge($mbox_msgs[$search_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset))));*/
303 function sqimap_array_merge_unique($to, $from)
304 {
305 if (empty($to))
306 return $from;
307 for ($i=0; $i<count($from); $i++) {
308 if (!in_array($from[$i], $to))
309 $to[] = $from[$i];
310 }
311 return $to;
312 }
313
314 function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $mboxes_array)
315 {
316 $search_charset = sqimap_asearch_get_charset();
317 $mbox_msgs = array();
318 $search_string = '';
319 $cur_mailbox = $mailbox_array[0];
320 $cur_biop = ''; /* Start with ALL */
321 /* We loop one more time than the real array count, so the last search gets fired */
322 for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++) {
323 if (empty($exclude_array[$cur_crit])) {
324 $next_mailbox = $mailbox_array[$cur_crit];
325 if ($next_mailbox != $cur_mailbox) {
326 $search_string = trim($search_string); /* Trim out last space */
327 if (($cur_mailbox == 'All Folders') && (!empty($mboxes_array)))
328 $search_mboxes = $mboxes_array;
329 else
330 $search_mboxes = array($cur_mailbox);
331 foreach ($search_mboxes as $cur_mailbox) {
332 s_debug_dump('C:SELECT:', $cur_mailbox);
333 sqimap_mailbox_select($imapConnection, $cur_mailbox);
334 if (isset($mbox_msgs[$cur_mailbox])) {
335 if ($cur_biop == 'OR') /* Merge with previous results */
336 $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset));
337 else /* Intersect previous results */
338 $mbox_msgs[$cur_mailbox] = array_values(array_intersect(sqimap_run_search($imapConnection, $search_string, $search_charset), $mbox_msgs[$cur_mailbox]));
339 }
340 else /* No previous results */
341 $mbox_msgs[$cur_mailbox] = sqimap_run_search($imapConnection, $search_string, $search_charset);
342 if (empty($mbox_msgs[$cur_mailbox])) /* Can happen with intersect, and we need at the end a contiguous array */
343 unset($mbox_msgs[$cur_mailbox]);
344 }
345 $cur_mailbox = $next_mailbox;
346 $search_string = '';
347 }
348 if (isset($where_array[$cur_crit])) {
349 $criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset);
350 if (!empty($criteria)) {
351 $unop = $unop_array[$cur_crit];
352 if (!empty($unop))
353 $criteria = $unop . ' ' . $criteria;
354 /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
355 $next_biop = '';
356 for ($next_crit = $cur_crit+1; $next_crit <= count($where_array); $next_crit++) {
357 if (empty($exclude_array[$next_crit])) {
358 if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox)
359 $next_biop = asearch_nz($biop_array[$next_crit]);
360 break;
361 }
362 }
363 if ($next_biop == 'OR')
364 $criteria = $next_biop . ' ' . $criteria;
365 $search_string .= $criteria;
366 $cur_biop = asearch_nz($biop_array[$cur_crit]);
367 }
368 }
369 }
370 }
371 return $mbox_msgs;
372 }
373
374 ?>