Preparation to begin using phpdocumentor.
[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
d6c32258 10 * @author Alex Lemaresquier - Brainstorm - alex at brainstorm.fr
cd33ec11 11 * See README file for infos.
d6c32258 12 * @package squirrelmail
cd33ec11 13 *
14 */
15
d6c32258 16/** This functionality requires the IMAP and date functions */
ff6f916c 17require_once(SM_PATH . 'functions/imap_general.php');
cd33ec11 18require_once(SM_PATH . 'functions/date.php');
19
d6c32258 20/** Set to TRUE to dump the imap dialogue */
cd33ec11 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
ff6f916c 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
84function 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];
b28bec15 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
797784f9 97 global $color;
b28bec15 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 }
ff6f916c 109}
110
cd33ec11 111/* This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc! */
112function asearch_nz(&$var)
113{
114 if (isset($var))
115 return $var;
116 return '';
117}
118
b28bec15 119/* This should give the same results as PHP 4 >= 4.3.0's html_entity_decode(), except it doesn't handle hex constructs */
cd33ec11 120function 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
ff6f916c 131function s_debug_dump($var_name, $var_var)
cd33ec11 132{
133 global $imap_asearch_debug_dump;
f9fb0d38 134 if ($imap_asearch_debug_dump) {
b28bec15 135 if (function_exists('sm_print_r')) //Only exists since 1.4.2
f9fb0d38 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 }
cd33ec11 144}
145
375b552d 146/*
1474.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.
1509. Formal Syntax:
151 quoted-specials = DQUOTE / "\"
152*/
f945228f 153function sqimap_asearch_encode_string($what, $charset)
cd33ec11 154{
f945228f 155 if (strtoupper($charset) == 'ISO-2022-JP') // This should be now handled in imap_utf7_local?
cd33ec11 156 $what = mb_convert_encoding($what, 'JIS', 'auto');
ff6f916c 157//if (ereg("[\"\\\r\n\x80-\xff]", $what))
158 if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
797784f9 159 return '{' . strlen($what) . "}\r\n" . $what; // 4.3 literal form
160 return '"' . $what . '"'; // 4.3 quoted string form
cd33ec11 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
375b552d 166 Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
cd33ec11 167*/
168function sqimap_asearch_parse_date($what)
169{
170 global $imap_asearch_months;
171
172 $what = trim($what);
375b552d 173 $what = ereg_replace('[ /\\.,]+', '-', $what);
cd33ec11 174 if ($what) {
375b552d 175 preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
cd33ec11 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
f945228f 198function sqimap_asearch_build_criteria($opcode, $what, $charset)
cd33ec11 199{
200 global $imap_asearch_opcodes;
201
375b552d 202 $criteria = '';
cd33ec11 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 . ' ' .
f945228f 218 sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
219 sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
cd33ec11 220 break;
221 case 'adate':
222 $what_parts = sqimap_asearch_parse_date($what);
375b552d 223 if (isset($what_parts[0]))
cd33ec11 224 $criteria = $opcode . ' ' . $what_parts[0] . ' ';
225 break;
226 case 'akeyword':
227 case 'astring':
f945228f 228 $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
cd33ec11 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
239function sqimap_run_search($imapConnection, $search_string, $search_charset)
240{
f945228f 241 global $uid_support;
cd33ec11 242
243 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
f945228f 244 if ($search_charset != '')
245 $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
cd33ec11 246 else
ff6f916c 247 $query = 'SEARCH ALL ' . $search_string;
248 s_debug_dump('C:', $query);
ff6f916c 249 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
cd33ec11 250
f945228f 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;
ff6f916c 254 s_debug_dump('C:', $query);
f945228f 255 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
ff6f916c 256 }
257 if (strtoupper($response) != 'OK') {
258 sqimap_asearch_error_box($response, $query, $message);
259 return array();
cd33ec11 260 }
261
262 unset($messagelist);
263
264 /* Keep going till we find the SEARCH response */
265 foreach ($readin as $readin_part) {
ff6f916c 266 s_debug_dump('S:', $readin_part);
cd33ec11 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));
ff6f916c 270 break; // Should be the last anyway
cd33ec11 271 }
ff6f916c 272/* else {
273 if (isset($errors))
274 $errors = $errors . $readin_part;
275 else
276 $errors = $readin_part;
277 }*/
cd33ec11 278 }
279
280 /* If nothing is found * SEARCH should be the first error else echo errors */
ff6f916c 281/*if (isset($errors)) {
cd33ec11 282 if (strstr($errors,'* SEARCH'))
283 return array();
284 echo '<!-- ' . htmlspecialchars($errors) . ' -->';
ff6f916c 285 }*/
cd33ec11 286
ff6f916c 287 if (empty($messagelist)) //Empty search response, ie '* SEARCH'
3f075f6c 288 return array();
289
cd33ec11 290 $cnt = count($messagelist);
291 for ($q = 0; $q < $cnt; $q++)
292 $id[$q] = trim($messagelist[$q]);
293 return $id;
294}
295
f945228f 296function 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
cd33ec11 305/* replaces $mbox_msgs[$search_mailbox] = array_values(array_unique(array_merge($mbox_msgs[$search_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset))));*/
306function 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
317function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $mboxes_array)
318{
f945228f 319 $search_charset = sqimap_asearch_get_charset();
cd33ec11 320 $mbox_msgs = array();
cd33ec11 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) {
ff6f916c 335 s_debug_dump('C:SELECT:', $cur_mailbox);
27907482 336 sqimap_mailbox_select($imapConnection, $cur_mailbox);
5ab3c3fe 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 */
cd33ec11 341 $mbox_msgs[$cur_mailbox] = array_values(array_intersect(sqimap_run_search($imapConnection, $search_string, $search_charset), $mbox_msgs[$cur_mailbox]));
342 }
5ab3c3fe 343 else /* No previous results */
344 $mbox_msgs[$cur_mailbox] = sqimap_run_search($imapConnection, $search_string, $search_charset);
cd33ec11 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)
5ab3c3fe 362 $next_biop = asearch_nz($biop_array[$next_crit]);
cd33ec11 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
d6c32258 377?>