Be smarter with PHP numerical conversion, who knows if the previous code wouldn't...
[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 http://www.ietf.org/rfc/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 /* <sequence-set> => 'asequence', */ // Special handling, @see sqimap_asearch_build_criteria()
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 sqimap_asearch_build_criteria()
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 a convenient way to avoid spreading if (isset(... all over the code
145 * @param mixed $var any variable (reference)
146 * @param mixed $def default value to return if unset (default is zls (''), pass 0 if required)
147 * @return mixed $def if $var is unset, otherwise $var
148 */
149 function asearch_nz(&$var, $def = '')
150 {
151 if (isset($var))
152 return $var;
153 return $def;
154 }
155
156 /**
157 * This should give the same results as PHP 4 >= 4.3.0's html_entity_decode(),
158 * except it doesn't handle hex constructs
159 * @param string $string string to unhtmlentity()
160 * @return string decoded string
161 */
162 function asearch_unhtmlentities($string) {
163 $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES));
164 for ($i=127; $i<255; $i++) /* Add &#<dec>; entities */
165 $trans_tbl['&#' . $i . ';'] = chr($i);
166 return strtr($string, $trans_tbl);
167 /* I think the one above is quicker, though it should be benchmarked
168 $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
169 return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
170 */
171 }
172
173 /**
174 * Provide an easy way to dump the imap dialogue if $imap_asearch_debug_dump is TRUE
175 * @global imap_asearch_debug_dump
176 * @param string $var_name
177 * @param string $var_var
178 */
179 function s_debug_dump($var_name, $var_var)
180 {
181 global $imap_asearch_debug_dump;
182 if ($imap_asearch_debug_dump) {
183 if (function_exists('sm_print_r')) //Only exists since 1.4.2
184 sm_print_r($var_name, $var_var); //Better be the 'varargs' version ;)
185 else {
186 echo '<pre>';
187 echo htmlentities($var_name);
188 print_r($var_var);
189 echo '</pre>';
190 }
191 }
192 }
193
194 /** Encode a string to quoted or literal as defined in rfc 3501
195 *
196 * - § 4.3 String:
197 * A quoted string is a sequence of zero or more 7-bit characters,
198 * excluding CR and LF, with double quote (<">) characters at each end.
199 * - § 9. Formal Syntax:
200 * quoted-specials = DQUOTE / "\"
201 * @param string $what string to encode
202 * @param string $charset search charset used
203 * @return string encoded string
204 */
205 function sqimap_asearch_encode_string($what, $charset)
206 {
207 if (strtoupper($charset) == 'ISO-2022-JP') // This should be now handled in imap_utf7_local?
208 $what = mb_convert_encoding($what, 'JIS', 'auto');
209 //if (ereg("[\"\\\r\n\x80-\xff]", $what))
210 if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
211 return '{' . strlen($what) . "}\r\n" . $what; // 4.3 literal form
212 return '"' . $what . '"'; // 4.3 quoted string form
213 }
214
215 /**
216 * Parses a user date string into an rfc 3501 date string
217 * Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
218 * @global imap_asearch_months
219 * @param string user date
220 * @return array a preg_match-style array:
221 * - [0] = fully formatted rfc 3501 date string (<day number>-<US month TLA>-<4 digit year>)
222 * - [1] = day
223 * - [2] = month
224 * - [3] = year
225 */
226 function sqimap_asearch_parse_date($what)
227 {
228 global $imap_asearch_months;
229
230 $what = trim($what);
231 $what = ereg_replace('[ /\\.,]+', '-', $what);
232 if ($what) {
233 preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
234 if (count($what_parts) == 4) {
235 $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
236 /* if (!in_array($what_month, $imap_asearch_months)) {*/
237 foreach ($imap_asearch_months as $month_number => $month_code) {
238 if (($what_month == $month_number)
239 || ($what_month == $month_code)
240 || ($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
241 || ($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
242 ) {
243 $what_parts[2] = $month_number;
244 $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
245 break;
246 }
247 }
248 /* }*/
249 }
250 }
251 else
252 $what_parts = array();
253 return $what_parts;
254 }
255
256 /**
257 * Build one criteria sequence
258 * @global array imap_asearch_opcodes
259 * @param string $opcode search opcode
260 * @param string $what opcode argument
261 * @param string $charset search charset
262 * @return string one full criteria sequence
263 */
264 function sqimap_asearch_build_criteria($opcode, $what, $charset)
265 {
266 global $imap_asearch_opcodes;
267
268 $criteria = '';
269 switch ($imap_asearch_opcodes[$opcode]) {
270 default:
271 case 'anum':
272 $what = str_replace(' ', '', $what);
273 $what = ereg_replace('[^0-9]+[^KMG]$', '', strtoupper($what));
274 if ($what != '') {
275 switch (substr($what, -1)) {
276 case 'G':
277 $what = substr($what, 0, -1) << 30;
278 break;
279 case 'M':
280 $what = substr($what, 0, -1) << 20;
281 break;
282 case 'K':
283 $what = substr($what, 0, -1) << 10;
284 break;
285 }
286 $criteria = $opcode . ' ' . $what . ' ';
287 }
288 break;
289 case '': //aflag
290 $criteria = $opcode . ' ';
291 break;
292 case 'afield': /* HEADER field-name: field-body */
293 preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
294 if (count($what_parts) == 3)
295 $criteria = $opcode . ' ' .
296 sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
297 sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
298 break;
299 case 'adate':
300 $what_parts = sqimap_asearch_parse_date($what);
301 if (isset($what_parts[0]))
302 $criteria = $opcode . ' ' . $what_parts[0] . ' ';
303 break;
304 case 'akeyword':
305 case 'astring':
306 $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
307 break;
308 case 'asequence':
309 $what = ereg_replace('[^0-9:\(\)]+', '', $what);
310 if ($what != '')
311 $criteria = $opcode . ' ' . $what . ' ';
312 break;
313 }
314 return $criteria;
315 }
316
317 /**
318 * Another way to do array_values(array_unique(array_merge($to, $from)));
319 * @param array $to to array (reference)
320 * @param array $from from array
321 * @return array uniquely merged array
322 */
323 function sqimap_array_merge_unique(&$to, $from)
324 {
325 if (empty($to))
326 return $from;
327 $count = count($from);
328 for ($i = 0; $i < $count; $i++) {
329 if (!in_array($from[$i], $to))
330 $to[] = $from[$i];
331 }
332 return $to;
333 }
334
335 /**
336 * Run the imap SEARCH command as defined in rfc 3501
337 * @link http://www.ietf.org/rfc/rfc3501.txt
338 * @param resource $imapConnection the current imap stream
339 * @param string $search_string the full search expression eg "ALL RECENT"
340 * @param string $search_charset charset to use or zls ('')
341 * @return array an IDs or UIDs array of matching messages or an empty array
342 */
343 function sqimap_run_search($imapConnection, $search_string, $search_charset)
344 {
345 /* 6.4.4 try OPTIONAL [CHARSET] specification first */
346 if ($search_charset != '')
347 $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
348 else
349 $query = 'SEARCH ALL ' . $search_string;
350 s_debug_dump('C:', $query);
351 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
352
353 /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
354 if (($search_charset != '') && (strtoupper($response) == 'NO')) {
355 $query = 'SEARCH CHARSET US-ASCII ALL ' . $search_string;
356 s_debug_dump('C:', $query);
357 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
358 }
359 if (strtoupper($response) != 'OK') {
360 sqimap_asearch_error_box($response, $query, $message);
361 return array();
362 }
363
364 // Keep going till we find the * SEARCH response
365 foreach ($readin as $readin_part) {
366 s_debug_dump('S:', $readin_part);
367 if (substr($readin_part, 0, 9) == '* SEARCH ') {
368 //EIMS returns multiple SEARCH responses, and this allowed according to Mark Crispin
369 $messagelist = sqimap_array_merge_unique($messagelist, preg_split("/ /", substr($readin_part, 9)));
370 }
371 }
372
373 if (empty($messagelist)) //Empty search response, ie '* SEARCH'
374 return array();
375
376 $cnt = count($messagelist);
377 for ($q = 0; $q < $cnt; $q++)
378 $id[$q] = trim($messagelist[$q]);
379 return $id;
380 }
381
382 /**
383 * Run the imap SORT command as defined in
384 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
385 * @param resource $imapConnection the current imap stream
386 * @param string $search_string the full search expression as defined in rfc 3501
387 * @param string $search_charset mandatory charset
388 * @param string $sort_criteria the full sort criteria expression eg "SUBJECT REVERSE DATE"
389 * @return array an IDs or UIDs array of matching messages or an empty array
390 */
391 function sqimap_run_sort($imapConnection, $search_string, $search_charset, $sort_criteria)
392 {
393 if ($search_charset == '')
394 $search_charset = 'US-ASCII';
395 $query = 'SORT (' . $sort_criteria . ') "' . strtoupper($search_charset) . '" ALL ' . $search_string;
396 s_debug_dump('C:', $query);
397 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
398 s_debug_dump('S:', $response);
399
400 /* 6.4 try US-ASCII charset if we received a tagged NO response (SHOULD be [BADCHARSET]) */
401 if (($search_charset != 'US-ASCII') && (strtoupper($response) == 'NO')) {
402 s_debug_dump('S:', $readin);
403 $query = 'SORT (' . $sort_criteria . ') US-ASCII ALL ' . $search_string;
404 s_debug_dump('C:', $query);
405 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
406 s_debug_dump('S:', $response);
407 }
408
409 if (strtoupper($response) != 'OK') {
410 s_debug_dump('S:', $readin);
411 // sqimap_asearch_error_box($response, $query, $message);
412 // return array();
413 return sqimap_run_search($imapConnection, $search_string, $search_charset); // Fell back to standard search
414 }
415
416 /* Keep going till we find the * SORT response */
417 foreach ($readin as $readin_part) {
418 s_debug_dump('S:', $readin_part);
419 if (substr($readin_part, 0, 7) == '* SORT ') {
420 //SORT returns untagged responses
421 $messagelist = sqimap_array_merge_unique($messagelist, preg_split("/ /", substr($readin_part, 7)));
422 }
423 }
424
425 if (empty($messagelist)) //Empty search response, ie '* SORT'
426 return array();
427
428 $cnt = count($messagelist);
429 for ($q = 0; $q < $cnt; $q++)
430 $id[$q] = trim($messagelist[$q]);
431 return $id;
432 }
433
434 /**
435 * Run the imap THREAD command as defined in
436 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
437 * @param resource $imapConnection the current imap stream
438 * @param string $search_string the full search expression as defined in rfc 3501
439 * @param string $search_charset mandatory charset
440 * @param string $thread_algorithm the threading algorithm "ORDEREDSUBJECT" or "REFERENCES"
441 * @return array an IDs or UIDs array of matching messages or an empty array
442 * @global array thread_new will be used by thread view in mailbox_display
443 * @global array server_sort_array will be used by thread view in mailbox_display
444 */
445 function sqimap_run_thread($imapConnection, $search_string, $search_charset, $thread_algorithm)
446 {
447 global $thread_new, $server_sort_array;
448
449 if (sqsession_is_registered('thread_new'))
450 sqsession_unregister('thread_new');
451 if (sqsession_is_registered('server_sort_array'))
452 sqsession_unregister('server_sort_array');
453
454 $thread_new = array();
455 $thread_new[0] = "";
456
457 $server_sort_array = array();
458
459 if ($search_charset == '')
460 $search_charset = 'US-ASCII';
461 $query = 'THREAD ' . $thread_algorithm . ' "' . strtoupper($search_charset) . '" ALL ' . $search_string;
462 s_debug_dump('C:', $query);
463 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
464 s_debug_dump('S:', $response);
465
466 /* 6.4 try US-ASCII charset if we received a tagged NO response (SHOULD be [BADCHARSET]) */
467 if (($search_charset != 'US-ASCII') && (strtoupper($response) == 'NO')) {
468 s_debug_dump('S:', $readin);
469 $query = 'THREAD ' . $thread_algorithm . ' US-ASCII ALL ' . $search_string;
470 s_debug_dump('C:', $query);
471 $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
472 s_debug_dump('S:', $response);
473 }
474
475 if (strtoupper($response) != 'OK') {
476 s_debug_dump('S:', $readin);
477 if (empty($response)) { //imap server closed connection. We can't go further.
478 /* we should at this point:
479 - warn the user that the THREAD call has failed
480 - (offer him a way to) disconnect it permanently in the prefs
481 - perform the regular search instead or provide a way to do it in one click
482 */
483 global $sort, $mailbox, $php_self;
484 $message = _("The imap server failed to handle threading.");
485 $unthread = _("Click here to unset thread view for this mailbox and start again.");
486 if (preg_match('/^(.+)\?.+$/', $php_self, $regs))
487 $source_url = $regs[1];
488 else
489 $source_url = $php_self;
490 $link = '<a href=' . $source_url . '?sort=' . $sort . '&start_messages=1&set_thread=0&mailbox=' . urlencode($mailbox) . '>' . $unthread . '</a>';
491 sqimap_asearch_error_box($response, $query, $message, $link);
492 return array();
493 }
494 return sqimap_run_search($imapConnection, $search_string, $search_charset); // Fell back to standard search
495 }
496
497 /* Keep going till we find the * THREAD response */
498 foreach ($readin as $readin_part) {
499 s_debug_dump('S:', $readin_part);
500 if (substr($readin_part, 0, 9) == '* THREAD ') {
501 $thread_temp = preg_split("//", substr($readin_part, 9), -1, PREG_SPLIT_NO_EMPTY);
502 break; // Should be the last anyway
503 }
504 }
505
506 if (empty($thread_temp)) //Empty search response, ie '* THREAD'
507 return array();
508
509 $char_count = count($thread_temp);
510 $counter = 0;
511 $k = 0;
512 for ($i=0;$i<$char_count;$i++) {
513 if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
514 $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
515 }
516 elseif ($thread_temp[$i] == '(') {
517 $thread_new[$k] .= $thread_temp[$i];
518 $counter++;
519 }
520 elseif ($thread_temp[$i] == ')') {
521 if ($counter > 1) {
522 $thread_new[$k] .= $thread_temp[$i];
523 $counter = $counter - 1;
524 }
525 else {
526 $thread_new[$k] .= $thread_temp[$i];
527 $k++;
528 $thread_new[$k] = "";
529 $counter = $counter - 1;
530 }
531 }
532 }
533 sqsession_register($thread_new, 'thread_new');
534 $thread_new = array_reverse($thread_new);
535 $thread_list = implode(" ", $thread_new);
536 $thread_list = str_replace("(", " ", $thread_list);
537 $thread_list = str_replace(")", " ", $thread_list);
538 $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
539 $server_sort_array = $thread_list;
540 sqsession_register($server_sort_array, 'server_sort_array');
541 return $thread_list;
542 }
543
544 /**
545 * @global bool allow_charset_search user setting
546 * @global array languages sm languages array
547 * @global string squirrelmail_language user language setting
548 * @return string the user defined charset if $allow_charset_search is TRUE else zls ('')
549 */
550 function sqimap_asearch_get_charset()
551 {
552 global $allow_charset_search, $languages, $squirrelmail_language;
553
554 if ($allow_charset_search)
555 return $languages[$squirrelmail_language]['CHARSET'];
556 return '';
557 }
558
559 /**
560 * Convert sm internal sort to imap sort taking care of:
561 * - user defined date sorting (ARRIVAL vs DATE)
562 * - if the searched mailbox is the sent folder then TO is being used instead of FROM
563 * - reverse order by using REVERSE
564 * @param string $mailbox mailbox name to sort
565 * @param integer $sort_by sm sort criteria index
566 * @global bool internal_date_sort sort by arrival date instead of message date
567 * @global string sent_folder sent folder name
568 * @return string imap sort criteria
569 */
570 function sqimap_asearch_get_sort_criteria($mailbox, $sort_by)
571 {
572 global $internal_date_sort, $sent_folder;
573
574 $sort_opcodes = array ('DATE', 'FROM', 'SUBJECT', 'SIZE');
575 if ($internal_date_sort == true)
576 $sort_opcodes[0] = 'ARRIVAL';
577 // if (handleAsSent($mailbox))
578 // if (isSentFolder($mailbox))
579 if ($mailbox == $sent_folder)
580 $sort_opcodes[1] = 'TO';
581 return (($sort_by % 2) ? '' : 'REVERSE ') . $sort_opcodes[($sort_by >> 1) & 3];
582 }
583
584 /**
585 * @param string $cur_mailbox unformatted mailbox name
586 * @param array $boxes_unformatted selectable mailbox unformatted names array (reference)
587 * @return array sub mailboxes unformatted names
588 */
589 function sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array)
590 {
591 $sub_mboxes_array = array();
592 $boxcount = count($mboxes_array);
593 for ($boxnum=0; $boxnum < $boxcount; $boxnum++) {
594 if (isBoxBelow($mboxes_array[$boxnum], $cur_mailbox))
595 $sub_mboxes_array[] = $mboxes_array[$boxnum];
596 }
597 return $sub_mboxes_array;
598 }
599
600 /**
601 * Performs the search, given all the criteria, merging results for every mailbox
602 * @param resource $imapConnection
603 * @param array $mailbox_array
604 * @param array $biop_array
605 * @param array $unop_array
606 * @param array $where_array
607 * @param array $what_array
608 * @param array $exclude_array
609 * @param array $sub_array
610 * @param array $mboxes_array selectable unformatted mailboxes names
611 * @global bool allow_server_sort comes from config.php
612 * @global integer sort sm internal sort order
613 * @global bool allow_thread_sort comes from config.php
614 * @global bool thread_sort_messages does it really need to global?
615 * @global integer sort_by_ref thread by references
616 * @global string data_dir
617 * @global string username
618 * @return array $mbox_msgs array(mailbox => array(UIDs))
619 */
620 function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $sub_array, $mboxes_array)
621 {
622 global $allow_server_sort, $sort, $allow_thread_sort, $thread_sort_messages, $sort_by_ref;
623 global $data_dir, $username;
624
625 $search_charset = sqimap_asearch_get_charset();
626 $mbox_msgs = array();
627 $search_string = '';
628 $cur_mailbox = $mailbox_array[0];
629 $cur_biop = ''; /* Start with ALL */
630 /* We loop one more time than the real array count, so the last search gets fired */
631 for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++) {
632 if (empty($exclude_array[$cur_crit])) {
633 $next_mailbox = $mailbox_array[$cur_crit];
634 if ($next_mailbox != $cur_mailbox) {
635 $search_string = trim($search_string); /* Trim out last space */
636 if ($cur_mailbox == 'All Folders')
637 $search_mboxes = $mboxes_array;
638 else if ((!empty($sub_array[$cur_crit - 1])) || (!in_array($cur_mailbox, $mboxes_array)))
639 $search_mboxes = sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array);
640 else
641 $search_mboxes = array($cur_mailbox);
642 foreach ($search_mboxes as $cur_mailbox) {
643 s_debug_dump('C:SELECT:', $cur_mailbox);
644 sqimap_mailbox_select($imapConnection, $cur_mailbox);
645 $thread_sort_messages = $allow_thread_sort && getPref($data_dir, $username, 'thread_' . $cur_mailbox);
646 if ($thread_sort_messages) {
647 if ($sort_by_ref == 1)
648 $thread_algorithm = 'REFERENCES';
649 else
650 $thread_algorithm = 'ORDEREDSUBJECT';
651 $found_msgs = sqimap_run_thread($imapConnection, $search_string, $search_charset, $thread_algorithm);
652 }
653 else
654 if (($allow_server_sort) && ($sort < 6)) {
655 $sort_criteria = sqimap_asearch_get_sort_criteria($cur_mailbox, $sort);
656 $found_msgs = sqimap_run_sort($imapConnection, $search_string, $search_charset, $sort_criteria);
657 }
658 else
659 $found_msgs = sqimap_run_search($imapConnection, $search_string, $search_charset);
660 if (isset($mbox_msgs[$cur_mailbox])) {
661 if ($cur_biop == 'OR') /* Merge with previous results */
662 $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], $found_msgs);
663 else /* Intersect previous results */
664 $mbox_msgs[$cur_mailbox] = array_values(array_intersect($found_msgs, $mbox_msgs[$cur_mailbox]));
665 }
666 else /* No previous results */
667 $mbox_msgs[$cur_mailbox] = $found_msgs;
668 if (empty($mbox_msgs[$cur_mailbox])) /* Can happen with intersect, and we need at the end a contiguous array */
669 unset($mbox_msgs[$cur_mailbox]);
670 }
671 $cur_mailbox = $next_mailbox;
672 $search_string = '';
673 }
674 if (isset($where_array[$cur_crit])) {
675 $criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset);
676 if (!empty($criteria)) {
677 $unop = $unop_array[$cur_crit];
678 if (!empty($unop))
679 $criteria = $unop . ' ' . $criteria;
680 /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
681 $next_biop = '';
682 for ($next_crit = $cur_crit+1; $next_crit <= count($where_array); $next_crit++) {
683 if (empty($exclude_array[$next_crit])) {
684 if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox)
685 $next_biop = asearch_nz($biop_array[$next_crit]);
686 break;
687 }
688 }
689 if ($next_biop == 'OR')
690 $criteria = $next_biop . ' ' . $criteria;
691 $search_string .= $criteria;
692 $cur_biop = asearch_nz($biop_array[$cur_crit]);
693 }
694 }
695 }
696 }
697 return $mbox_msgs;
698 }
699
700 ?>