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