imap_asearch.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. * $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))
  108. $title = _("ERROR : Unknown imap response.");
  109. else
  110. $title = $imap_error_titles[$response];
  111. if ($link == '')
  112. $message_title = _("Reason Given: ");
  113. else
  114. $message_title = _("Possible reason : ");
  115. if (function_exists('sqimap_error_box'))
  116. sqimap_error_box($title, $query, $message_title, $message, $link);
  117. else { //Straight copy of 1.5 imap_general.php:sqimap_error_box(). Can be removed at a later time
  118. global $color;
  119. require_once(SM_PATH . 'functions/display_messages.php');
  120. $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
  121. if ($query != '')
  122. $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
  123. if ($message_title != '')
  124. $string .= $message_title;
  125. if ($message != '')
  126. $string .= htmlspecialchars($message);
  127. if ($link != '')
  128. $string .= $link;
  129. $string .= "</font><br>\n";
  130. error_box($string,$color);
  131. }
  132. }
  133. /**
  134. * This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc!
  135. * @param mixed $var any variable (reference)
  136. * @return mixed zls ('') if $var is not defined, otherwise $var
  137. */
  138. function asearch_nz(&$var)
  139. {
  140. if (isset($var))
  141. return $var;
  142. return '';
  143. }
  144. /**
  145. * This should give the same results as PHP 4 >= 4.3.0's html_entity_decode(),
  146. * except it doesn't handle hex constructs
  147. * @param string $string string to unhtmlentity()
  148. * @return string decoded string
  149. */
  150. function asearch_unhtmlentities($string) {
  151. $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES));
  152. for ($i=127; $i<255; $i++) /* Add &#<dec>; entities */
  153. $trans_tbl['&#' . $i . ';'] = chr($i);
  154. return strtr($string, $trans_tbl);
  155. /* I think the one above is quicker, though it should be benchmarked
  156. $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
  157. return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
  158. */
  159. }
  160. /**
  161. * Provide an easy way to dump the imap dialogue if $imap_asearch_debug_dump is TRUE
  162. * @global imap_asearch_debug_dump
  163. * @param string $var_name
  164. * @param string $var_var
  165. */
  166. function s_debug_dump($var_name, $var_var)
  167. {
  168. global $imap_asearch_debug_dump;
  169. if ($imap_asearch_debug_dump) {
  170. if (function_exists('sm_print_r')) //Only exists since 1.4.2
  171. sm_print_r($var_name, $var_var); //Better be the 'varargs' version ;)
  172. else {
  173. echo '<pre>';
  174. echo htmlentities($var_name);
  175. print_r($var_var);
  176. echo '</pre>';
  177. }
  178. }
  179. }
  180. /** Encode a string to quoted or literal as defined in rfc 3501
  181. *
  182. * - § 4.3 String:
  183. * A quoted string is a sequence of zero or more 7-bit characters,
  184. * excluding CR and LF, with double quote (<">) characters at each end.
  185. * - § 9. Formal Syntax:
  186. * quoted-specials = DQUOTE / "\"
  187. * @param string $what string to encode
  188. * @param string $charset search charset used
  189. * @return string encoded string
  190. */
  191. function sqimap_asearch_encode_string($what, $charset)
  192. {
  193. if (strtoupper($charset) == 'ISO-2022-JP') // This should be now handled in imap_utf7_local?
  194. $what = mb_convert_encoding($what, 'JIS', 'auto');
  195. //if (ereg("[\"\\\r\n\x80-\xff]", $what))
  196. if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
  197. return '{' . strlen($what) . "}\r\n" . $what; // 4.3 literal form
  198. return '"' . $what . '"'; // 4.3 quoted string form
  199. }
  200. /**
  201. * Parses a user date string into an rfc 3501 date string
  202. * Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
  203. * @global imap_asearch_months
  204. * @param string user date
  205. * @return array a preg_match-style array:
  206. * - [0] = fully formatted rfc 3501 date string (<day number>-<US month TLA>-<4 digit year>)
  207. * - [1] = day
  208. * - [2] = month
  209. * - [3] = year
  210. */
  211. function sqimap_asearch_parse_date($what)
  212. {
  213. global $imap_asearch_months;
  214. $what = trim($what);
  215. $what = ereg_replace('[ /\\.,]+', '-', $what);
  216. if ($what) {
  217. preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
  218. if (count($what_parts) == 4) {
  219. $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
  220. /* if (!in_array($what_month, $imap_asearch_months)) {*/
  221. foreach ($imap_asearch_months as $month_number => $month_code) {
  222. if (($what_month == $month_number)
  223. || ($what_month == $month_code)
  224. || ($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
  225. || ($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
  226. ) {
  227. $what_parts[2] = $month_number;
  228. $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
  229. break;
  230. }
  231. }
  232. /* }*/
  233. }
  234. }
  235. else
  236. $what_parts = array();
  237. return $what_parts;
  238. }
  239. /**
  240. * Build one criteria sequence
  241. * @global array imap_asearch_opcodes
  242. * @param string $opcode search opcode
  243. * @param string $what opcode argument
  244. * @param string $charset search charset
  245. * @return string one full criteria sequence
  246. */
  247. function sqimap_asearch_build_criteria($opcode, $what, $charset)
  248. {
  249. global $imap_asearch_opcodes;
  250. $criteria = '';
  251. switch ($imap_asearch_opcodes[$opcode]) {
  252. default:
  253. case 'anum':
  254. // $what = str_replace(' ', '', $what);
  255. $what = ereg_replace('[^0-9]+', '', $what);
  256. if ($what != '')
  257. $criteria = $opcode . ' ' . $what . ' ';
  258. break;
  259. case '': //aflag
  260. $criteria = $opcode . ' ';
  261. break;
  262. case 'afield': /* HEADER field-name: field-body */
  263. preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
  264. if (count($what_parts) == 3)
  265. $criteria = $opcode . ' ' .
  266. sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
  267. sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
  268. break;
  269. case 'adate':
  270. $what_parts = sqimap_asearch_parse_date($what);
  271. if (isset($what_parts[0]))
  272. $criteria = $opcode . ' ' . $what_parts[0] . ' ';
  273. break;
  274. case 'akeyword':
  275. case 'astring':
  276. $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
  277. break;
  278. case 'asequence':
  279. $what = ereg_replace('[^0-9:\(\)]+', '', $what);
  280. if ($what != '')
  281. $criteria = $opcode . ' ' . $what . ' ';
  282. break;
  283. }
  284. return $criteria;
  285. }
  286. /**
  287. * Another way to do array_values(array_unique(array_merge($to, $from)));
  288. * @param array $to to array (reference)
  289. * @param array $from from array
  290. * @return array uniquely merged array
  291. */
  292. function sqimap_array_merge_unique(&$to, $from)
  293. {
  294. if (empty($to))
  295. return $from;
  296. $count = count($from);
  297. for ($i = 0; $i < $count; $i++) {
  298. if (!in_array($from[$i], $to))
  299. $to[] = $from[$i];
  300. }
  301. return $to;
  302. }
  303. /**
  304. * Run the imap SEARCH command as defined in rfc 3501
  305. * @link ftp://ftp.rfc-editor.org/in-notes/rfc3501.txt
  306. * @param resource $imapConnection the current imap stream
  307. * @param string $search_string the full search expression eg "ALL RECENT"
  308. * @param string $search_charset charset to use or zls ('')
  309. * @return array an IDs or UIDs array of matching messages or an empty array
  310. */
  311. function sqimap_run_search($imapConnection, $search_string, $search_charset)
  312. {
  313. /* 6.4.4 try OPTIONAL [CHARSET] specification first */
  314. if ($search_charset != '')
  315. $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
  316. else
  317. $query = 'SEARCH ALL ' . $search_string;
  318. s_debug_dump('C:', $query);
  319. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  320. /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
  321. if (($search_charset != '') && (strtoupper($response) == 'NO')) {
  322. $query = 'SEARCH CHARSET US-ASCII ALL ' . $search_string;
  323. s_debug_dump('C:', $query);
  324. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  325. }
  326. if (strtoupper($response) != 'OK') {
  327. sqimap_asearch_error_box($response, $query, $message);
  328. return array();
  329. }
  330. // Keep going till we find the * SEARCH response
  331. foreach ($readin as $readin_part) {
  332. s_debug_dump('S:', $readin_part);
  333. if (substr($readin_part, 0, 9) == '* SEARCH ') {
  334. //EIMS returns multiple SEARCH responses, and this allowed according to Mark Crispin
  335. $messagelist = sqimap_array_merge_unique($messagelist, preg_split("/ /", substr($readin_part, 9)));
  336. }
  337. }
  338. if (empty($messagelist)) //Empty search response, ie '* SEARCH'
  339. return array();
  340. $cnt = count($messagelist);
  341. for ($q = 0; $q < $cnt; $q++)
  342. $id[$q] = trim($messagelist[$q]);
  343. return $id;
  344. }
  345. /**
  346. * Run the imap SORT command as defined in
  347. * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
  348. * @param resource $imapConnection the current imap stream
  349. * @param string $search_string the full search expression as defined in rfc 3501
  350. * @param string $search_charset mandatory charset
  351. * @param string $sort_criteria the full sort criteria expression eg "SUBJECT REVERSE DATE"
  352. * @return array an IDs or UIDs array of matching messages or an empty array
  353. */
  354. function sqimap_run_sort($imapConnection, $search_string, $search_charset, $sort_criteria)
  355. {
  356. if ($search_charset == '')
  357. $search_charset = 'US-ASCII';
  358. $query = 'SORT (' . $sort_criteria . ') "' . strtoupper($search_charset) . '" ALL ' . $search_string;
  359. s_debug_dump('C:', $query);
  360. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  361. s_debug_dump('S:', $response);
  362. /* 6.4 try US-ASCII charset if we received a tagged NO response (SHOULD be [BADCHARSET]) */
  363. if (($search_charset != 'US-ASCII') && (strtoupper($response) == 'NO')) {
  364. s_debug_dump('S:', $readin);
  365. $query = 'SORT (' . $sort_criteria . ') US-ASCII ALL ' . $search_string;
  366. s_debug_dump('C:', $query);
  367. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  368. s_debug_dump('S:', $response);
  369. }
  370. if (strtoupper($response) != 'OK') {
  371. s_debug_dump('S:', $readin);
  372. // sqimap_asearch_error_box($response, $query, $message);
  373. // return array();
  374. return sqimap_run_search($imapConnection, $search_string, $search_charset); // Fell back to standard search
  375. }
  376. /* Keep going till we find the * SORT response */
  377. foreach ($readin as $readin_part) {
  378. s_debug_dump('S:', $readin_part);
  379. if (substr($readin_part, 0, 7) == '* SORT ') {
  380. //SORT returns untagged responses
  381. $messagelist = sqimap_array_merge_unique($messagelist, preg_split("/ /", substr($readin_part, 7)));
  382. }
  383. }
  384. if (empty($messagelist)) //Empty search response, ie '* SORT'
  385. return array();
  386. $cnt = count($messagelist);
  387. for ($q = 0; $q < $cnt; $q++)
  388. $id[$q] = trim($messagelist[$q]);
  389. return $id;
  390. }
  391. /**
  392. * Run the imap THREAD command as defined in
  393. * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
  394. * @param resource $imapConnection the current imap stream
  395. * @param string $search_string the full search expression as defined in rfc 3501
  396. * @param string $search_charset mandatory charset
  397. * @param string $thread_algorithm the threading algorithm "ORDEREDSUBJECT" or "REFERENCES"
  398. * @return array an IDs or UIDs array of matching messages or an empty array
  399. * @global array thread_new will be used by thread view in mailbox_display
  400. * @global array server_sort_array will be used by thread view in mailbox_display
  401. */
  402. function sqimap_run_thread($imapConnection, $search_string, $search_charset, $thread_algorithm)
  403. {
  404. global $thread_new, $server_sort_array;
  405. if (sqsession_is_registered('thread_new'))
  406. sqsession_unregister('thread_new');
  407. if (sqsession_is_registered('server_sort_array'))
  408. sqsession_unregister('server_sort_array');
  409. $thread_new = array();
  410. $thread_new[0] = "";
  411. $server_sort_array = array();
  412. if ($search_charset == '')
  413. $search_charset = 'US-ASCII';
  414. $query = 'THREAD ' . $thread_algorithm . ' "' . strtoupper($search_charset) . '" ALL ' . $search_string;
  415. s_debug_dump('C:', $query);
  416. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  417. s_debug_dump('S:', $response);
  418. /* 6.4 try US-ASCII charset if we received a tagged NO response (SHOULD be [BADCHARSET]) */
  419. if (($search_charset != 'US-ASCII') && (strtoupper($response) == 'NO')) {
  420. s_debug_dump('S:', $readin);
  421. $query = 'THREAD ' . $thread_algorithm . ' US-ASCII ALL ' . $search_string;
  422. s_debug_dump('C:', $query);
  423. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  424. s_debug_dump('S:', $response);
  425. }
  426. if (strtoupper($response) != 'OK') {
  427. s_debug_dump('S:', $readin);
  428. if (empty($response)) { //imap server closed connection. We can't go further.
  429. /* we should at this point:
  430. - warn the user that the THREAD call has failed
  431. - (offer him a way to) disconnect it permanently in the prefs
  432. - perform the regular search instead or provide a way to do it in one click
  433. */
  434. global $sort, $mailbox, $php_self;
  435. $message = _("The imap server failed to handle threading.");
  436. $unthread = _("Click here to unset thread view for this mailbox and start again.");
  437. if (preg_match('/^(.+)\?.+$/', $php_self, $regs))
  438. $source_url = $regs[1];
  439. else
  440. $source_url = $php_self;
  441. $link = '<a href=' . $source_url . '?sort=' . $sort . '&start_messages=1&set_thread=0&mailbox=' . urlencode($mailbox) . '>' . $unthread . '</a>';
  442. sqimap_asearch_error_box($response, $query, $message, $link);
  443. return array();
  444. }
  445. return sqimap_run_search($imapConnection, $search_string, $search_charset); // Fell back to standard search
  446. }
  447. /* Keep going till we find the * THREAD response */
  448. foreach ($readin as $readin_part) {
  449. s_debug_dump('S:', $readin_part);
  450. if (substr($readin_part, 0, 9) == '* THREAD ') {
  451. $thread_temp = preg_split("//", substr($readin_part, 9), -1, PREG_SPLIT_NO_EMPTY);
  452. break; // Should be the last anyway
  453. }
  454. }
  455. if (empty($thread_temp)) //Empty search response, ie '* THREAD'
  456. return array();
  457. $char_count = count($thread_temp);
  458. $counter = 0;
  459. $k = 0;
  460. for ($i=0;$i<$char_count;$i++) {
  461. if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
  462. $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
  463. }
  464. elseif ($thread_temp[$i] == '(') {
  465. $thread_new[$k] .= $thread_temp[$i];
  466. $counter++;
  467. }
  468. elseif ($thread_temp[$i] == ')') {
  469. if ($counter > 1) {
  470. $thread_new[$k] .= $thread_temp[$i];
  471. $counter = $counter - 1;
  472. }
  473. else {
  474. $thread_new[$k] .= $thread_temp[$i];
  475. $k++;
  476. $thread_new[$k] = "";
  477. $counter = $counter - 1;
  478. }
  479. }
  480. }
  481. sqsession_register($thread_new, 'thread_new');
  482. $thread_new = array_reverse($thread_new);
  483. $thread_list = implode(" ", $thread_new);
  484. $thread_list = str_replace("(", " ", $thread_list);
  485. $thread_list = str_replace(")", " ", $thread_list);
  486. $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
  487. $server_sort_array = $thread_list;
  488. sqsession_register($server_sort_array, 'server_sort_array');
  489. return $thread_list;
  490. }
  491. /**
  492. * @global bool allow_charset_search user setting
  493. * @global array languages sm languages array
  494. * @global string squirrelmail_language user language setting
  495. * @return string the user defined charset if $allow_charset_search is TRUE else zls ('')
  496. */
  497. function sqimap_asearch_get_charset()
  498. {
  499. global $allow_charset_search, $languages, $squirrelmail_language;
  500. if ($allow_charset_search)
  501. return $languages[$squirrelmail_language]['CHARSET'];
  502. return '';
  503. }
  504. /**
  505. * Convert sm internal sort to imap sort taking care of:
  506. * - user defined date sorting (ARRIVAL vs DATE)
  507. * - if the searched mailbox is the sent folder then TO is being used instead of FROM
  508. * - reverse order by using REVERSE
  509. * @param string $mailbox mailbox name to sort
  510. * @param integer $sort_by sm sort criteria index
  511. * @global bool internal_date_sort sort by arrival date instead of message date
  512. * @global string sent_folder sent folder name
  513. * @return string imap sort criteria
  514. */
  515. function sqimap_asearch_get_sort_criteria($mailbox, $sort_by)
  516. {
  517. global $internal_date_sort, $sent_folder;
  518. $sort_opcodes = array ('DATE', 'FROM', 'SUBJECT', 'SIZE');
  519. if ($internal_date_sort == true)
  520. $sort_opcodes[0] = 'ARRIVAL';
  521. // if (handleAsSent($mailbox))
  522. // if (isSentFolder($mailbox))
  523. if ($mailbox == $sent_folder)
  524. $sort_opcodes[1] = 'TO';
  525. return (($sort_by % 2) ? '' : 'REVERSE ') . $sort_opcodes[($sort_by >> 1) & 3];
  526. }
  527. /**
  528. * @param string $cur_mailbox unformatted mailbox name
  529. * @param array $boxes_unformatted selectable mailbox unformatted names array (reference)
  530. * @return array sub mailboxes unformatted names
  531. */
  532. function sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array)
  533. {
  534. $sub_mboxes_array = array();
  535. $boxcount = count($mboxes_array);
  536. for ($boxnum=0; $boxnum < $boxcount; $boxnum++) {
  537. if (isBoxBelow($mboxes_array[$boxnum], $cur_mailbox))
  538. $sub_mboxes_array[] = $mboxes_array[$boxnum];
  539. }
  540. return $sub_mboxes_array;
  541. }
  542. /**
  543. * Performs the search, given all the criteria, merging results for every mailbox
  544. * @param resource $imapConnection
  545. * @param array $mailbox_array
  546. * @param array $biop_array
  547. * @param array $unop_array
  548. * @param array $where_array
  549. * @param array $what_array
  550. * @param array $exclude_array
  551. * @param array $sub_array
  552. * @param array $mboxes_array selectable unformatted mailboxes names
  553. * @global bool allow_server_sort comes from config.php
  554. * @global integer sort sm internal sort order
  555. * @global bool allow_thread_sort comes from config.php
  556. * @global bool thread_sort_messages does it really need to global?
  557. * @global integer sort_by_ref thread by references
  558. * @global string data_dir
  559. * @global string username
  560. * @return array $mbox_msgs array(mailbox => array(UIDs))
  561. */
  562. function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $sub_array, $mboxes_array)
  563. {
  564. global $allow_server_sort, $sort, $allow_thread_sort, $thread_sort_messages, $sort_by_ref;
  565. global $data_dir, $username;
  566. $search_charset = sqimap_asearch_get_charset();
  567. $mbox_msgs = array();
  568. $search_string = '';
  569. $cur_mailbox = $mailbox_array[0];
  570. $cur_biop = ''; /* Start with ALL */
  571. /* We loop one more time than the real array count, so the last search gets fired */
  572. for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++) {
  573. if (empty($exclude_array[$cur_crit])) {
  574. $next_mailbox = $mailbox_array[$cur_crit];
  575. if ($next_mailbox != $cur_mailbox) {
  576. $search_string = trim($search_string); /* Trim out last space */
  577. if ($cur_mailbox == 'All Folders')
  578. $search_mboxes = $mboxes_array;
  579. else if ((!empty($sub_array[$cur_crit - 1])) || (!in_array($cur_mailbox, $mboxes_array)))
  580. $search_mboxes = sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array);
  581. else
  582. $search_mboxes = array($cur_mailbox);
  583. foreach ($search_mboxes as $cur_mailbox) {
  584. s_debug_dump('C:SELECT:', $cur_mailbox);
  585. sqimap_mailbox_select($imapConnection, $cur_mailbox);
  586. $thread_sort_messages = $allow_thread_sort && getPref($data_dir, $username, 'thread_' . $cur_mailbox);
  587. if ($thread_sort_messages) {
  588. if ($sort_by_ref == 1)
  589. $thread_algorithm = 'REFERENCES';
  590. else
  591. $thread_algorithm = 'ORDEREDSUBJECT';
  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. ?>