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