imap_asearch.php 24 KB

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