Fix for situation when mailbox cache was invalidated while iterating through
[squirrelmail.git] / functions / imap_asearch.php
CommitLineData
cd33ec11 1<?php
2
3/**
0e1a248b 4 * imap_search.php
5 *
0e1a248b 6 * IMAP asearch routines
7 *
8 * Subfolder search idea from Patch #806075 by Thomas Pohl xraven at users.sourceforge.net. Thanks Thomas!
9 *
4b4abf93 10 * @author Alex Lemaresquier - Brainstorm <alex at brainstorm.fr>
11 * @copyright &copy; 1999-2005 The SquirrelMail Project Team
12 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
0e1a248b 13 * @version $Id$
14 * @package squirrelmail
15 * @subpackage imap
16 * @see search.php
17 * @link http://www.ietf.org/rfc/rfc3501.txt
0e1a248b 18 */
cd33ec11 19
0e218c3b 20/** This functionality requires the IMAP and date functions
0e1a248b 21 */
ff6f916c 22require_once(SM_PATH . 'functions/imap_general.php');
cd33ec11 23require_once(SM_PATH . 'functions/date.php');
24
0e1a248b 25/** Set to TRUE to dump the IMAP dialogue
26 * @global bool $imap_asearch_debug_dump
27 */
cd33ec11 28$imap_asearch_debug_dump = FALSE;
29
0e1a248b 30/** IMAP SEARCH keys
31 * @global array $imap_asearch_opcodes
32 */
17a7913a 33global $imap_asearch_opcodes;
cd33ec11 34$imap_asearch_opcodes = array(
91e0dccc 35/* <sequence-set> => 'asequence', */ // Special handling, @see sqimap_asearch_build_criteria()
cd33ec11 36/*'ALL' is binary operator */
f7027a32 37 'ANSWERED' => '',
38 'BCC' => 'astring',
39 'BEFORE' => 'adate',
40 'BODY' => 'astring',
41 'CC' => 'astring',
42 'DELETED' => '',
43 'DRAFT' => '',
44 'FLAGGED' => '',
45 'FROM' => 'astring',
91e0dccc 46 'HEADER' => 'afield', // Special syntax for this one, @see sqimap_asearch_build_criteria()
f7027a32 47 'KEYWORD' => 'akeyword',
48 'LARGER' => 'anum',
49 'NEW' => '',
cd33ec11 50/*'NOT' is unary operator */
f7027a32 51 'OLD' => '',
52 'ON' => 'adate',
cd33ec11 53/*'OR' is binary operator */
f7027a32 54 'RECENT' => '',
55 'SEEN' => '',
56 'SENTBEFORE' => 'adate',
57 'SENTON' => 'adate',
58 'SENTSINCE' => 'adate',
59 'SINCE' => 'adate',
60 'SMALLER' => 'anum',
61 'SUBJECT' => 'astring',
62 'TEXT' => 'astring',
63 'TO' => 'astring',
64 'UID' => 'asequence',
65 'UNANSWERED' => '',
66 'UNDELETED' => '',
67 'UNDRAFT' => '',
68 'UNFLAGGED' => '',
69 'UNKEYWORD' => 'akeyword',
70 'UNSEEN' => ''
cd33ec11 71);
72
0e1a248b 73/** IMAP SEARCH month names encoding
74 * @global array $imap_asearch_months
75 */
cd33ec11 76$imap_asearch_months = array(
f7027a32 77 '01' => 'jan',
78 '02' => 'feb',
79 '03' => 'mar',
80 '04' => 'apr',
81 '05' => 'may',
82 '06' => 'jun',
83 '07' => 'jul',
84 '08' => 'aug',
85 '09' => 'sep',
86 '10' => 'oct',
87 '11' => 'nov',
88 '12' => 'dec'
cd33ec11 89);
90
00b05f03 91/**
0e1a248b 92 * Function to display an error related to an IMAP query.
93 * We need to do our own error management since we may receive NO responses on purpose (even BAD with SORT or THREAD)
94 * so we call sqimap_error_box() if the function exists (sm >= 1.5) or use our own embedded code
95 * @global array imap_error_titles
96 * @param string $response the imap server response code
97 * @param string $query the failed query
98 * @param string $message an optional error message
99 * @param string $link an optional link to try again
100 */
00b05f03 101//@global array color sm colors array
40fbe929 102function sqimap_asearch_error_box($response, $query, $message, $link = '')
ff6f916c 103{
0daff8c9 104 global $color;
0e1a248b 105 // Error message titles according to IMAP server returned code
0daff8c9 106 $imap_error_titles = array(
107 'OK' => '',
0e1a248b 108 'NO' => _("ERROR: Could not complete request."),
109 'BAD' => _("ERROR: Bad or malformed request."),
110 'BYE' => _("ERROR: IMAP server closed the connection."),
111 '' => _("ERROR: Connection dropped by IMAP server.")
0daff8c9 112 );
113
f7027a32 114
115 if (!array_key_exists($response, $imap_error_titles))
0e1a248b 116 $title = _("ERROR: Unknown IMAP response.");
f7027a32 117 else
118 $title = $imap_error_titles[$response];
119 if ($link == '')
0e1a248b 120 $message_title = _("Reason Given:");
f7027a32 121 else
0e1a248b 122 $message_title = _("Possible reason:");
123 $message_title .= ' ';
f7027a32 124 if (function_exists('sqimap_error_box'))
125 sqimap_error_box($title, $query, $message_title, $message, $link);
91e0dccc 126 else { //Straight copy of 1.5 imap_general.php:sqimap_error_box(). Can be removed at a later time
f7027a32 127 global $color;
b28bec15 128 require_once(SM_PATH . 'functions/display_messages.php');
6fd95361 129 $string = "<font color=\"$color[2]\"><b>\n" . $title . "</b><br />\n";
b28bec15 130 if ($query != '')
6fd95361 131 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br />';
b28bec15 132 if ($message_title != '')
133 $string .= $message_title;
134 if ($message != '')
135 $string .= htmlspecialchars($message);
40fbe929 136 if ($link != '')
137 $string .= $link;
6fd95361 138 $string .= "</font><br />\n";
b28bec15 139 error_box($string,$color);
f7027a32 140 }
ff6f916c 141}
142
48af4b64 143/**
0e1a248b 144 * This is a convenient way to avoid spreading if (isset(... all over the code
145 * @param mixed $var any variable (reference)
146 * @param mixed $def default value to return if unset (default is zls (''), pass 0 or array() when appropriate)
147 * @return mixed $def if $var is unset, otherwise $var
148 */
2c300e0b 149function asearch_nz(&$var, $def = '')
cd33ec11 150{
f7027a32 151 if (isset($var))
152 return $var;
153 return $def;
cd33ec11 154}
155
48af4b64 156/**
0e1a248b 157 * This should give the same results as PHP 4 >= 4.3.0's html_entity_decode(),
158 * except it doesn't handle hex constructs
159 * @param string $string string to unhtmlentity()
160 * @return string decoded string
161 */
cd33ec11 162function asearch_unhtmlentities($string) {
f7027a32 163 $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES));
91e0dccc 164 for ($i=127; $i<255; $i++) /* Add &#<dec>; entities */
f7027a32 165 $trans_tbl['&#' . $i . ';'] = chr($i);
166 return strtr($string, $trans_tbl);
cd33ec11 167/* I think the one above is quicker, though it should be benchmarked
f7027a32 168 $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
169 return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
0e1a248b 170 */
cd33ec11 171}
172
00b05f03 173/**
0e1a248b 174 * Provide an easy way to dump the IMAP dialogue if $imap_asearch_debug_dump is TRUE
175 * @global bool imap_asearch_debug_dump
176 * @param string $var_name
177 * @param string $var_var
f8a1ed5a 178 * @deprecated contains workarounds for 1.4.0 and older code.
7e627c96 179 * code without workarounds uses regular sm 1.4.2+ functions.
180 * it is not compatible with 1.4.1
181 * @todo remove debugging function
0e1a248b 182 */
ff6f916c 183function s_debug_dump($var_name, $var_var)
cd33ec11 184{
f7027a32 185 global $imap_asearch_debug_dump;
186 if ($imap_asearch_debug_dump) {
91e0dccc 187 if (function_exists('sm_print_r')) //Only exists since 1.4.2
188 sm_print_r($var_name, $var_var); //Better be the 'varargs' version ;)
f7027a32 189 else {
190 echo '<pre>';
191 echo htmlentities($var_name);
192 print_r($var_var);
193 echo '</pre>';
194 }
195 }
cd33ec11 196}
197
00b05f03 198/** Encode a string to quoted or literal as defined in rfc 3501
0e1a248b 199 *
200 * - 4.3 String:
201 * A quoted string is a sequence of zero or more 7-bit characters,
202 * excluding CR and LF, with double quote (<">) characters at each end.
203 * - 9. Formal Syntax:
204 * quoted-specials = DQUOTE / "\"
205 * @param string $what string to encode
206 * @param string $charset search charset used
207 * @return string encoded string
208 */
f945228f 209function sqimap_asearch_encode_string($what, $charset)
cd33ec11 210{
91e0dccc 211 if (strtoupper($charset) == 'ISO-2022-JP') // This should be now handled in imap_utf7_local?
f7027a32 212 $what = mb_convert_encoding($what, 'JIS', 'auto');
213 if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
91e0dccc 214 return '{' . strlen($what) . "}\r\n" . $what; // 4.3 literal form
215 return '"' . $what . '"'; // 4.3 quoted string form
cd33ec11 216}
217
48af4b64 218/**
0e1a248b 219 * Parses a user date string into an rfc 3501 date string
220 * Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
221 * @global array imap_asearch_months
222 * @param string user date
223 * @return array a preg_match-style array:
224 * - [0] = fully formatted rfc 3501 date string (<day number>-<US month TLA>-<4 digit year>)
225 * - [1] = day
226 * - [2] = month
227 * - [3] = year
228 */
cd33ec11 229function sqimap_asearch_parse_date($what)
230{
f7027a32 231 global $imap_asearch_months;
232
233 $what = trim($what);
234 $what = ereg_replace('[ /\\.,]+', '-', $what);
235 if ($what) {
236 preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
237 if (count($what_parts) == 4) {
238 $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
91e0dccc 239/* if (!in_array($what_month, $imap_asearch_months)) {*/
f7027a32 240 foreach ($imap_asearch_months as $month_number => $month_code) {
241 if (($what_month == $month_number)
242 || ($what_month == $month_code)
243 || ($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
244 || ($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
245 ) {
246 $what_parts[2] = $month_number;
247 $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
248 break;
249 }
250 }
91e0dccc 251/* }*/
f7027a32 252 }
253 }
254 else
255 $what_parts = array();
256 return $what_parts;
cd33ec11 257}
258
00b05f03 259/**
0e1a248b 260 * Build one criteria sequence
261 * @global array imap_asearch_opcodes
262 * @param string $opcode search opcode
263 * @param string $what opcode argument
264 * @param string $charset search charset
265 * @return string one full criteria sequence
266 */
f945228f 267function sqimap_asearch_build_criteria($opcode, $what, $charset)
cd33ec11 268{
f7027a32 269 global $imap_asearch_opcodes;
270
271 $criteria = '';
272 switch ($imap_asearch_opcodes[$opcode]) {
273 default:
274 case 'anum':
275 $what = str_replace(' ', '', $what);
276 $what = ereg_replace('[^0-9]+[^KMG]$', '', strtoupper($what));
277 if ($what != '') {
278 switch (substr($what, -1)) {
279 case 'G':
280 $what = substr($what, 0, -1) << 30;
281 break;
282 case 'M':
283 $what = substr($what, 0, -1) << 20;
284 break;
285 case 'K':
286 $what = substr($what, 0, -1) << 10;
287 break;
288 }
289 $criteria = $opcode . ' ' . $what . ' ';
290 }
291 break;
91e0dccc 292 case '': //aflag
f7027a32 293 $criteria = $opcode . ' ';
294 break;
91e0dccc 295 case 'afield': /* HEADER field-name: field-body */
f7027a32 296 preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
297 if (count($what_parts) == 3)
298 $criteria = $opcode . ' ' .
299 sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
300 sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
301 break;
302 case 'adate':
303 $what_parts = sqimap_asearch_parse_date($what);
304 if (isset($what_parts[0]))
305 $criteria = $opcode . ' ' . $what_parts[0] . ' ';
306 break;
307 case 'akeyword':
308 case 'astring':
309 $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
310 break;
311 case 'asequence':
312 $what = ereg_replace('[^0-9:\(\)]+', '', $what);
313 if ($what != '')
314 $criteria = $opcode . ' ' . $what . ' ';
315 break;
316 }
317 return $criteria;
cd33ec11 318}
319
00b05f03 320/**
0e1a248b 321 * Another way to do array_values(array_unique(array_merge($to, $from)));
322 * @param array $to to array (reference)
323 * @param array $from from array
324 * @return array uniquely merged array
325 */
d2f031ed 326function sqimap_array_merge_unique(&$to, $from)
75d24fd2 327{
f7027a32 328 if (empty($to))
329 return $from;
330 $count = count($from);
331 for ($i = 0; $i < $count; $i++) {
332 if (!in_array($from[$i], $to))
333 $to[] = $from[$i];
334 }
335 return $to;
75d24fd2 336}
337
00b05f03 338/**
0e1a248b 339 * Run the IMAP SEARCH command as defined in rfc 3501
340 * @link http://www.ietf.org/rfc/rfc3501.txt
341 * @param resource $imapConnection the current imap stream
342 * @param string $search_string the full search expression eg "ALL RECENT"
343 * @param string $search_charset charset to use or zls ('')
344 * @return array an IDs or UIDs array of matching messages or an empty array
345 * @since 1.5.0
346 */
cd33ec11 347function sqimap_run_search($imapConnection, $search_string, $search_charset)
348{
f7027a32 349 //For some reason, this seems to happen and forbids searching servers not allowing OPTIONAL [CHARSET]
350 if (strtoupper($search_charset) == 'US-ASCII')
351 $search_charset = '';
352 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
353 if ($search_charset != '')
354 $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ' . $search_string;
355 else
356 $query = 'SEARCH ' . $search_string;
357 s_debug_dump('C:', $query);
358 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
359
360 /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
361 if (($search_charset != '') && (strtoupper($response) == 'NO')) {
362 $query = 'SEARCH CHARSET US-ASCII ' . $search_string;
363 s_debug_dump('C:', $query);
364 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
365 }
366 if (strtoupper($response) != 'OK') {
367 sqimap_asearch_error_box($response, $query, $message);
368 return array();
369 }
324ac3c5 370 $messagelist = parseUidList($readin,'SEARCH');
cd33ec11 371
91e0dccc 372 if (empty($messagelist)) //Empty search response, ie '* SEARCH'
f7027a32 373 return array();
3f075f6c 374
f7027a32 375 $cnt = count($messagelist);
376 for ($q = 0; $q < $cnt; $q++)
377 $id[$q] = trim($messagelist[$q]);
378 return $id;
cd33ec11 379}
380
00b05f03 381/**
0e1a248b 382 * @global bool allow_charset_search user setting
383 * @global array languages sm languages array
384 * @global string squirrelmail_language user language setting
385 * @return string the user defined charset if $allow_charset_search is TRUE else zls ('')
386 */
f945228f 387function sqimap_asearch_get_charset()
388{
f7027a32 389 global $allow_charset_search, $languages, $squirrelmail_language;
f945228f 390
f7027a32 391 if ($allow_charset_search)
392 return $languages[$squirrelmail_language]['CHARSET'];
393 return '';
f945228f 394}
395
00b05f03 396/**
0e1a248b 397 * Convert SquirrelMail internal sort to IMAP sort taking care of:
398 * - user defined date sorting (ARRIVAL vs DATE)
399 * - if the searched mailbox is the sent folder then TO is being used instead of FROM
400 * - reverse order by using REVERSE
401 * @param string $mailbox mailbox name to sort
402 * @param integer $sort_by sm sort criteria index
403 * @global bool internal_date_sort sort by arrival date instead of message date
404 * @global string sent_folder sent folder name
405 * @return string imap sort criteria
406 */
c2d47d51 407function sqimap_asearch_get_sort_criteria($mailbox, $sort_by)
408{
f7027a32 409 global $internal_date_sort, $sent_folder;
c2d47d51 410
f7027a32 411 $sort_opcodes = array ('DATE', 'FROM', 'SUBJECT', 'SIZE');
412 if ($internal_date_sort == true)
413 $sort_opcodes[0] = 'ARRIVAL';
e50f5ac2 414// if (handleAsSent($mailbox))
415// if (isSentFolder($mailbox))
f7027a32 416 if ($mailbox == $sent_folder)
417 $sort_opcodes[1] = 'TO';
418 return (($sort_by % 2) ? '' : 'REVERSE ') . $sort_opcodes[($sort_by >> 1) & 3];
c2d47d51 419}
420
40fbe929 421/**
0e1a248b 422 * @param string $cur_mailbox unformatted mailbox name
423 * @param array $boxes_unformatted selectable mailbox unformatted names array (reference)
424 * @return array sub mailboxes unformatted names
425 */
0e218c3b 426function sqimap_asearch_get_sub_mailboxes($cur_mailbox, &$mboxes_array)
40fbe929 427{
f7027a32 428 $sub_mboxes_array = array();
429 $boxcount = count($mboxes_array);
430 for ($boxnum=0; $boxnum < $boxcount; $boxnum++) {
431 if (isBoxBelow($mboxes_array[$boxnum], $cur_mailbox))
432 $sub_mboxes_array[] = $mboxes_array[$boxnum];
433 }
434 return $sub_mboxes_array;
40fbe929 435}
436
00b05f03 437/**
0e1a248b 438 * Create the search query strings for all given criteria and merge results for every mailbox
439 * @param resource $imapConnection
440 * @param array $mailbox_array (reference)
441 * @param array $biop_array (reference)
442 * @param array $unop_array (reference)
443 * @param array $where_array (reference)
444 * @param array $what_array (reference)
445 * @param array $exclude_array (reference)
446 * @param array $sub_array (reference)
447 * @param array $mboxes_array selectable unformatted mailboxes names (reference)
448 * @return array array(mailbox => array(UIDs))
449 */
0e218c3b 450function sqimap_asearch($imapConnection, &$mailbox_array, &$biop_array, &$unop_array, &$where_array, &$what_array, &$exclude_array, &$sub_array, &$mboxes_array)
cd33ec11 451{
c2d47d51 452
f7027a32 453 $search_charset = sqimap_asearch_get_charset();
324ac3c5 454 $mbox_search = array();
f7027a32 455 $search_string = '';
456 $cur_mailbox = $mailbox_array[0];
91e0dccc 457 $cur_biop = ''; /* Start with ALL */
f7027a32 458 /* We loop one more time than the real array count, so the last search gets fired */
459 for ($cur_crit=0,$iCnt=count($where_array); $cur_crit <= $iCnt; ++$cur_crit) {
460 if (empty($exclude_array[$cur_crit])) {
461 $next_mailbox = (isset($mailbox_array[$cur_crit])) ? $mailbox_array[$cur_crit] : false;
462 if ($next_mailbox != $cur_mailbox) {
91e0dccc 463 $search_string = trim($search_string); /* Trim out last space */
f7027a32 464 if ($cur_mailbox == 'All Folders')
696155b5 465 $search_mboxes = $mboxes_array;
f7027a32 466 else if ((!empty($sub_array[$cur_crit - 1])) || (!in_array($cur_mailbox, $mboxes_array)))
467 $search_mboxes = sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array);
468 else
469 $search_mboxes = array($cur_mailbox);
470 foreach ($search_mboxes as $cur_mailbox) {
324ac3c5 471 if (isset($mbox_search[$cur_mailbox])) {
472 $mbox_search[$cur_mailbox]['search'] .= ' ' . $search_string;
473 } else {
474 $mbox_search[$cur_mailbox]['search'] = $search_string;
475 }
476 $mbox_search[$cur_mailbox]['charset'] = $search_charset;
477 }
f7027a32 478 $cur_mailbox = $next_mailbox;
479 $search_string = '';
f7027a32 480 }
481 if (isset($where_array[$cur_crit]) && empty($exclude_array[$cur_crit])) {
482 for ($crit = $cur_crit; $crit < count($where_array); $crit++) {
483 $criteria = trim(sqimap_asearch_build_criteria($where_array[$crit], $what_array[$crit], $search_charset));
484 if (!empty($criteria) && empty($exclude_array[$crit])) {
485 if (asearch_nz($mailbox_array[$crit]) == $cur_mailbox) {
486 $unop = $unop_array[$crit];
487 if (!empty($unop)) {
488 $criteria = $unop . ' ' . $criteria;
489 }
490 $aCriteria[] = array($biop_array[$crit], $criteria);
491 }
324ac3c5 492 }
f7027a32 493 // unset something
494 $exclude_array[$crit] = true;
495 }
496 $aSearch = array();
497 for($i=0,$iCnt=count($aCriteria);$i<$iCnt;++$i) {
498 $cur_biop = $aCriteria[$i][0];
499 $next_biop = (isset($aCriteria[$i+1][0])) ? $aCriteria[$i+1][0] : false;
500 if ($next_biop != $cur_biop && $next_biop == 'OR') {
501 $aSearch[] = 'OR '.$aCriteria[$i][1];
502 } else if ($cur_biop != 'OR') {
503 $aSearch[] = 'ALL '.$aCriteria[$i][1];
696155b5 504 } else { // OR only supports 2 search keys so we need to create a parenthesized list
f7027a32 505 $prev_biop = (isset($aCriteria[$i-1][0])) ? $aCriteria[$i-1][0] : false;
506 if ($prev_biop == $cur_biop) {
507 $last = $aSearch[$i-1];
508 if (!substr($last,-1) == ')') {
509 $aSearch[$i-1] = "(OR $last";
510 $aSearch[] = $aCriteria[$i][1].')';
511 } else {
512 $sEnd = '';
513 while ($last && substr($last,-1) == ')') {
696155b5 514 $last = substr($last,0,-1);
515 $sEnd .= ')';
324ac3c5 516 }
f7027a32 517 $aSearch[$i-1] = "(OR $last";
518 $aSearch[] = $aCriteria[$i][1].$sEnd.')';
519 }
520 } else {
521 $aSearch[] = $aCriteria[$i][1];
522 }
523 }
f7027a32 524 }
525 $search_string .= implode(' ',$aSearch);
526 }
f7027a32 527 }
528 }
324ac3c5 529 return ($mbox_search);
cd33ec11 530}
531
6fd95361 532?>