imap_asearch.php 24 KB

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