imap_asearch.php 21 KB

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