imap_asearch.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. /**
  86. * Function to display an error related to an IMAP-query.
  87. * We need to do our own error management since we may receive NO responses on purpose (even BAD with SORT or THREAD)
  88. * so we call sqimap_error_box() if the function exists (sm >= 1.5) or use our own embedded code
  89. * @global array imap_error_titles
  90. * @param string $response the imap server response code
  91. * @param string $query the failed query
  92. * @param string $message an optional error message
  93. * @param string $link an optional link to try again
  94. */
  95. //@global array color sm colors array
  96. function sqimap_asearch_error_box($response, $query, $message, $link = '')
  97. {
  98. global $color;
  99. // Error message titles according to imap server returned code
  100. $imap_error_titles = array(
  101. 'OK' => '',
  102. 'NO' => _("ERROR : Could not complete request."),
  103. 'BAD' => _("ERROR : Bad or malformed request."),
  104. 'BYE' => _("ERROR : Imap server closed the connection."),
  105. '' => _("ERROR : Connection dropped by imap-server.")
  106. );
  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 a convenient way to avoid spreading if (isset(... all over the code
  135. * @param mixed $var any variable (reference)
  136. * @param mixed $def default value to return if unset (default is zls (''), pass 0 or array() when appropriate)
  137. * @return mixed $def if $var is unset, otherwise $var
  138. */
  139. function asearch_nz(&$var, $def = '')
  140. {
  141. if (isset($var))
  142. return $var;
  143. return $def;
  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 bool 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 (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 array 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]+[^KMG]$', '', strtoupper($what));
  256. if ($what != '') {
  257. switch (substr($what, -1)) {
  258. case 'G':
  259. $what = substr($what, 0, -1) << 30;
  260. break;
  261. case 'M':
  262. $what = substr($what, 0, -1) << 20;
  263. break;
  264. case 'K':
  265. $what = substr($what, 0, -1) << 10;
  266. break;
  267. }
  268. $criteria = $opcode . ' ' . $what . ' ';
  269. }
  270. break;
  271. case '': //aflag
  272. $criteria = $opcode . ' ';
  273. break;
  274. case 'afield': /* HEADER field-name: field-body */
  275. preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
  276. if (count($what_parts) == 3)
  277. $criteria = $opcode . ' ' .
  278. sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
  279. sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
  280. break;
  281. case 'adate':
  282. $what_parts = sqimap_asearch_parse_date($what);
  283. if (isset($what_parts[0]))
  284. $criteria = $opcode . ' ' . $what_parts[0] . ' ';
  285. break;
  286. case 'akeyword':
  287. case 'astring':
  288. $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
  289. break;
  290. case 'asequence':
  291. $what = ereg_replace('[^0-9:\(\)]+', '', $what);
  292. if ($what != '')
  293. $criteria = $opcode . ' ' . $what . ' ';
  294. break;
  295. }
  296. return $criteria;
  297. }
  298. /**
  299. * Another way to do array_values(array_unique(array_merge($to, $from)));
  300. * @param array $to to array (reference)
  301. * @param array $from from array
  302. * @return array uniquely merged array
  303. */
  304. function sqimap_array_merge_unique(&$to, $from)
  305. {
  306. if (empty($to))
  307. return $from;
  308. $count = count($from);
  309. for ($i = 0; $i < $count; $i++) {
  310. if (!in_array($from[$i], $to))
  311. $to[] = $from[$i];
  312. }
  313. return $to;
  314. }
  315. /**
  316. * Run the imap SEARCH command as defined in rfc 3501
  317. * @link http://www.ietf.org/rfc/rfc3501.txt
  318. * @param resource $imapConnection the current imap stream
  319. * @param string $search_string the full search expression eg "ALL RECENT"
  320. * @param string $search_charset charset to use or zls ('')
  321. * @return array an IDs or UIDs array of matching messages or an empty array
  322. */
  323. function sqimap_run_search($imapConnection, $search_string, $search_charset)
  324. {
  325. //For some reason, this seems to happen and forbids searching servers not allowing OPTIONAL [CHARSET]
  326. if (strtoupper($search_charset) == 'US-ASCII')
  327. $search_charset = '';
  328. /* 6.4.4 try OPTIONAL [CHARSET] specification first */
  329. if ($search_charset != '')
  330. $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ' . $search_string;
  331. else
  332. $query = 'SEARCH ' . $search_string;
  333. s_debug_dump('C:', $query);
  334. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  335. /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
  336. if (($search_charset != '') && (strtoupper($response) == 'NO')) {
  337. $query = 'SEARCH CHARSET US-ASCII ' . $search_string;
  338. s_debug_dump('C:', $query);
  339. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  340. }
  341. if (strtoupper($response) != 'OK') {
  342. sqimap_asearch_error_box($response, $query, $message);
  343. return array();
  344. }
  345. $messagelist = parseUidList($readin,'SEARCH');
  346. if (empty($messagelist)) //Empty search response, ie '* SEARCH'
  347. return array();
  348. $cnt = count($messagelist);
  349. for ($q = 0; $q < $cnt; $q++)
  350. $id[$q] = trim($messagelist[$q]);
  351. return $id;
  352. }
  353. /**
  354. * @global bool allow_charset_search user setting
  355. * @global array languages sm languages array
  356. * @global string squirrelmail_language user language setting
  357. * @return string the user defined charset if $allow_charset_search is TRUE else zls ('')
  358. */
  359. function sqimap_asearch_get_charset()
  360. {
  361. global $allow_charset_search, $languages, $squirrelmail_language;
  362. if ($allow_charset_search)
  363. return $languages[$squirrelmail_language]['CHARSET'];
  364. return '';
  365. }
  366. /**
  367. * Convert sm internal sort to imap sort taking care of:
  368. * - user defined date sorting (ARRIVAL vs DATE)
  369. * - if the searched mailbox is the sent folder then TO is being used instead of FROM
  370. * - reverse order by using REVERSE
  371. * @param string $mailbox mailbox name to sort
  372. * @param integer $sort_by sm sort criteria index
  373. * @global bool internal_date_sort sort by arrival date instead of message date
  374. * @global string sent_folder sent folder name
  375. * @return string imap sort criteria
  376. */
  377. function sqimap_asearch_get_sort_criteria($mailbox, $sort_by)
  378. {
  379. global $internal_date_sort, $sent_folder;
  380. $sort_opcodes = array ('DATE', 'FROM', 'SUBJECT', 'SIZE');
  381. if ($internal_date_sort == true)
  382. $sort_opcodes[0] = 'ARRIVAL';
  383. // if (handleAsSent($mailbox))
  384. // if (isSentFolder($mailbox))
  385. if ($mailbox == $sent_folder)
  386. $sort_opcodes[1] = 'TO';
  387. return (($sort_by % 2) ? '' : 'REVERSE ') . $sort_opcodes[($sort_by >> 1) & 3];
  388. }
  389. /**
  390. * @param string $cur_mailbox unformatted mailbox name
  391. * @param array $boxes_unformatted selectable mailbox unformatted names array (reference)
  392. * @return array sub mailboxes unformatted names
  393. */
  394. function sqimap_asearch_get_sub_mailboxes($cur_mailbox, &$mboxes_array)
  395. {
  396. $sub_mboxes_array = array();
  397. $boxcount = count($mboxes_array);
  398. for ($boxnum=0; $boxnum < $boxcount; $boxnum++) {
  399. if (isBoxBelow($mboxes_array[$boxnum], $cur_mailbox))
  400. $sub_mboxes_array[] = $mboxes_array[$boxnum];
  401. }
  402. return $sub_mboxes_array;
  403. }
  404. /**
  405. * Create the search query strings for all given criteria and merge results for every mailbox
  406. * @param resource $imapConnection
  407. * @param array $mailbox_array (reference)
  408. * @param array $biop_array (reference)
  409. * @param array $unop_array (reference)
  410. * @param array $where_array (reference)
  411. * @param array $what_array (reference)
  412. * @param array $exclude_array (reference)
  413. * @param array $sub_array (reference)
  414. * @param array $mboxes_array selectable unformatted mailboxes names (reference)
  415. * @return array array(mailbox => array(UIDs))
  416. */
  417. function sqimap_asearch($imapConnection, &$mailbox_array, &$biop_array, &$unop_array, &$where_array, &$what_array, &$exclude_array, &$sub_array, &$mboxes_array)
  418. {
  419. $search_charset = sqimap_asearch_get_charset();
  420. $mbox_msgs = array();
  421. $mbox_search = array();
  422. $search_string = '';
  423. $cur_mailbox = $mailbox_array[0];
  424. $cur_biop = ''; /* Start with ALL */
  425. /* We loop one more time than the real array count, so the last search gets fired */
  426. for ($cur_crit=0,$iCnt=count($where_array); $cur_crit <= $iCnt; ++$cur_crit) {
  427. if (empty($exclude_array[$cur_crit])) {
  428. $next_mailbox = (isset($mailbox_array[$cur_crit])) ? $mailbox_array[$cur_crit] : false;
  429. if ($next_mailbox != $cur_mailbox) {
  430. $search_string = trim($search_string); /* Trim out last space */
  431. if ($cur_mailbox == 'All Folders')
  432. $search_mboxes = $mboxes_array;
  433. else if ((!empty($sub_array[$cur_crit - 1])) || (!in_array($cur_mailbox, $mboxes_array)))
  434. $search_mboxes = sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array);
  435. else
  436. $search_mboxes = array($cur_mailbox);
  437. foreach ($search_mboxes as $cur_mailbox) {
  438. if (isset($mbox_search[$cur_mailbox])) {
  439. $mbox_search[$cur_mailbox]['search'] .= ' ' . $search_string;
  440. } else {
  441. $mbox_search[$cur_mailbox]['search'] = $search_string;
  442. }
  443. $mbox_search[$cur_mailbox]['charset'] = $search_charset;
  444. }
  445. $cur_mailbox = $next_mailbox;
  446. $search_string = '';
  447. }
  448. if (isset($where_array[$cur_crit]) && empty($exclude_array[$cur_crit])) {
  449. for ($crit = $cur_crit; $crit < count($where_array); $crit++) {
  450. $criteria = trim(sqimap_asearch_build_criteria($where_array[$crit], $what_array[$crit], $search_charset));
  451. if (!empty($criteria) && empty($exclude_array[$crit])) {
  452. if (asearch_nz($mailbox_array[$crit]) == $cur_mailbox) {
  453. $unop = $unop_array[$crit];
  454. if (!empty($unop)) {
  455. $criteria = $unop . ' ' . $criteria;
  456. }
  457. $aCriteria[] = array($biop_array[$crit], $criteria);
  458. }
  459. }
  460. // unset something
  461. $exclude_array[$crit] = true;
  462. }
  463. $aSearch = array();
  464. for($i=0,$iCnt=count($aCriteria);$i<$iCnt;++$i) {
  465. $cur_biop = $aCriteria[$i][0];
  466. $next_biop = (isset($aCriteria[$i+1][0])) ? $aCriteria[$i+1][0] : false;
  467. if ($next_biop != $cur_biop && $next_biop == 'OR') {
  468. $aSearch[] = 'OR '.$aCriteria[$i][1];
  469. } else if ($cur_biop != 'OR') {
  470. $aSearch[] = 'ALL '.$aCriteria[$i][1];
  471. } else { // OR only supports 2 search keys so we need to create a parenthesized list
  472. $prev_biop = (isset($aCriteria[$i-1][0])) ? $aCriteria[$i-1][0] : false;
  473. if ($prev_biop == $cur_biop) {
  474. $last = $aSearch[$i-1];
  475. if (!substr($last,-1) == ')') {
  476. $aSearch[$i-1] = "(OR $last";
  477. $aSearch[] = $aCriteria[$i][1].')';
  478. } else {
  479. $sEnd = '';
  480. while ($last && substr($last,-1) == ')') {
  481. $last = substr($last,0,-1);
  482. $sEnd .= ')';
  483. }
  484. $aSearch[$i-1] = "(OR $last";
  485. $aSearch[] = $aCriteria[$i][1].$sEnd.')';
  486. }
  487. } else {
  488. $aSearch[] = $aCriteria[$i][1];
  489. }
  490. }
  491. }
  492. $search_string .= implode(' ',$aSearch);
  493. }
  494. }
  495. }
  496. return ($mbox_search);
  497. }
  498. ?>