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