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