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