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