Bring my last changes into synch with code conventions in this file
[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.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 /* This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc! */
76 function asearch_nz(&$var)
77 {
78 if (isset($var))
79 return $var;
80 return '';
81 }
82
83 /* This should give the same results as PHP 4 >= 4.3.0's html_entity_decode() */
84 function asearch_unhtmlentities($string) {
85 $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES));
86 for ($i=127; $i<255; $i++) /* Add &#<dec>; entities */
87 $trans_tbl['&#' . $i . ';'] = chr($i);
88 return strtr($string, $trans_tbl);
89 /* I think the one above is quicker, though it should be benchmarked
90 $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
91 return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
92 */
93 }
94
95 function s_dump($var_name, $var_var, $compact = FALSE)
96 {
97 if (!$compact)
98 echo '<PRE>';
99 echo htmlentities($var_name) . '=';
100 print_r($var_var);
101 if ($compact)
102 echo "<BR>\n";
103 else
104 echo "</PRE>\n";
105 }
106
107 function s_debug_dump($var_name, $var_var, $compact = FALSE)
108 {
109 global $imap_asearch_debug_dump;
110 if ($imap_asearch_debug_dump)
111 s_dump($var_name, $var_var, $compact);
112 }
113
114 function sqimap_asearch_encode_string($what, $search_charset)
115 {
116 if (strtoupper($search_charset) == 'ISO-2022-JP')
117 $what = mb_convert_encoding($what, 'JIS', 'auto');
118 if (strpos($what,'"') > -1)
119 return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
120 return '"' . $what . '"'; /* 4.3 quoted string form */
121 }
122
123 /*
124 Parses a user date string into an rfc2060 date string (<day number>-<US month TLA>-<4 digit year>)
125 Returns a preg_match-style array: [0]: fully formatted date, [1]: day, [2]: month, [3]: year
126 Handles space, slash, dot and comma as separators (and dash of course ;=)
127 */
128 function sqimap_asearch_parse_date($what)
129 {
130 global $imap_asearch_months;
131
132 $what = trim($what);
133 $what = ereg_replace('[ :,:/:.]+', '-', $what);
134 if ($what) {
135 preg_match('/^([0-9]+)-([^\-]+)-([0-9]+)$/', $what, $what_parts);
136 if (count($what_parts) == 4) {
137 $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
138 /* if (!in_array($what_month, $imap_asearch_months)) {*/
139 foreach ($imap_asearch_months as $month_number => $month_code) {
140 if (($what_month == $month_number)
141 || ($what_month == $month_code)
142 || ($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
143 || ($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
144 ) {
145 $what_parts[2] = $month_number;
146 $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
147 break;
148 }
149 }
150 /* }*/
151 }
152 }
153 else
154 $what_parts = array();
155 return $what_parts;
156 }
157
158 function sqimap_asearch_build_criteria($opcode, $what, $search_charset)
159 {
160 global $imap_asearch_opcodes;
161
162 switch ($imap_asearch_opcodes[$opcode]) {
163 default:
164 case 'anum':
165 /* $what = str_replace(' ', '', $what);*/
166 $what = ereg_replace('[^0-9]+', '', $what);
167 if ($what != '')
168 $criteria = $opcode . ' ' . $what . ' ';
169 break;
170 case '': /* aflag */
171 $criteria = $opcode . ' ';
172 break;
173 case 'afield': /* HEADER field-name: field-body */
174 preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
175 if (count($what_parts) == 3)
176 $criteria = $opcode . ' ' .
177 sqimap_asearch_encode_string($what_parts[1], $search_charset) . ' ' .
178 sqimap_asearch_encode_string($what_parts[2], $search_charset) . ' ';
179 break;
180 case 'adate':
181 $what_parts = sqimap_asearch_parse_date($what);
182 if ($what_parts[0] != '')
183 $criteria = $opcode . ' ' . $what_parts[0] . ' ';
184 break;
185 case 'akeyword':
186 case 'astring':
187 $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $search_charset) . ' ';
188 break;
189 case 'asequence':
190 $what = ereg_replace('[^0-9:\(\)]+', '', $what);
191 if ($what != '')
192 $criteria = $opcode . ' ' . $what . ' ';
193 break;
194 }
195 return $criteria;
196 }
197
198 function sqimap_run_search($imapConnection, $search_string, $search_charset)
199 {
200 global $allow_charset_search, $uid_support;
201
202 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
203 if ($allow_charset_search && (!empty($search_charset)))
204 $ss = 'SEARCH CHARSET ' . strtoupper($search_charset) . ' ALL ' . $search_string;
205 else
206 $ss = 'SEARCH ALL ' . $search_string;
207 s_debug_dump('O', $ss);
208
209 /* read data back from IMAP */
210 $readin = sqimap_run_command($imapConnection, $ss, false, $result, $message, $uid_support);
211
212 /* 6.4.4 try US-ASCII charset if we receive a tagged NO response */
213 if (!empty($charset) && strtolower($result) == 'no') {
214 $ss = 'SEARCH CHARSET "US-ASCII" ALL ' . $search_string;
215 s_debug_dump('O', $ss);
216 $readin = sqimap_run_command ($imapConnection, $ss, true, $result, $message); /* no $uid_support? */
217 }
218
219 unset($messagelist);
220
221 /* Keep going till we find the SEARCH response */
222 foreach ($readin as $readin_part) {
223 s_debug_dump('I', $readin_part);
224 /* Check to see if a SEARCH response was received */
225 if (substr($readin_part, 0, 9) == '* SEARCH ') {
226 $messagelist = preg_split("/ /", substr($readin_part, 9));
227 } else if (isset($errors)) {
228 $errors = $errors . $readin_part;
229 } else {
230 $errors = $readin_part;
231 }
232 }
233
234 /* If nothing is found * SEARCH should be the first error else echo errors */
235 if (isset($errors)) {
236 if (strstr($errors,'* SEARCH'))
237 return array();
238 echo '<!-- ' . htmlspecialchars($errors) . ' -->';
239 }
240
241 if (empty($messagelist))
242 return array();
243
244 $cnt = count($messagelist);
245 for ($q = 0; $q < $cnt; $q++)
246 $id[$q] = trim($messagelist[$q]);
247 return $id;
248 }
249
250 /* replaces $mbox_msgs[$search_mailbox] = array_values(array_unique(array_merge($mbox_msgs[$search_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset))));*/
251 function sqimap_array_merge_unique($to, $from)
252 {
253 if (empty($to))
254 return $from;
255 for ($i=0; $i<count($from); $i++) {
256 if (!in_array($from[$i], $to))
257 $to[] = $from[$i];
258 }
259 return $to;
260 }
261
262 function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $mboxes_array)
263 {
264 global $languages, $squirrelmail_language;
265
266 /* ??? what are those for ?? */
267 /* $pos = $search_position;*/
268
269 $mbox_msgs = array();
270 $search_charset = $languages[$squirrelmail_language]['CHARSET'];
271 $search_string = '';
272 $cur_mailbox = $mailbox_array[0];
273 $cur_biop = ''; /* Start with ALL */
274 /* We loop one more time than the real array count, so the last search gets fired */
275 for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++) {
276 if (empty($exclude_array[$cur_crit])) {
277 $next_mailbox = $mailbox_array[$cur_crit];
278 if ($next_mailbox != $cur_mailbox) {
279 $search_string = trim($search_string); /* Trim out last space */
280 if (($cur_mailbox == 'All Folders') && (!empty($mboxes_array)))
281 $search_mboxes = $mboxes_array;
282 else
283 $search_mboxes = array($cur_mailbox);
284 foreach ($search_mboxes as $cur_mailbox) {
285 sqimap_mailbox_select($imapConnection, $cur_mailbox);
286 s_debug_dump('SELECT',$cur_mailbox);
287 if (isset($mbox_msgs[$cur_mailbox])) {
288 if ($cur_biop == 'OR') /* Merge with previous results */
289 $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset));
290 else /* Intersect previous results */
291 $mbox_msgs[$cur_mailbox] = array_values(array_intersect(sqimap_run_search($imapConnection, $search_string, $search_charset), $mbox_msgs[$cur_mailbox]));
292 }
293 else /* No previous results */
294 $mbox_msgs[$cur_mailbox] = sqimap_run_search($imapConnection, $search_string, $search_charset);
295 if (empty($mbox_msgs[$cur_mailbox])) /* Can happen with intersect, and we need at the end a contiguous array */
296 unset($mbox_msgs[$cur_mailbox]);
297 }
298 $cur_mailbox = $next_mailbox;
299 $search_string = '';
300 }
301 if (isset($where_array[$cur_crit])) {
302 $criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset);
303 if (!empty($criteria)) {
304 $unop = $unop_array[$cur_crit];
305 if (!empty($unop))
306 $criteria = $unop . ' ' . $criteria;
307 /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
308 $next_biop = '';
309 for ($next_crit = $cur_crit+1; $next_crit <= count($where_array); $next_crit++) {
310 if (empty($exclude_array[$next_crit])) {
311 if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox)
312 $next_biop = asearch_nz($biop_array[$next_crit]);
313 break;
314 }
315 }
316 if ($next_biop == 'OR')
317 $criteria = $next_biop . ' ' . $criteria;
318 $search_string .= $criteria;
319 $cur_biop = asearch_nz($biop_array[$cur_crit]);
320 }
321 }
322 }
323 }
324 return $mbox_msgs;
325 }
326
327 ?>