imap_asearch.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. <?php
  2. /**
  3. * imap_search.php
  4. *
  5. * Copyright (c) 1999-2004 The SquirrelMail Project Team
  6. * Licensed under the GNU GPL. For full terms see the file COPYING.
  7. *
  8. * IMAP asearch routines
  9. *
  10. * Subfolder search idea from Patch #806075 by Thomas Pohl xraven at users.sourceforge.net. Thanks Thomas!
  11. *
  12. * @version $Id$
  13. * @package squirrelmail
  14. * @subpackage imap
  15. * @see search.php
  16. * @link ftp://ftp.rfc-editor.org/in-notes/rfc3501.txt
  17. * @author Alex Lemaresquier - Brainstorm - alex at brainstorm.fr
  18. */
  19. /** This functionality requires the IMAP and date functions */
  20. require_once(SM_PATH . 'functions/imap_general.php');
  21. require_once(SM_PATH . 'functions/date.php');
  22. /** Set to TRUE to dump the imap dialogue
  23. * @global bool $imap_asearch_debug_dump
  24. */
  25. $imap_asearch_debug_dump = FALSE;
  26. /** Imap SEARCH keys
  27. * @global array $imap_asearch_opcodes
  28. */
  29. $imap_asearch_opcodes = array(
  30. /* <message set> => 'asequence', */
  31. /*'ALL' is binary operator */
  32. 'ANSWERED' => '',
  33. 'BCC' => 'astring',
  34. 'BEFORE' => 'adate',
  35. 'BODY' => 'astring',
  36. 'CC' => 'astring',
  37. 'DELETED' => '',
  38. 'DRAFT' => '',
  39. 'FLAGGED' => '',
  40. 'FROM' => 'astring',
  41. 'HEADER' => 'afield', /* Special syntax for this one, see below */
  42. 'KEYWORD' => 'akeyword',
  43. 'LARGER' => 'anum',
  44. 'NEW' => '',
  45. /*'NOT' is unary operator */
  46. 'OLD' => '',
  47. 'ON' => 'adate',
  48. /*'OR' is binary operator */
  49. 'RECENT' => '',
  50. 'SEEN' => '',
  51. 'SENTBEFORE' => 'adate',
  52. 'SENTON' => 'adate',
  53. 'SENTSINCE' => 'adate',
  54. 'SINCE' => 'adate',
  55. 'SMALLER' => 'anum',
  56. 'SUBJECT' => 'astring',
  57. 'TEXT' => 'astring',
  58. 'TO' => 'astring',
  59. 'UID' => 'asequence',
  60. 'UNANSWERED' => '',
  61. 'UNDELETED' => '',
  62. 'UNDRAFT' => '',
  63. 'UNFLAGGED' => '',
  64. 'UNKEYWORD' => 'akeyword',
  65. 'UNSEEN' => ''
  66. );
  67. /** Imap SEARCH month names encoding
  68. * @global array $imap_asearch_months
  69. */
  70. $imap_asearch_months = array(
  71. '01' => 'jan',
  72. '02' => 'feb',
  73. '03' => 'mar',
  74. '04' => 'apr',
  75. '05' => 'may',
  76. '06' => 'jun',
  77. '07' => 'jul',
  78. '08' => 'aug',
  79. '09' => 'sep',
  80. '10' => 'oct',
  81. '11' => 'nov',
  82. '12' => 'dec'
  83. );
  84. /** Error message titles according to imap server returned code
  85. * @global array $imap_error_titles
  86. */
  87. $imap_error_titles = array(
  88. 'OK' => '',
  89. 'NO' => _("ERROR : Could not complete request."),
  90. 'BAD' => _("ERROR : Bad or malformed request."),
  91. 'BYE' => _("ERROR : Imap server closed the connection."),
  92. '' => _("ERROR : Connection dropped by imap-server.")
  93. );
  94. /**
  95. * Function to display an error related to an IMAP-query.
  96. * We need to do our own error management since we may receive NO responses on purpose (even BAD with SORT or THREAD)
  97. * so we call sqimap_error_box() if the function exists (sm >= 1.5) or use our own embedded code
  98. * @global array imap_error_titles
  99. * @param string $response the imap server response code
  100. * @param string $query the failed query
  101. * @param string $message an optional error message
  102. * @param string $link an optional link to try again
  103. */
  104. //@global array color sm colors array
  105. function sqimap_asearch_error_box($response, $query, $message, $link = '')
  106. {
  107. global $imap_error_titles;
  108. if (!array_key_exists($response, $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. /* 6.4.4 try OPTIONAL [CHARSET] specification first */
  315. if ($search_charset != '')
  316. $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
  317. else
  318. $query = 'SEARCH ALL ' . $search_string;
  319. s_debug_dump('C:', $query);
  320. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  321. /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
  322. if (($search_charset != '') && (strtoupper($response) == 'NO')) {
  323. $query = 'SEARCH CHARSET US-ASCII ALL ' . $search_string;
  324. s_debug_dump('C:', $query);
  325. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  326. }
  327. if (strtoupper($response) != 'OK') {
  328. sqimap_asearch_error_box($response, $query, $message);
  329. return array();
  330. }
  331. // Keep going till we find the * SEARCH response
  332. foreach ($readin as $readin_part) {
  333. s_debug_dump('S:', $readin_part);
  334. if (substr($readin_part, 0, 9) == '* SEARCH ') {
  335. //EIMS returns multiple SEARCH responses, and this allowed according to Mark Crispin
  336. $messagelist = sqimap_array_merge_unique($messagelist, preg_split("/ /", substr($readin_part, 9)));
  337. }
  338. }
  339. if (empty($messagelist)) //Empty search response, ie '* SEARCH'
  340. return array();
  341. $cnt = count($messagelist);
  342. for ($q = 0; $q < $cnt; $q++)
  343. $id[$q] = trim($messagelist[$q]);
  344. return $id;
  345. }
  346. /**
  347. * Run the imap SORT command as defined in
  348. * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
  349. * @param resource $imapConnection the current imap stream
  350. * @param string $search_string the full search expression as defined in rfc 3501
  351. * @param string $search_charset mandatory charset
  352. * @param string $sort_criteria the full sort criteria expression eg "SUBJECT REVERSE DATE"
  353. * @return array an IDs or UIDs array of matching messages or an empty array
  354. */
  355. function sqimap_run_sort($imapConnection, $search_string, $search_charset, $sort_criteria)
  356. {
  357. if ($search_charset == '')
  358. $search_charset = 'US-ASCII';
  359. $query = 'SORT (' . $sort_criteria . ') "' . strtoupper($search_charset) . '" ALL ' . $search_string;
  360. s_debug_dump('C:', $query);
  361. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  362. s_debug_dump('S:', $response);
  363. /* 6.4 try US-ASCII charset if we received a tagged NO response (SHOULD be [BADCHARSET]) */
  364. if (($search_charset != 'US-ASCII') && (strtoupper($response) == 'NO')) {
  365. s_debug_dump('S:', $readin);
  366. $query = 'SORT (' . $sort_criteria . ') US-ASCII ALL ' . $search_string;
  367. s_debug_dump('C:', $query);
  368. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  369. s_debug_dump('S:', $response);
  370. }
  371. if (strtoupper($response) != 'OK') {
  372. s_debug_dump('S:', $readin);
  373. // sqimap_asearch_error_box($response, $query, $message);
  374. // return array();
  375. return sqimap_run_search($imapConnection, $search_string, $search_charset); // Fell back to standard search
  376. }
  377. /* Keep going till we find the * SORT response */
  378. foreach ($readin as $readin_part) {
  379. s_debug_dump('S:', $readin_part);
  380. if (substr($readin_part, 0, 7) == '* SORT ') {
  381. //SORT returns untagged responses
  382. $messagelist = sqimap_array_merge_unique($messagelist, preg_split("/ /", substr($readin_part, 7)));
  383. }
  384. }
  385. if (empty($messagelist)) //Empty search response, ie '* SORT'
  386. return array();
  387. $cnt = count($messagelist);
  388. for ($q = 0; $q < $cnt; $q++)
  389. $id[$q] = trim($messagelist[$q]);
  390. return $id;
  391. }
  392. /**
  393. * Run the imap THREAD command as defined in
  394. * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
  395. * @param resource $imapConnection the current imap stream
  396. * @param string $search_string the full search expression as defined in rfc 3501
  397. * @param string $search_charset mandatory charset
  398. * @param string $thread_algorithm the threading algorithm "ORDEREDSUBJECT" or "REFERENCES"
  399. * @return array an IDs or UIDs array of matching messages or an empty array
  400. * @global array thread_new will be used by thread view in mailbox_display
  401. * @global array server_sort_array will be used by thread view in mailbox_display
  402. */
  403. function sqimap_run_thread($imapConnection, $search_string, $search_charset, $thread_algorithm)
  404. {
  405. global $thread_new, $server_sort_array;
  406. if (sqsession_is_registered('thread_new'))
  407. sqsession_unregister('thread_new');
  408. if (sqsession_is_registered('server_sort_array'))
  409. sqsession_unregister('server_sort_array');
  410. $thread_new = array();
  411. $thread_new[0] = "";
  412. $server_sort_array = array();
  413. if ($search_charset == '')
  414. $search_charset = 'US-ASCII';
  415. $query = 'THREAD ' . $thread_algorithm . ' "' . strtoupper($search_charset) . '" ALL ' . $search_string;
  416. s_debug_dump('C:', $query);
  417. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  418. s_debug_dump('S:', $response);
  419. /* 6.4 try US-ASCII charset if we received a tagged NO response (SHOULD be [BADCHARSET]) */
  420. if (($search_charset != 'US-ASCII') && (strtoupper($response) == 'NO')) {
  421. s_debug_dump('S:', $readin);
  422. $query = 'THREAD ' . $thread_algorithm . ' US-ASCII ALL ' . $search_string;
  423. s_debug_dump('C:', $query);
  424. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  425. s_debug_dump('S:', $response);
  426. }
  427. if (strtoupper($response) != 'OK') {
  428. s_debug_dump('S:', $readin);
  429. if (empty($response)) { //imap server closed connection. We can't go further.
  430. /* we should at this point:
  431. - warn the user that the THREAD call has failed
  432. - (offer him a way to) disconnect it permanently in the prefs
  433. - perform the regular search instead or provide a way to do it in one click
  434. */
  435. global $sort, $mailbox, $php_self;
  436. $message = _("The imap server failed to handle threading.");
  437. $unthread = _("Click here to unset thread view for this mailbox and start again.");
  438. if (preg_match('/^(.+)\?.+$/', $php_self, $regs))
  439. $source_url = $regs[1];
  440. else
  441. $source_url = $php_self;
  442. $link = '<a href=' . $source_url . '?sort=' . $sort . '&start_messages=1&set_thread=0&mailbox=' . urlencode($mailbox) . '>' . $unthread . '</a>';
  443. sqimap_asearch_error_box($response, $query, $message, $link);
  444. return array();
  445. }
  446. return sqimap_run_search($imapConnection, $search_string, $search_charset); // Fell back to standard search
  447. }
  448. /* Keep going till we find the * THREAD response */
  449. foreach ($readin as $readin_part) {
  450. s_debug_dump('S:', $readin_part);
  451. if (substr($readin_part, 0, 9) == '* THREAD ') {
  452. $thread_temp = preg_split("//", substr($readin_part, 9), -1, PREG_SPLIT_NO_EMPTY);
  453. break; // Should be the last anyway
  454. }
  455. }
  456. if (empty($thread_temp)) //Empty search response, ie '* THREAD'
  457. return array();
  458. $char_count = count($thread_temp);
  459. $counter = 0;
  460. $k = 0;
  461. for ($i=0;$i<$char_count;$i++) {
  462. if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
  463. $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
  464. }
  465. elseif ($thread_temp[$i] == '(') {
  466. $thread_new[$k] .= $thread_temp[$i];
  467. $counter++;
  468. }
  469. elseif ($thread_temp[$i] == ')') {
  470. if ($counter > 1) {
  471. $thread_new[$k] .= $thread_temp[$i];
  472. $counter = $counter - 1;
  473. }
  474. else {
  475. $thread_new[$k] .= $thread_temp[$i];
  476. $k++;
  477. $thread_new[$k] = "";
  478. $counter = $counter - 1;
  479. }
  480. }
  481. }
  482. sqsession_register($thread_new, 'thread_new');
  483. $thread_new = array_reverse($thread_new);
  484. $thread_list = implode(" ", $thread_new);
  485. $thread_list = str_replace("(", " ", $thread_list);
  486. $thread_list = str_replace(")", " ", $thread_list);
  487. $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
  488. $server_sort_array = $thread_list;
  489. sqsession_register($server_sort_array, 'server_sort_array');
  490. return $thread_list;
  491. }
  492. /**
  493. * @global bool allow_charset_search user setting
  494. * @global array languages sm languages array
  495. * @global string squirrelmail_language user language setting
  496. * @return string the user defined charset if $allow_charset_search is TRUE else zls ('')
  497. */
  498. function sqimap_asearch_get_charset()
  499. {
  500. global $allow_charset_search, $languages, $squirrelmail_language;
  501. if ($allow_charset_search)
  502. return $languages[$squirrelmail_language]['CHARSET'];
  503. return '';
  504. }
  505. /**
  506. * Convert sm internal sort to imap sort taking care of:
  507. * - user defined date sorting (ARRIVAL vs DATE)
  508. * - if the searched mailbox is the sent folder then TO is being used instead of FROM
  509. * - reverse order by using REVERSE
  510. * @param string $mailbox mailbox name to sort
  511. * @param integer $sort_by sm sort criteria index
  512. * @global bool internal_date_sort sort by arrival date instead of message date
  513. * @global string sent_folder sent folder name
  514. * @return string imap sort criteria
  515. */
  516. function sqimap_asearch_get_sort_criteria($mailbox, $sort_by)
  517. {
  518. global $internal_date_sort, $sent_folder;
  519. $sort_opcodes = array ('DATE', 'FROM', 'SUBJECT', 'SIZE');
  520. if ($internal_date_sort == true)
  521. $sort_opcodes[0] = 'ARRIVAL';
  522. // if (handleAsSent($mailbox))
  523. // if (isSentFolder($mailbox))
  524. if ($mailbox == $sent_folder)
  525. $sort_opcodes[1] = 'TO';
  526. return (($sort_by % 2) ? '' : 'REVERSE ') . $sort_opcodes[($sort_by >> 1) & 3];
  527. }
  528. /**
  529. * @param string $cur_mailbox unformatted mailbox name
  530. * @param array $boxes_unformatted selectable mailbox unformatted names array (reference)
  531. * @return array sub mailboxes unformatted names
  532. */
  533. function sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array)
  534. {
  535. $sub_mboxes_array = array();
  536. $boxcount = count($mboxes_array);
  537. for ($boxnum=0; $boxnum < $boxcount; $boxnum++) {
  538. if (isBoxBelow($mboxes_array[$boxnum], $cur_mailbox))
  539. $sub_mboxes_array[] = $mboxes_array[$boxnum];
  540. }
  541. return $sub_mboxes_array;
  542. }
  543. /**
  544. * Performs the search, given all the criteria, merging results for every mailbox
  545. * @param resource $imapConnection
  546. * @param array $mailbox_array
  547. * @param array $biop_array
  548. * @param array $unop_array
  549. * @param array $where_array
  550. * @param array $what_array
  551. * @param array $exclude_array
  552. * @param array $sub_array
  553. * @param array $mboxes_array selectable unformatted mailboxes names
  554. * @global bool allow_server_sort comes from config.php
  555. * @global integer sort sm internal sort order
  556. * @global bool allow_thread_sort comes from config.php
  557. * @global bool thread_sort_messages does it really need to global?
  558. * @global integer sort_by_ref thread by references
  559. * @global string data_dir
  560. * @global string username
  561. * @return array $mbox_msgs array(mailbox => array(UIDs))
  562. */
  563. function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $sub_array, $mboxes_array)
  564. {
  565. global $allow_server_sort, $sort, $allow_thread_sort, $thread_sort_messages, $sort_by_ref;
  566. global $data_dir, $username;
  567. $search_charset = sqimap_asearch_get_charset();
  568. $mbox_msgs = array();
  569. $search_string = '';
  570. $cur_mailbox = $mailbox_array[0];
  571. $cur_biop = ''; /* Start with ALL */
  572. /* We loop one more time than the real array count, so the last search gets fired */
  573. for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++) {
  574. if (empty($exclude_array[$cur_crit])) {
  575. $next_mailbox = $mailbox_array[$cur_crit];
  576. if ($next_mailbox != $cur_mailbox) {
  577. $search_string = trim($search_string); /* Trim out last space */
  578. if ($cur_mailbox == 'All Folders')
  579. $search_mboxes = $mboxes_array;
  580. else if ((!empty($sub_array[$cur_crit - 1])) || (!in_array($cur_mailbox, $mboxes_array)))
  581. $search_mboxes = sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array);
  582. else
  583. $search_mboxes = array($cur_mailbox);
  584. foreach ($search_mboxes as $cur_mailbox) {
  585. s_debug_dump('C:SELECT:', $cur_mailbox);
  586. sqimap_mailbox_select($imapConnection, $cur_mailbox);
  587. $thread_sort_messages = $allow_thread_sort && getPref($data_dir, $username, 'thread_' . $cur_mailbox);
  588. if ($thread_sort_messages) {
  589. if ($sort_by_ref == 1)
  590. $thread_algorithm = 'REFERENCES';
  591. else
  592. $thread_algorithm = 'ORDEREDSUBJECT';
  593. $found_msgs = sqimap_run_thread($imapConnection, $search_string, $search_charset, $thread_algorithm);
  594. }
  595. else
  596. if (($allow_server_sort) && ($sort < 6)) {
  597. $sort_criteria = sqimap_asearch_get_sort_criteria($cur_mailbox, $sort);
  598. $found_msgs = sqimap_run_sort($imapConnection, $search_string, $search_charset, $sort_criteria);
  599. }
  600. else
  601. $found_msgs = sqimap_run_search($imapConnection, $search_string, $search_charset);
  602. if (isset($mbox_msgs[$cur_mailbox])) {
  603. if ($cur_biop == 'OR') /* Merge with previous results */
  604. $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], $found_msgs);
  605. else /* Intersect previous results */
  606. $mbox_msgs[$cur_mailbox] = array_values(array_intersect($found_msgs, $mbox_msgs[$cur_mailbox]));
  607. }
  608. else /* No previous results */
  609. $mbox_msgs[$cur_mailbox] = $found_msgs;
  610. if (empty($mbox_msgs[$cur_mailbox])) /* Can happen with intersect, and we need at the end a contiguous array */
  611. unset($mbox_msgs[$cur_mailbox]);
  612. }
  613. $cur_mailbox = $next_mailbox;
  614. $search_string = '';
  615. }
  616. if (isset($where_array[$cur_crit])) {
  617. $criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset);
  618. if (!empty($criteria)) {
  619. $unop = $unop_array[$cur_crit];
  620. if (!empty($unop))
  621. $criteria = $unop . ' ' . $criteria;
  622. /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
  623. $next_biop = '';
  624. for ($next_crit = $cur_crit+1; $next_crit <= count($where_array); $next_crit++) {
  625. if (empty($exclude_array[$next_crit])) {
  626. if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox)
  627. $next_biop = asearch_nz($biop_array[$next_crit]);
  628. break;
  629. }
  630. }
  631. if ($next_biop == 'OR')
  632. $criteria = $next_biop . ' ' . $criteria;
  633. $search_string .= $criteria;
  634. $cur_biop = asearch_nz($biop_array[$cur_crit]);
  635. }
  636. }
  637. }
  638. }
  639. return $mbox_msgs;
  640. }
  641. ?>