this looks better ;)
[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 * 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 ftp://ftp.rfc-editor.org/in-notes/rfc3501.txt
18 * @author Alex Lemaresquier - Brainstorm - alex at brainstorm.fr
19 */
20
21 /** This functionality requires the IMAP and date functions */
22 require_once(SM_PATH . 'functions/imap_general.php');
23 require_once(SM_PATH . 'functions/date.php');
24
25 /** Set to TRUE to dump the imap dialogue
26 * @global bool $imap_asearch_debug_dump
27 */
28 $imap_asearch_debug_dump = FALSE;
29
30 /** Imap SEARCH keys
31 * @global array $imap_asearch_opcodes
32 */
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
72 /** Imap SEARCH month names encoding
73 * @global array $imap_asearch_months
74 */
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
90 /** Error message titles according to imap server returned code
91 * @global array $imap_error_titles
92 */
93 $imap_error_titles = array(
94 'OK' => '',
95 'NO' => _("ERROR : Could not complete request."),
96 'BAD' => _("ERROR : Bad or malformed request."),
97 'BYE' => _("ERROR : Imap server closed the connection."),
98 '' => _("ERROR : Connection dropped by imap-server.")
99 );
100
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
108 * @param string $message an optional error message
109 * @param string $link an optional link to try again
110 */
111 //@global array color sm colors array
112 function sqimap_asearch_error_box($response, $query, $message, $link = '')
113 {
114 global $imap_error_titles;
115
116 if (!array_key_exists($response, $imap_error_titles))
117 $title = _("ERROR : Unknown imap response.");
118 else
119 $title = $imap_error_titles[$response];
120 if ($link == '')
121 $message_title = _("Reason Given: ");
122 else
123 $message_title = _("Possible reason : ");
124 if (function_exists('sqimap_error_box'))
125 sqimap_error_box($title, $query, $message_title, $message, $link);
126 else { //Straight copy of 1.5 imap_general.php:sqimap_error_box(). Can be removed at a later time
127 global $color;
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);
136 if ($link != '')
137 $string .= $link;
138 $string .= "</font><br>\n";
139 error_box($string,$color);
140 }
141 }
142
143 /**
144 * This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc!
145 * @param mixed $var any variable (reference)
146 * @return mixed zls ('') if $var is not defined, otherwise $var
147 */
148 function asearch_nz(&$var)
149 {
150 if (isset($var))
151 return $var;
152 return '';
153 }
154
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
158 * @param string $string string to unhtmlentity()
159 * @return string decoded string
160 */
161 function 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
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 */
178 function s_debug_dump($var_name, $var_var)
179 {
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 }
191 }
192
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 */
204 function sqimap_asearch_encode_string($what, $charset)
205 {
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 (ereg("[\"\\\r\n\x80-\xff]", $what))
209 if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
210 return '{' . strlen($what) . "}\r\n" . $what; // 4.3 literal form
211 return '"' . $what . '"'; // 4.3 quoted string form
212 }
213
214 /**
215 * Parses a user date string into an rfc 3501 date string
216 * Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
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
224 */
225 function sqimap_asearch_parse_date($what)
226 {
227 global $imap_asearch_months;
228
229 $what = trim($what);
230 $what = ereg_replace('[ /\\.,]+', '-', $what);
231 if ($what) {
232 preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
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
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 */
263 function sqimap_asearch_build_criteria($opcode, $what, $charset)
264 {
265 global $imap_asearch_opcodes;
266
267 $criteria = '';
268 switch ($imap_asearch_opcodes[$opcode]) {
269 default:
270 case 'anum':
271 // $what = str_replace(' ', '', $what);
272 $what = ereg_replace('[^0-9]+', '', $what);
273 if ($what != '')
274 $criteria = $opcode . ' ' . $what . ' ';
275 break;
276 case '': //aflag
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 . ' ' .
283 sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
284 sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
285 break;
286 case 'adate':
287 $what_parts = sqimap_asearch_parse_date($what);
288 if (isset($what_parts[0]))
289 $criteria = $opcode . ' ' . $what_parts[0] . ' ';
290 break;
291 case 'akeyword':
292 case 'astring':
293 $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
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
304 /**
305 * Another way to do array_values(array_unique(array_merge($to, $from)));
306 * @param array $to to array (reference)
307 * @param array $from from array
308 * @return array uniquely merged array
309 */
310 function sqimap_array_merge_unique(&$to, $from)
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
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 */
330 function sqimap_run_search($imapConnection, $search_string, $search_charset)
331 {
332 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
333 if ($search_charset != '')
334 $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
335 else
336 $query = 'SEARCH ALL ' . $search_string;
337 s_debug_dump('C:', $query);
338 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
339
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;
343 s_debug_dump('C:', $query);
344 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
345 }
346 if (strtoupper($response) != 'OK') {
347 sqimap_asearch_error_box($response, $query, $message);
348 return array();
349 }
350
351 // Keep going till we find the * SEARCH response
352 foreach ($readin as $readin_part) {
353 s_debug_dump('S:', $readin_part);
354 if (substr($readin_part, 0, 9) == '* SEARCH ') {
355 //EIMS returns multiple SEARCH responses, and this allowed according to Mark Crispin
356 $messagelist = sqimap_array_merge_unique($messagelist, preg_split("/ /", substr($readin_part, 9)));
357 }
358 }
359
360 if (empty($messagelist)) //Empty search response, ie '* SEARCH'
361 return array();
362
363 $cnt = count($messagelist);
364 for ($q = 0; $q < $cnt; $q++)
365 $id[$q] = trim($messagelist[$q]);
366 return $id;
367 }
368
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 */
378 function sqimap_run_sort($imapConnection, $search_string, $search_charset, $sort_criteria)
379 {
380 if ($search_charset == '')
381 $search_charset = 'US-ASCII';
382 $query = 'SORT (' . $sort_criteria . ') "' . strtoupper($search_charset) . '" ALL ' . $search_string;
383 s_debug_dump('C:', $query);
384 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
385 s_debug_dump('S:', $response);
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')) {
389 s_debug_dump('S:', $readin);
390 $query = 'SORT (' . $sort_criteria . ') US-ASCII ALL ' . $search_string;
391 s_debug_dump('C:', $query);
392 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
393 s_debug_dump('S:', $response);
394 }
395
396 if (strtoupper($response) != 'OK') {
397 s_debug_dump('S:', $readin);
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
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 ') {
407 //SORT returns untagged responses
408 $messagelist = sqimap_array_merge_unique($messagelist, preg_split("/ /", substr($readin_part, 7)));
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
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
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
431 */
432 function 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
446 if ($search_charset == '')
447 $search_charset = 'US-ASCII';
448 $query = 'THREAD ' . $thread_algorithm . ' "' . strtoupper($search_charset) . '" ALL ' . $search_string;
449 s_debug_dump('C:', $query);
450 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
451 s_debug_dump('S:', $response);
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')) {
455 s_debug_dump('S:', $readin);
456 $query = 'THREAD ' . $thread_algorithm . ' US-ASCII ALL ' . $search_string;
457 s_debug_dump('C:', $query);
458 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
459 s_debug_dump('S:', $response);
460 }
461
462 if (strtoupper($response) != 'OK') {
463 s_debug_dump('S:', $readin);
464 if (empty($response)) { //imap server closed connection. We can't go further.
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 */
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
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
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 */
537 function 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
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
552 * @param integer $sort_by sm sort criteria index
553 * @global bool internal_date_sort sort by arrival date instead of message date
554 * @global string sent_folder sent folder name
555 * @return string imap sort criteria
556 */
557 function sqimap_asearch_get_sort_criteria($mailbox, $sort_by)
558 {
559 global $internal_date_sort, $sent_folder;
560
561 $sort_opcodes = array ('DATE', 'FROM', 'SUBJECT', 'SIZE');
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';
568 return (($sort_by % 2) ? '' : 'REVERSE ') . $sort_opcodes[($sort_by >> 1) & 3];
569 }
570
571 /**
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 */
576 function 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 /**
588 * Performs the search, given all the criteria, merging results for every mailbox
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
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
605 * @return array $mbox_msgs array(mailbox => array(UIDs))
606 */
607 function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $sub_array, $mboxes_array)
608 {
609 global $allow_server_sort, $sort, $allow_thread_sort, $thread_sort_messages, $sort_by_ref;
610 global $data_dir, $username;
611
612 $search_charset = sqimap_asearch_get_charset();
613 $mbox_msgs = array();
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 */
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);
627 else
628 $search_mboxes = array($cur_mailbox);
629 foreach ($search_mboxes as $cur_mailbox) {
630 s_debug_dump('C:SELECT:', $cur_mailbox);
631 sqimap_mailbox_select($imapConnection, $cur_mailbox);
632 $thread_sort_messages = $allow_thread_sort && getPref($data_dir, $username, 'thread_' . $cur_mailbox);
633 if ($thread_sort_messages) {
634 if ($sort_by_ref == 1)
635 $thread_algorithm = 'REFERENCES';
636 else
637 $thread_algorithm = 'ORDEREDSUBJECT';
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);
647 if (isset($mbox_msgs[$cur_mailbox])) {
648 if ($cur_biop == 'OR') /* Merge with previous results */
649 $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], $found_msgs);
650 else /* Intersect previous results */
651 $mbox_msgs[$cur_mailbox] = array_values(array_intersect($found_msgs, $mbox_msgs[$cur_mailbox]));
652 }
653 else /* No previous results */
654 $mbox_msgs[$cur_mailbox] = $found_msgs;
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)
672 $next_biop = asearch_nz($biop_array[$next_crit]);
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
687 ?>