two more subpackage blocks
[squirrelmail.git] / functions / imap_asearch.php
CommitLineData
cd33ec11 1<?php
2
3/**
4 * imap_search.php
5 *
82d304a0 6 * Copyright (c) 1999-2004 The SquirrelMail Project Team
cd33ec11 7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * IMAP asearch routines
40fbe929 10 *
eb19bc67 11 * Subfolder search idea from Patch #806075 by Thomas Pohl xraven at users.sourceforge.net. Thanks Thomas!
12 *
13 * @version $Id$
d6c32258 14 * @package squirrelmail
eb19bc67 15 * @subpackage imap
00b05f03 16 * @see search.php
40fbe929 17 * @link ftp://ftp.rfc-editor.org/in-notes/rfc3501.txt
18 * @author Alex Lemaresquier - Brainstorm - alex at brainstorm.fr
cd33ec11 19 */
20
d6c32258 21/** This functionality requires the IMAP and date functions */
ff6f916c 22require_once(SM_PATH . 'functions/imap_general.php');
cd33ec11 23require_once(SM_PATH . 'functions/date.php');
24
00b05f03 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
40fbe929 30/** Imap SEARCH keys
00b05f03 31 * @global array $imap_asearch_opcodes
32 */
cd33ec11 33$imap_asearch_opcodes = array(
34/* <message set> => 'asequence', */
35/*'ALL' is binary operator */
36 'ANSWERED' => '',
37 'BCC' => 'astring',
38 'BEFORE' => 'adate',
39 'BODY' => 'astring',
40 'CC' => 'astring',
41 'DELETED' => '',
42 'DRAFT' => '',
43 'FLAGGED' => '',
44 'FROM' => 'astring',
45 'HEADER' => 'afield', /* Special syntax for this one, see below */
46 'KEYWORD' => 'akeyword',
47 'LARGER' => 'anum',
48 'NEW' => '',
49/*'NOT' is unary operator */
50 'OLD' => '',
51 'ON' => 'adate',
52/*'OR' is binary operator */
53 'RECENT' => '',
54 'SEEN' => '',
55 'SENTBEFORE' => 'adate',
56 'SENTON' => 'adate',
57 'SENTSINCE' => 'adate',
58 'SINCE' => 'adate',
59 'SMALLER' => 'anum',
60 'SUBJECT' => 'astring',
61 'TEXT' => 'astring',
62 'TO' => 'astring',
63 'UID' => 'asequence',
64 'UNANSWERED' => '',
65 'UNDELETED' => '',
66 'UNDRAFT' => '',
67 'UNFLAGGED' => '',
68 'UNKEYWORD' => 'akeyword',
69 'UNSEEN' => ''
70);
71
00b05f03 72/** Imap SEARCH month names encoding
73 * @global array $imap_asearch_months
74 */
cd33ec11 75$imap_asearch_months = array(
76 '01' => 'jan',
77 '02' => 'feb',
78 '03' => 'mar',
79 '04' => 'apr',
80 '05' => 'may',
81 '06' => 'jun',
82 '07' => 'jul',
83 '08' => 'aug',
84 '09' => 'sep',
85 '10' => 'oct',
86 '11' => 'nov',
87 '12' => 'dec'
88);
89
00b05f03 90/** Error message titles according to imap server returned code
91 * @global array $imap_error_titles
92 */
ff6f916c 93$imap_error_titles = array(
94 'OK' => '',
95 'NO' => _("ERROR : Could not complete request."),
96 'BAD' => _("ERROR : Bad or malformed request."),
40fbe929 97 'BYE' => _("ERROR : Imap server closed the connection."),
98 '' => _("ERROR : Connection dropped by imap-server.")
ff6f916c 99);
100
00b05f03 101/**
102 * Function to display an error related to an IMAP-query.
103 * We need to do our own error management since we may receive NO responses on purpose (even BAD with SORT or THREAD)
104 * so we call sqimap_error_box() if the function exists (sm >= 1.5) or use our own embedded code
105 * @global array imap_error_titles
106 * @param string $response the imap server response code
107 * @param string $query the failed query
40fbe929 108 * @param string $message an optional error message
109 * @param string $link an optional link to try again
00b05f03 110 */
111//@global array color sm colors array
40fbe929 112function sqimap_asearch_error_box($response, $query, $message, $link = '')
ff6f916c 113{
114 global $imap_error_titles;
115
abd74f7d 116 if (!array_key_exists($response, $imap_error_titles))
ff6f916c 117 $title = _("ERROR : Unknown imap response.");
118 else
119 $title = $imap_error_titles[$response];
40fbe929 120 if ($link == '')
121 $message_title = _("Reason Given: ");
122 else
123 $message_title = _("Possible reason : ");
b28bec15 124 if (function_exists('sqimap_error_box'))
40fbe929 125 sqimap_error_box($title, $query, $message_title, $message, $link);
b28bec15 126 else { //Straight copy of 1.5 imap_general.php:sqimap_error_box(). Can be removed at a later time
797784f9 127 global $color;
b28bec15 128 require_once(SM_PATH . 'functions/display_messages.php');
129 $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
130 if ($query != '')
131 $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
132 if ($message_title != '')
133 $string .= $message_title;
134 if ($message != '')
135 $string .= htmlspecialchars($message);
40fbe929 136 if ($link != '')
137 $string .= $link;
b28bec15 138 $string .= "</font><br>\n";
139 error_box($string,$color);
140 }
ff6f916c 141}
142
48af4b64 143/**
144 * This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc!
d2f031ed 145 * @param mixed $var any variable (reference)
00b05f03 146 * @return mixed zls ('') if $var is not defined, otherwise $var
48af4b64 147 */
cd33ec11 148function asearch_nz(&$var)
149{
150 if (isset($var))
151 return $var;
152 return '';
153}
154
48af4b64 155/**
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
00b05f03 158 * @param string $string string to unhtmlentity()
159 * @return string decoded string
48af4b64 160 */
cd33ec11 161function asearch_unhtmlentities($string) {
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);
166/* I think the one above is quicker, though it should be benchmarked
167 $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
168 return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
169*/
170}
171
00b05f03 172/**
173 * Provide an easy way to dump the imap dialogue if $imap_asearch_debug_dump is TRUE
174 * @global 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{
180 global $imap_asearch_debug_dump;
f9fb0d38 181 if ($imap_asearch_debug_dump) {
b28bec15 182 if (function_exists('sm_print_r')) //Only exists since 1.4.2
f9fb0d38 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
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{
f945228f 206 if (strtoupper($charset) == 'ISO-2022-JP') // This should be now handled in imap_utf7_local?
cd33ec11 207 $what = mb_convert_encoding($what, 'JIS', 'auto');
ff6f916c 208//if (ereg("[\"\\\r\n\x80-\xff]", $what))
209 if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
797784f9 210 return '{' . strlen($what) . "}\r\n" . $what; // 4.3 literal form
211 return '"' . $what . '"'; // 4.3 quoted string form
cd33ec11 212}
213
48af4b64 214/**
00b05f03 215 * Parses a user date string into an rfc 3501 date string
48af4b64 216 * Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
00b05f03 217 * @global imap_asearch_months
218 * @param string user date
219 * @return array a preg_match-style array:
220 * - [0] = fully formatted rfc 3501 date string (<day number>-<US month TLA>-<4 digit year>)
221 * - [1] = day
222 * - [2] = month
223 * - [3] = year
48af4b64 224 */
cd33ec11 225function sqimap_asearch_parse_date($what)
226{
227 global $imap_asearch_months;
228
229 $what = trim($what);
375b552d 230 $what = ereg_replace('[ /\\.,]+', '-', $what);
cd33ec11 231 if ($what) {
375b552d 232 preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
cd33ec11 233 if (count($what_parts) == 4) {
234 $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
235/* if (!in_array($what_month, $imap_asearch_months)) {*/
236 foreach ($imap_asearch_months as $month_number => $month_code) {
237 if (($what_month == $month_number)
238 || ($what_month == $month_code)
239 || ($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
240 || ($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
241 ) {
242 $what_parts[2] = $month_number;
243 $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
244 break;
245 }
246 }
247/* }*/
248 }
249 }
250 else
251 $what_parts = array();
252 return $what_parts;
253}
254
00b05f03 255/**
256 * Build one criteria sequence
257 * @global array imap_asearch_opcodes
258 * @param string $opcode search opcode
259 * @param string $what opcode argument
260 * @param string $charset search charset
261 * @return string one full criteria sequence
262 */
f945228f 263function sqimap_asearch_build_criteria($opcode, $what, $charset)
cd33ec11 264{
265 global $imap_asearch_opcodes;
266
375b552d 267 $criteria = '';
cd33ec11 268 switch ($imap_asearch_opcodes[$opcode]) {
269 default:
270 case 'anum':
00b05f03 271// $what = str_replace(' ', '', $what);
cd33ec11 272 $what = ereg_replace('[^0-9]+', '', $what);
273 if ($what != '')
274 $criteria = $opcode . ' ' . $what . ' ';
275 break;
00b05f03 276 case '': //aflag
cd33ec11 277 $criteria = $opcode . ' ';
278 break;
279 case 'afield': /* HEADER field-name: field-body */
280 preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
281 if (count($what_parts) == 3)
282 $criteria = $opcode . ' ' .
f945228f 283 sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
284 sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
cd33ec11 285 break;
286 case 'adate':
287 $what_parts = sqimap_asearch_parse_date($what);
375b552d 288 if (isset($what_parts[0]))
cd33ec11 289 $criteria = $opcode . ' ' . $what_parts[0] . ' ';
290 break;
291 case 'akeyword':
292 case 'astring':
f945228f 293 $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
cd33ec11 294 break;
295 case 'asequence':
296 $what = ereg_replace('[^0-9:\(\)]+', '', $what);
297 if ($what != '')
298 $criteria = $opcode . ' ' . $what . ' ';
299 break;
300 }
301 return $criteria;
302}
303
00b05f03 304/**
305 * Another way to do array_values(array_unique(array_merge($to, $from)));
d2f031ed 306 * @param array $to to array (reference)
00b05f03 307 * @param array $from from array
308 * @return array uniquely merged array
309 */
d2f031ed 310function sqimap_array_merge_unique(&$to, $from)
75d24fd2 311{
312 if (empty($to))
313 return $from;
314 $count = count($from);
315 for ($i = 0; $i < $count; $i++) {
316 if (!in_array($from[$i], $to))
317 $to[] = $from[$i];
318 }
319 return $to;
320}
321
00b05f03 322/**
323 * Run the imap SEARCH command as defined in rfc 3501
324 * @link ftp://ftp.rfc-editor.org/in-notes/rfc3501.txt
325 * @param resource $imapConnection the current imap stream
326 * @param string $search_string the full search expression eg "ALL RECENT"
327 * @param string $search_charset charset to use or zls ('')
328 * @return array an IDs or UIDs array of matching messages or an empty array
329 */
cd33ec11 330function sqimap_run_search($imapConnection, $search_string, $search_charset)
331{
cd33ec11 332 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
f945228f 333 if ($search_charset != '')
334 $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
cd33ec11 335 else
ff6f916c 336 $query = 'SEARCH ALL ' . $search_string;
337 s_debug_dump('C:', $query);
6201339c 338 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
cd33ec11 339
f945228f 340 /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
341 if (($search_charset != '') && (strtoupper($response) == 'NO')) {
342 $query = 'SEARCH CHARSET US-ASCII ALL ' . $search_string;
ff6f916c 343 s_debug_dump('C:', $query);
6201339c 344 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
ff6f916c 345 }
346 if (strtoupper($response) != 'OK') {
347 sqimap_asearch_error_box($response, $query, $message);
348 return array();
cd33ec11 349 }
350
75d24fd2 351 // Keep going till we find the * SEARCH response
cd33ec11 352 foreach ($readin as $readin_part) {
ff6f916c 353 s_debug_dump('S:', $readin_part);
cd33ec11 354 if (substr($readin_part, 0, 9) == '* SEARCH ') {
00b05f03 355 //EIMS returns multiple SEARCH responses, and this allowed according to Mark Crispin
d2f031ed 356 $messagelist = sqimap_array_merge_unique($messagelist, preg_split("/ /", substr($readin_part, 9)));
cd33ec11 357 }
358 }
359
ff6f916c 360 if (empty($messagelist)) //Empty search response, ie '* SEARCH'
3f075f6c 361 return array();
362
cd33ec11 363 $cnt = count($messagelist);
364 for ($q = 0; $q < $cnt; $q++)
365 $id[$q] = trim($messagelist[$q]);
366 return $id;
367}
368
00b05f03 369/**
370 * Run the imap SORT command as defined in
371 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
372 * @param resource $imapConnection the current imap stream
373 * @param string $search_string the full search expression as defined in rfc 3501
374 * @param string $search_charset mandatory charset
375 * @param string $sort_criteria the full sort criteria expression eg "SUBJECT REVERSE DATE"
376 * @return array an IDs or UIDs array of matching messages or an empty array
377 */
c2d47d51 378function sqimap_run_sort($imapConnection, $search_string, $search_charset, $sort_criteria)
379{
c2d47d51 380 if ($search_charset == '')
381 $search_charset = 'US-ASCII';
40fbe929 382 $query = 'SORT (' . $sort_criteria . ') "' . strtoupper($search_charset) . '" ALL ' . $search_string;
c2d47d51 383 s_debug_dump('C:', $query);
6201339c 384 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
40fbe929 385 s_debug_dump('S:', $response);
c2d47d51 386
387 /* 6.4 try US-ASCII charset if we received a tagged NO response (SHOULD be [BADCHARSET]) */
388 if (($search_charset != 'US-ASCII') && (strtoupper($response) == 'NO')) {
40fbe929 389 s_debug_dump('S:', $readin);
c2d47d51 390 $query = 'SORT (' . $sort_criteria . ') US-ASCII ALL ' . $search_string;
391 s_debug_dump('C:', $query);
6201339c 392 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
40fbe929 393 s_debug_dump('S:', $response);
c2d47d51 394 }
395
396 if (strtoupper($response) != 'OK') {
40fbe929 397 s_debug_dump('S:', $readin);
75d24fd2 398// sqimap_asearch_error_box($response, $query, $message);
399// return array();
400 return sqimap_run_search($imapConnection, $search_string, $search_charset); // Fell back to standard search
c2d47d51 401 }
402
403 /* Keep going till we find the * SORT response */
404 foreach ($readin as $readin_part) {
405 s_debug_dump('S:', $readin_part);
406 if (substr($readin_part, 0, 7) == '* SORT ') {
00b05f03 407 //SORT returns untagged responses
d2f031ed 408 $messagelist = sqimap_array_merge_unique($messagelist, preg_split("/ /", substr($readin_part, 7)));
c2d47d51 409 }
410 }
411
412 if (empty($messagelist)) //Empty search response, ie '* SORT'
413 return array();
414
415 $cnt = count($messagelist);
416 for ($q = 0; $q < $cnt; $q++)
417 $id[$q] = trim($messagelist[$q]);
418 return $id;
419}
420
00b05f03 421/**
422 * Run the imap THREAD command as defined in
423 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
424 * @param resource $imapConnection the current imap stream
425 * @param string $search_string the full search expression as defined in rfc 3501
426 * @param string $search_charset mandatory charset
427 * @param string $thread_algorithm the threading algorithm "ORDEREDSUBJECT" or "REFERENCES"
428 * @return array an IDs or UIDs array of matching messages or an empty array
2d2f8bb8 429 * @global array thread_new will be used by thread view in mailbox_display
430 * @global array server_sort_array will be used by thread view in mailbox_display
00b05f03 431 */
c2d47d51 432function sqimap_run_thread($imapConnection, $search_string, $search_charset, $thread_algorithm)
433{
434 global $thread_new, $server_sort_array;
435
436 if (sqsession_is_registered('thread_new'))
437 sqsession_unregister('thread_new');
438 if (sqsession_is_registered('server_sort_array'))
439 sqsession_unregister('server_sort_array');
440
441 $thread_new = array();
442 $thread_new[0] = "";
443
444 $server_sort_array = array();
445
c2d47d51 446 if ($search_charset == '')
447 $search_charset = 'US-ASCII';
40fbe929 448 $query = 'THREAD ' . $thread_algorithm . ' "' . strtoupper($search_charset) . '" ALL ' . $search_string;
c2d47d51 449 s_debug_dump('C:', $query);
6201339c 450 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
40fbe929 451 s_debug_dump('S:', $response);
c2d47d51 452
453 /* 6.4 try US-ASCII charset if we received a tagged NO response (SHOULD be [BADCHARSET]) */
454 if (($search_charset != 'US-ASCII') && (strtoupper($response) == 'NO')) {
40fbe929 455 s_debug_dump('S:', $readin);
c2d47d51 456 $query = 'THREAD ' . $thread_algorithm . ' US-ASCII ALL ' . $search_string;
457 s_debug_dump('C:', $query);
6201339c 458 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
40fbe929 459 s_debug_dump('S:', $response);
c2d47d51 460 }
461
462 if (strtoupper($response) != 'OK') {
40fbe929 463 s_debug_dump('S:', $readin);
464 if (empty($response)) { //imap server closed connection. We can't go further.
75d24fd2 465/* we should at this point:
466 - warn the user that the THREAD call has failed
467 - (offer him a way to) disconnect it permanently in the prefs
468 - perform the regular search instead or provide a way to do it in one click
469*/
40fbe929 470 global $sort, $mailbox, $php_self;
471 $message = _("The imap server failed to handle threading.");
472 $unthread = _("Click here to unset thread view for this mailbox and start again.");
473 if (preg_match('/^(.+)\?.+$/', $php_self, $regs))
474 $source_url = $regs[1];
475 else
476 $source_url = $php_self;
477 $link = '<a href=' . $source_url . '?sort=' . $sort . '&start_messages=1&set_thread=0&mailbox=' . urlencode($mailbox) . '>' . $unthread . '</a>';
478 sqimap_asearch_error_box($response, $query, $message, $link);
479 return array();
480 }
481 return sqimap_run_search($imapConnection, $search_string, $search_charset); // Fell back to standard search
c2d47d51 482 }
483
484 /* Keep going till we find the * THREAD response */
485 foreach ($readin as $readin_part) {
486 s_debug_dump('S:', $readin_part);
487 if (substr($readin_part, 0, 9) == '* THREAD ') {
488 $thread_temp = preg_split("//", substr($readin_part, 9), -1, PREG_SPLIT_NO_EMPTY);
489 break; // Should be the last anyway
490 }
491 }
492
493 if (empty($thread_temp)) //Empty search response, ie '* THREAD'
494 return array();
495
496 $char_count = count($thread_temp);
497 $counter = 0;
498 $k = 0;
499 for ($i=0;$i<$char_count;$i++) {
500 if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
501 $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
502 }
503 elseif ($thread_temp[$i] == '(') {
504 $thread_new[$k] .= $thread_temp[$i];
505 $counter++;
506 }
507 elseif ($thread_temp[$i] == ')') {
508 if ($counter > 1) {
509 $thread_new[$k] .= $thread_temp[$i];
510 $counter = $counter - 1;
511 }
512 else {
513 $thread_new[$k] .= $thread_temp[$i];
514 $k++;
515 $thread_new[$k] = "";
516 $counter = $counter - 1;
517 }
518 }
519 }
520 sqsession_register($thread_new, 'thread_new');
521 $thread_new = array_reverse($thread_new);
522 $thread_list = implode(" ", $thread_new);
523 $thread_list = str_replace("(", " ", $thread_list);
524 $thread_list = str_replace(")", " ", $thread_list);
525 $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
526 $server_sort_array = $thread_list;
527 sqsession_register($server_sort_array, 'server_sort_array');
528 return $thread_list;
529}
530
00b05f03 531/**
532 * @global bool allow_charset_search user setting
533 * @global array languages sm languages array
534 * @global string squirrelmail_language user language setting
535 * @return string the user defined charset if $allow_charset_search is TRUE else zls ('')
536 */
f945228f 537function sqimap_asearch_get_charset()
538{
539 global $allow_charset_search, $languages, $squirrelmail_language;
540
541 if ($allow_charset_search)
542 return $languages[$squirrelmail_language]['CHARSET'];
543 return '';
544}
545
00b05f03 546/**
547 * Convert sm internal sort to imap sort taking care of:
548 * - user defined date sorting (ARRIVAL vs DATE)
549 * - if the searched mailbox is the sent folder then TO is being used instead of FROM
550 * - reverse order by using REVERSE
551 * @param string $mailbox mailbox name to sort
40fbe929 552 * @param integer $sort_by sm sort criteria index
2d2f8bb8 553 * @global bool internal_date_sort sort by arrival date instead of message date
554 * @global string sent_folder sent folder name
00b05f03 555 * @return string imap sort criteria
556 */
c2d47d51 557function sqimap_asearch_get_sort_criteria($mailbox, $sort_by)
558{
559 global $internal_date_sort, $sent_folder;
560
d2f031ed 561 $sort_opcodes = array ('DATE', 'FROM', 'SUBJECT', 'SIZE');
c2d47d51 562 if ($internal_date_sort == true)
563 $sort_opcodes[0] = 'ARRIVAL';
564// if (handleAsSent($mailbox))
565// if (isSentFolder($mailbox))
566 if ($mailbox == $sent_folder)
567 $sort_opcodes[1] = 'TO';
d2f031ed 568 return (($sort_by % 2) ? '' : 'REVERSE ') . $sort_opcodes[($sort_by >> 1) & 3];
c2d47d51 569}
570
00b05f03 571/**
40fbe929 572 * @param string $cur_mailbox unformatted mailbox name
573 * @param array $boxes_unformatted selectable mailbox unformatted names array (reference)
574 * @return array sub mailboxes unformatted names
575 */
576function sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array)
577{
578 $sub_mboxes_array = array();
579 $boxcount = count($mboxes_array);
580 for ($boxnum=0; $boxnum < $boxcount; $boxnum++) {
581 if (isBoxBelow($mboxes_array[$boxnum], $cur_mailbox))
582 $sub_mboxes_array[] = $mboxes_array[$boxnum];
583 }
584 return $sub_mboxes_array;
585}
586
587/**
00b05f03 588 * Performs the search, given all the criteria, merging results for every mailbox
40fbe929 589 * @param resource $imapConnection
590 * @param array $mailbox_array
591 * @param array $biop_array
592 * @param array $unop_array
593 * @param array $where_array
594 * @param array $what_array
595 * @param array $exclude_array
596 * @param array $sub_array
597 * @param array $mboxes_array selectable unformatted mailboxes names
2d2f8bb8 598 * @global bool allow_server_sort comes from config.php
599 * @global integer sort sm internal sort order
600 * @global bool allow_thread_sort comes from config.php
601 * @global bool thread_sort_messages does it really need to global?
602 * @global integer sort_by_ref thread by references
603 * @global string data_dir
604 * @global string username
40fbe929 605 * @return array $mbox_msgs array(mailbox => array(UIDs))
00b05f03 606 */
40fbe929 607function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $sub_array, $mboxes_array)
cd33ec11 608{
436d7f4e 609 global $allow_server_sort, $sort, $allow_thread_sort, $thread_sort_messages, $sort_by_ref;
c2d47d51 610 global $data_dir, $username;
611
f945228f 612 $search_charset = sqimap_asearch_get_charset();
cd33ec11 613 $mbox_msgs = array();
cd33ec11 614 $search_string = '';
615 $cur_mailbox = $mailbox_array[0];
616 $cur_biop = ''; /* Start with ALL */
617 /* We loop one more time than the real array count, so the last search gets fired */
618 for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++) {
619 if (empty($exclude_array[$cur_crit])) {
620 $next_mailbox = $mailbox_array[$cur_crit];
621 if ($next_mailbox != $cur_mailbox) {
622 $search_string = trim($search_string); /* Trim out last space */
40fbe929 623 if ($cur_mailbox == 'All Folders')
624 $search_mboxes = $mboxes_array;
625 else if ((!empty($sub_array[$cur_crit - 1])) || (!in_array($cur_mailbox, $mboxes_array)))
626 $search_mboxes = sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array);
cd33ec11 627 else
628 $search_mboxes = array($cur_mailbox);
629 foreach ($search_mboxes as $cur_mailbox) {
ff6f916c 630 s_debug_dump('C:SELECT:', $cur_mailbox);
27907482 631 sqimap_mailbox_select($imapConnection, $cur_mailbox);
c2d47d51 632 $thread_sort_messages = $allow_thread_sort && getPref($data_dir, $username, 'thread_' . $cur_mailbox);
633 if ($thread_sort_messages) {
436d7f4e 634 if ($sort_by_ref == 1)
635 $thread_algorithm = 'REFERENCES';
636 else
637 $thread_algorithm = 'ORDEREDSUBJECT';
c2d47d51 638 $found_msgs = sqimap_run_thread($imapConnection, $search_string, $search_charset, $thread_algorithm);
639 }
640 else
641 if (($allow_server_sort) && ($sort < 6)) {
642 $sort_criteria = sqimap_asearch_get_sort_criteria($cur_mailbox, $sort);
643 $found_msgs = sqimap_run_sort($imapConnection, $search_string, $search_charset, $sort_criteria);
644 }
645 else
646 $found_msgs = sqimap_run_search($imapConnection, $search_string, $search_charset);
5ab3c3fe 647 if (isset($mbox_msgs[$cur_mailbox])) {
648 if ($cur_biop == 'OR') /* Merge with previous results */
c2d47d51 649 $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], $found_msgs);
5ab3c3fe 650 else /* Intersect previous results */
c2d47d51 651 $mbox_msgs[$cur_mailbox] = array_values(array_intersect($found_msgs, $mbox_msgs[$cur_mailbox]));
cd33ec11 652 }
5ab3c3fe 653 else /* No previous results */
c2d47d51 654 $mbox_msgs[$cur_mailbox] = $found_msgs;
cd33ec11 655 if (empty($mbox_msgs[$cur_mailbox])) /* Can happen with intersect, and we need at the end a contiguous array */
656 unset($mbox_msgs[$cur_mailbox]);
657 }
658 $cur_mailbox = $next_mailbox;
659 $search_string = '';
660 }
661 if (isset($where_array[$cur_crit])) {
662 $criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset);
663 if (!empty($criteria)) {
664 $unop = $unop_array[$cur_crit];
665 if (!empty($unop))
666 $criteria = $unop . ' ' . $criteria;
667 /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
668 $next_biop = '';
669 for ($next_crit = $cur_crit+1; $next_crit <= count($where_array); $next_crit++) {
670 if (empty($exclude_array[$next_crit])) {
671 if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox)
5ab3c3fe 672 $next_biop = asearch_nz($biop_array[$next_crit]);
cd33ec11 673 break;
674 }
675 }
676 if ($next_biop == 'OR')
677 $criteria = $next_biop . ' ' . $criteria;
678 $search_string .= $criteria;
679 $cur_biop = asearch_nz($biop_array[$cur_crit]);
680 }
681 }
682 }
683 }
684 return $mbox_msgs;
685}
686
d6c32258 687?>