Added Flag/Unflag buttons. I have been up for 2 days straight. Please check for...
[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)) //php 4.0.6 compatibility
116 if (!in_array($response, array_keys($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 global $uid_support;
333
334 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
335 if ($search_charset != '')
336 $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
337 else
338 $query = 'SEARCH ALL ' . $search_string;
339 s_debug_dump('C:', $query);
340 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
341
342 /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
343 if (($search_charset != '') && (strtoupper($response) == 'NO')) {
344 $query = 'SEARCH CHARSET US-ASCII ALL ' . $search_string;
345 s_debug_dump('C:', $query);
346 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
347 }
348 if (strtoupper($response) != 'OK') {
349 sqimap_asearch_error_box($response, $query, $message);
350 return array();
351 }
352
353 // Keep going till we find the * SEARCH response
354 foreach ($readin as $readin_part) {
355 s_debug_dump('S:', $readin_part);
356 if (substr($readin_part, 0, 9) == '* SEARCH ') {
357 //EIMS returns multiple SEARCH responses, and this allowed according to Mark Crispin
358 $messagelist = sqimap_array_merge_unique($messagelist, preg_split("/ /", substr($readin_part, 9)));
359 }
360 }
361
362 if (empty($messagelist)) //Empty search response, ie '* SEARCH'
363 return array();
364
365 $cnt = count($messagelist);
366 for ($q = 0; $q < $cnt; $q++)
367 $id[$q] = trim($messagelist[$q]);
368 return $id;
369 }
370
371 /**
372 * Run the imap SORT command as defined in
373 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
374 * @param resource $imapConnection the current imap stream
375 * @param string $search_string the full search expression as defined in rfc 3501
376 * @param string $search_charset mandatory charset
377 * @param string $sort_criteria the full sort criteria expression eg "SUBJECT REVERSE DATE"
378 * @return array an IDs or UIDs array of matching messages or an empty array
379 */
380 function sqimap_run_sort($imapConnection, $search_string, $search_charset, $sort_criteria)
381 {
382 global $uid_support;
383
384 if ($search_charset == '')
385 $search_charset = 'US-ASCII';
386 $query = 'SORT (' . $sort_criteria . ') "' . strtoupper($search_charset) . '" ALL ' . $search_string;
387 s_debug_dump('C:', $query);
388 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
389 s_debug_dump('S:', $response);
390
391 /* 6.4 try US-ASCII charset if we received a tagged NO response (SHOULD be [BADCHARSET]) */
392 if (($search_charset != 'US-ASCII') && (strtoupper($response) == 'NO')) {
393 s_debug_dump('S:', $readin);
394 $query = 'SORT (' . $sort_criteria . ') US-ASCII ALL ' . $search_string;
395 s_debug_dump('C:', $query);
396 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
397 s_debug_dump('S:', $response);
398 }
399
400 if (strtoupper($response) != 'OK') {
401 s_debug_dump('S:', $readin);
402 // sqimap_asearch_error_box($response, $query, $message);
403 // return array();
404 return sqimap_run_search($imapConnection, $search_string, $search_charset); // Fell back to standard search
405 }
406
407 /* Keep going till we find the * SORT response */
408 foreach ($readin as $readin_part) {
409 s_debug_dump('S:', $readin_part);
410 if (substr($readin_part, 0, 7) == '* SORT ') {
411 //SORT returns untagged responses
412 $messagelist = sqimap_array_merge_unique($messagelist, preg_split("/ /", substr($readin_part, 7)));
413 }
414 }
415
416 if (empty($messagelist)) //Empty search response, ie '* SORT'
417 return array();
418
419 $cnt = count($messagelist);
420 for ($q = 0; $q < $cnt; $q++)
421 $id[$q] = trim($messagelist[$q]);
422 return $id;
423 }
424
425 /**
426 * Run the imap THREAD command as defined in
427 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
428 * @param resource $imapConnection the current imap stream
429 * @param string $search_string the full search expression as defined in rfc 3501
430 * @param string $search_charset mandatory charset
431 * @param string $thread_algorithm the threading algorithm "ORDEREDSUBJECT" or "REFERENCES"
432 * @return array an IDs or UIDs array of matching messages or an empty array
433 * @global array thread_new will be used by thread view in mailbox_display
434 * @global array server_sort_array will be used by thread view in mailbox_display
435 */
436 function sqimap_run_thread($imapConnection, $search_string, $search_charset, $thread_algorithm)
437 {
438 global $thread_new, $server_sort_array;
439
440 if (sqsession_is_registered('thread_new'))
441 sqsession_unregister('thread_new');
442 if (sqsession_is_registered('server_sort_array'))
443 sqsession_unregister('server_sort_array');
444
445 $thread_new = array();
446 $thread_new[0] = "";
447
448 $server_sort_array = array();
449
450 global $uid_support;
451
452 if ($search_charset == '')
453 $search_charset = 'US-ASCII';
454 $query = 'THREAD ' . $thread_algorithm . ' "' . strtoupper($search_charset) . '" ALL ' . $search_string;
455 s_debug_dump('C:', $query);
456 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
457 s_debug_dump('S:', $response);
458
459 /* 6.4 try US-ASCII charset if we received a tagged NO response (SHOULD be [BADCHARSET]) */
460 if (($search_charset != 'US-ASCII') && (strtoupper($response) == 'NO')) {
461 s_debug_dump('S:', $readin);
462 $query = 'THREAD ' . $thread_algorithm . ' US-ASCII ALL ' . $search_string;
463 s_debug_dump('C:', $query);
464 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
465 s_debug_dump('S:', $response);
466 }
467
468 if (strtoupper($response) != 'OK') {
469 s_debug_dump('S:', $readin);
470 if (empty($response)) { //imap server closed connection. We can't go further.
471 /* we should at this point:
472 - warn the user that the THREAD call has failed
473 - (offer him a way to) disconnect it permanently in the prefs
474 - perform the regular search instead or provide a way to do it in one click
475 */
476 global $sort, $mailbox, $php_self;
477 $message = _("The imap server failed to handle threading.");
478 $unthread = _("Click here to unset thread view for this mailbox and start again.");
479 if (preg_match('/^(.+)\?.+$/', $php_self, $regs))
480 $source_url = $regs[1];
481 else
482 $source_url = $php_self;
483 $link = '<a href=' . $source_url . '?sort=' . $sort . '&start_messages=1&set_thread=0&mailbox=' . urlencode($mailbox) . '>' . $unthread . '</a>';
484 sqimap_asearch_error_box($response, $query, $message, $link);
485 return array();
486 }
487 return sqimap_run_search($imapConnection, $search_string, $search_charset); // Fell back to standard search
488 }
489
490 /* Keep going till we find the * THREAD response */
491 foreach ($readin as $readin_part) {
492 s_debug_dump('S:', $readin_part);
493 if (substr($readin_part, 0, 9) == '* THREAD ') {
494 $thread_temp = preg_split("//", substr($readin_part, 9), -1, PREG_SPLIT_NO_EMPTY);
495 break; // Should be the last anyway
496 }
497 }
498
499 if (empty($thread_temp)) //Empty search response, ie '* THREAD'
500 return array();
501
502 $char_count = count($thread_temp);
503 $counter = 0;
504 $k = 0;
505 for ($i=0;$i<$char_count;$i++) {
506 if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
507 $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
508 }
509 elseif ($thread_temp[$i] == '(') {
510 $thread_new[$k] .= $thread_temp[$i];
511 $counter++;
512 }
513 elseif ($thread_temp[$i] == ')') {
514 if ($counter > 1) {
515 $thread_new[$k] .= $thread_temp[$i];
516 $counter = $counter - 1;
517 }
518 else {
519 $thread_new[$k] .= $thread_temp[$i];
520 $k++;
521 $thread_new[$k] = "";
522 $counter = $counter - 1;
523 }
524 }
525 }
526 sqsession_register($thread_new, 'thread_new');
527 $thread_new = array_reverse($thread_new);
528 $thread_list = implode(" ", $thread_new);
529 $thread_list = str_replace("(", " ", $thread_list);
530 $thread_list = str_replace(")", " ", $thread_list);
531 $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
532 $server_sort_array = $thread_list;
533 sqsession_register($server_sort_array, 'server_sort_array');
534 return $thread_list;
535 }
536
537 /**
538 * @global bool allow_charset_search user setting
539 * @global array languages sm languages array
540 * @global string squirrelmail_language user language setting
541 * @return string the user defined charset if $allow_charset_search is TRUE else zls ('')
542 */
543 function sqimap_asearch_get_charset()
544 {
545 global $allow_charset_search, $languages, $squirrelmail_language;
546
547 if ($allow_charset_search)
548 return $languages[$squirrelmail_language]['CHARSET'];
549 return '';
550 }
551
552 /**
553 * Convert sm internal sort to imap sort taking care of:
554 * - user defined date sorting (ARRIVAL vs DATE)
555 * - if the searched mailbox is the sent folder then TO is being used instead of FROM
556 * - reverse order by using REVERSE
557 * @param string $mailbox mailbox name to sort
558 * @param integer $sort_by sm sort criteria index
559 * @global bool internal_date_sort sort by arrival date instead of message date
560 * @global string sent_folder sent folder name
561 * @return string imap sort criteria
562 */
563 function sqimap_asearch_get_sort_criteria($mailbox, $sort_by)
564 {
565 global $internal_date_sort, $sent_folder;
566
567 $sort_opcodes = array ('DATE', 'FROM', 'SUBJECT', 'SIZE');
568 if ($internal_date_sort == true)
569 $sort_opcodes[0] = 'ARRIVAL';
570 // if (handleAsSent($mailbox))
571 // if (isSentFolder($mailbox))
572 if ($mailbox == $sent_folder)
573 $sort_opcodes[1] = 'TO';
574 return (($sort_by % 2) ? '' : 'REVERSE ') . $sort_opcodes[($sort_by >> 1) & 3];
575 }
576
577 /**
578 * @param string $cur_mailbox unformatted mailbox name
579 * @param array $boxes_unformatted selectable mailbox unformatted names array (reference)
580 * @return array sub mailboxes unformatted names
581 */
582 function sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array)
583 {
584 $sub_mboxes_array = array();
585 $boxcount = count($mboxes_array);
586 for ($boxnum=0; $boxnum < $boxcount; $boxnum++) {
587 if (isBoxBelow($mboxes_array[$boxnum], $cur_mailbox))
588 $sub_mboxes_array[] = $mboxes_array[$boxnum];
589 }
590 return $sub_mboxes_array;
591 }
592
593 /**
594 * Performs the search, given all the criteria, merging results for every mailbox
595 * @param resource $imapConnection
596 * @param array $mailbox_array
597 * @param array $biop_array
598 * @param array $unop_array
599 * @param array $where_array
600 * @param array $what_array
601 * @param array $exclude_array
602 * @param array $sub_array
603 * @param array $mboxes_array selectable unformatted mailboxes names
604 * @global bool allow_server_sort comes from config.php
605 * @global integer sort sm internal sort order
606 * @global bool allow_thread_sort comes from config.php
607 * @global bool thread_sort_messages does it really need to global?
608 * @global integer sort_by_ref thread by references
609 * @global string data_dir
610 * @global string username
611 * @return array $mbox_msgs array(mailbox => array(UIDs))
612 */
613 function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $sub_array, $mboxes_array)
614 {
615 global $allow_server_sort, $sort, $allow_thread_sort, $thread_sort_messages, $sort_by_ref;
616 global $data_dir, $username;
617
618 $search_charset = sqimap_asearch_get_charset();
619 $mbox_msgs = array();
620 $search_string = '';
621 $cur_mailbox = $mailbox_array[0];
622 $cur_biop = ''; /* Start with ALL */
623 /* We loop one more time than the real array count, so the last search gets fired */
624 for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++) {
625 if (empty($exclude_array[$cur_crit])) {
626 $next_mailbox = $mailbox_array[$cur_crit];
627 if ($next_mailbox != $cur_mailbox) {
628 $search_string = trim($search_string); /* Trim out last space */
629 if ($cur_mailbox == 'All Folders')
630 $search_mboxes = $mboxes_array;
631 else if ((!empty($sub_array[$cur_crit - 1])) || (!in_array($cur_mailbox, $mboxes_array)))
632 $search_mboxes = sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array);
633 else
634 $search_mboxes = array($cur_mailbox);
635 foreach ($search_mboxes as $cur_mailbox) {
636 s_debug_dump('C:SELECT:', $cur_mailbox);
637 sqimap_mailbox_select($imapConnection, $cur_mailbox);
638 $thread_sort_messages = $allow_thread_sort && getPref($data_dir, $username, 'thread_' . $cur_mailbox);
639 if ($thread_sort_messages) {
640 if ($sort_by_ref == 1)
641 $thread_algorithm = 'REFERENCES';
642 else
643 $thread_algorithm = 'ORDEREDSUBJECT';
644 $found_msgs = sqimap_run_thread($imapConnection, $search_string, $search_charset, $thread_algorithm);
645 }
646 else
647 if (($allow_server_sort) && ($sort < 6)) {
648 $sort_criteria = sqimap_asearch_get_sort_criteria($cur_mailbox, $sort);
649 $found_msgs = sqimap_run_sort($imapConnection, $search_string, $search_charset, $sort_criteria);
650 }
651 else
652 $found_msgs = sqimap_run_search($imapConnection, $search_string, $search_charset);
653 if (isset($mbox_msgs[$cur_mailbox])) {
654 if ($cur_biop == 'OR') /* Merge with previous results */
655 $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], $found_msgs);
656 else /* Intersect previous results */
657 $mbox_msgs[$cur_mailbox] = array_values(array_intersect($found_msgs, $mbox_msgs[$cur_mailbox]));
658 }
659 else /* No previous results */
660 $mbox_msgs[$cur_mailbox] = $found_msgs;
661 if (empty($mbox_msgs[$cur_mailbox])) /* Can happen with intersect, and we need at the end a contiguous array */
662 unset($mbox_msgs[$cur_mailbox]);
663 }
664 $cur_mailbox = $next_mailbox;
665 $search_string = '';
666 }
667 if (isset($where_array[$cur_crit])) {
668 $criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset);
669 if (!empty($criteria)) {
670 $unop = $unop_array[$cur_crit];
671 if (!empty($unop))
672 $criteria = $unop . ' ' . $criteria;
673 /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
674 $next_biop = '';
675 for ($next_crit = $cur_crit+1; $next_crit <= count($where_array); $next_crit++) {
676 if (empty($exclude_array[$next_crit])) {
677 if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox)
678 $next_biop = asearch_nz($biop_array[$next_crit]);
679 break;
680 }
681 }
682 if ($next_biop == 'OR')
683 $criteria = $next_biop . ' ' . $criteria;
684 $search_string .= $criteria;
685 $cur_biop = asearch_nz($biop_array[$cur_crit]);
686 }
687 }
688 }
689 }
690 return $mbox_msgs;
691 }
692
693 ?>