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