imap_asearch.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. <?php
  2. /**
  3. * imap_search.php
  4. *
  5. * Copyright (c) 1999-2005 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. global $imap_asearch_opcodes;
  31. $imap_asearch_opcodes = array(
  32. /* <sequence-set> => 'asequence', */ // Special handling, @see sqimap_asearch_build_criteria()
  33. /*'ALL' is binary operator */
  34. 'ANSWERED' => '',
  35. 'BCC' => 'astring',
  36. 'BEFORE' => 'adate',
  37. 'BODY' => 'astring',
  38. 'CC' => 'astring',
  39. 'DELETED' => '',
  40. 'DRAFT' => '',
  41. 'FLAGGED' => '',
  42. 'FROM' => 'astring',
  43. 'HEADER' => 'afield', // Special syntax for this one, @see sqimap_asearch_build_criteria()
  44. 'KEYWORD' => 'akeyword',
  45. 'LARGER' => 'anum',
  46. 'NEW' => '',
  47. /*'NOT' is unary operator */
  48. 'OLD' => '',
  49. 'ON' => 'adate',
  50. /*'OR' is binary operator */
  51. 'RECENT' => '',
  52. 'SEEN' => '',
  53. 'SENTBEFORE' => 'adate',
  54. 'SENTON' => 'adate',
  55. 'SENTSINCE' => 'adate',
  56. 'SINCE' => 'adate',
  57. 'SMALLER' => 'anum',
  58. 'SUBJECT' => 'astring',
  59. 'TEXT' => 'astring',
  60. 'TO' => 'astring',
  61. 'UID' => 'asequence',
  62. 'UNANSWERED' => '',
  63. 'UNDELETED' => '',
  64. 'UNDRAFT' => '',
  65. 'UNFLAGGED' => '',
  66. 'UNKEYWORD' => 'akeyword',
  67. 'UNSEEN' => ''
  68. );
  69. /** Imap SEARCH month names encoding
  70. * @global array $imap_asearch_months
  71. */
  72. $imap_asearch_months = array(
  73. '01' => 'jan',
  74. '02' => 'feb',
  75. '03' => 'mar',
  76. '04' => 'apr',
  77. '05' => 'may',
  78. '06' => 'jun',
  79. '07' => 'jul',
  80. '08' => 'aug',
  81. '09' => 'sep',
  82. '10' => 'oct',
  83. '11' => 'nov',
  84. '12' => 'dec'
  85. );
  86. /**
  87. * Function to display an error related to an IMAP-query.
  88. * We need to do our own error management since we may receive NO responses on purpose (even BAD with SORT or THREAD)
  89. * so we call sqimap_error_box() if the function exists (sm >= 1.5) or use our own embedded code
  90. * @global array imap_error_titles
  91. * @param string $response the imap server response code
  92. * @param string $query the failed query
  93. * @param string $message an optional error message
  94. * @param string $link an optional link to try again
  95. */
  96. //@global array color sm colors array
  97. function sqimap_asearch_error_box($response, $query, $message, $link = '')
  98. {
  99. global $color;
  100. // Error message titles according to imap server returned code
  101. $imap_error_titles = array(
  102. 'OK' => '',
  103. 'NO' => _("ERROR : Could not complete request."),
  104. 'BAD' => _("ERROR : Bad or malformed request."),
  105. 'BYE' => _("ERROR : Imap server closed the connection."),
  106. '' => _("ERROR : Connection dropped by imap-server.")
  107. );
  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 a convenient way to avoid spreading if (isset(... all over the code
  136. * @param mixed $var any variable (reference)
  137. * @param mixed $def default value to return if unset (default is zls (''), pass 0 or array() when appropriate)
  138. * @return mixed $def if $var is unset, otherwise $var
  139. */
  140. function asearch_nz(&$var, $def = '')
  141. {
  142. if (isset($var))
  143. return $var;
  144. return $def;
  145. }
  146. /**
  147. * This should give the same results as PHP 4 >= 4.3.0's html_entity_decode(),
  148. * except it doesn't handle hex constructs
  149. * @param string $string string to unhtmlentity()
  150. * @return string decoded string
  151. */
  152. function asearch_unhtmlentities($string) {
  153. $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES));
  154. for ($i=127; $i<255; $i++) /* Add &#<dec>; entities */
  155. $trans_tbl['&#' . $i . ';'] = chr($i);
  156. return strtr($string, $trans_tbl);
  157. /* I think the one above is quicker, though it should be benchmarked
  158. $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
  159. return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
  160. */
  161. }
  162. /**
  163. * Provide an easy way to dump the imap dialogue if $imap_asearch_debug_dump is TRUE
  164. * @global bool imap_asearch_debug_dump
  165. * @param string $var_name
  166. * @param string $var_var
  167. */
  168. function s_debug_dump($var_name, $var_var)
  169. {
  170. global $imap_asearch_debug_dump;
  171. if ($imap_asearch_debug_dump) {
  172. if (function_exists('sm_print_r')) //Only exists since 1.4.2
  173. sm_print_r($var_name, $var_var); //Better be the 'varargs' version ;)
  174. else {
  175. echo '<pre>';
  176. echo htmlentities($var_name);
  177. print_r($var_var);
  178. echo '</pre>';
  179. }
  180. }
  181. }
  182. /** Encode a string to quoted or literal as defined in rfc 3501
  183. *
  184. * - 4.3 String:
  185. * A quoted string is a sequence of zero or more 7-bit characters,
  186. * excluding CR and LF, with double quote (<">) characters at each end.
  187. * - 9. Formal Syntax:
  188. * quoted-specials = DQUOTE / "\"
  189. * @param string $what string to encode
  190. * @param string $charset search charset used
  191. * @return string encoded string
  192. */
  193. function sqimap_asearch_encode_string($what, $charset)
  194. {
  195. if (strtoupper($charset) == 'ISO-2022-JP') // This should be now handled in imap_utf7_local?
  196. $what = mb_convert_encoding($what, 'JIS', 'auto');
  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 array 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]+[^KMG]$', '', strtoupper($what));
  257. if ($what != '') {
  258. switch (substr($what, -1)) {
  259. case 'G':
  260. $what = substr($what, 0, -1) << 30;
  261. break;
  262. case 'M':
  263. $what = substr($what, 0, -1) << 20;
  264. break;
  265. case 'K':
  266. $what = substr($what, 0, -1) << 10;
  267. break;
  268. }
  269. $criteria = $opcode . ' ' . $what . ' ';
  270. }
  271. break;
  272. case '': //aflag
  273. $criteria = $opcode . ' ';
  274. break;
  275. case 'afield': /* HEADER field-name: field-body */
  276. preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
  277. if (count($what_parts) == 3)
  278. $criteria = $opcode . ' ' .
  279. sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
  280. sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
  281. break;
  282. case 'adate':
  283. $what_parts = sqimap_asearch_parse_date($what);
  284. if (isset($what_parts[0]))
  285. $criteria = $opcode . ' ' . $what_parts[0] . ' ';
  286. break;
  287. case 'akeyword':
  288. case 'astring':
  289. $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
  290. break;
  291. case 'asequence':
  292. $what = ereg_replace('[^0-9:\(\)]+', '', $what);
  293. if ($what != '')
  294. $criteria = $opcode . ' ' . $what . ' ';
  295. break;
  296. }
  297. return $criteria;
  298. }
  299. /**
  300. * Another way to do array_values(array_unique(array_merge($to, $from)));
  301. * @param array $to to array (reference)
  302. * @param array $from from array
  303. * @return array uniquely merged array
  304. */
  305. function sqimap_array_merge_unique(&$to, $from)
  306. {
  307. if (empty($to))
  308. return $from;
  309. $count = count($from);
  310. for ($i = 0; $i < $count; $i++) {
  311. if (!in_array($from[$i], $to))
  312. $to[] = $from[$i];
  313. }
  314. return $to;
  315. }
  316. /**
  317. * Run the imap SEARCH command as defined in rfc 3501
  318. * @link http://www.ietf.org/rfc/rfc3501.txt
  319. * @param resource $imapConnection the current imap stream
  320. * @param string $search_string the full search expression eg "ALL RECENT"
  321. * @param string $search_charset charset to use or zls ('')
  322. * @return array an IDs or UIDs array of matching messages or an empty array
  323. * @since 1.5.0
  324. */
  325. function sqimap_run_search($imapConnection, $search_string, $search_charset)
  326. {
  327. //For some reason, this seems to happen and forbids searching servers not allowing OPTIONAL [CHARSET]
  328. if (strtoupper($search_charset) == 'US-ASCII')
  329. $search_charset = '';
  330. /* 6.4.4 try OPTIONAL [CHARSET] specification first */
  331. if ($search_charset != '')
  332. $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ' . $search_string;
  333. else
  334. $query = 'SEARCH ' . $search_string;
  335. s_debug_dump('C:', $query);
  336. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  337. /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
  338. if (($search_charset != '') && (strtoupper($response) == 'NO')) {
  339. $query = 'SEARCH CHARSET US-ASCII ' . $search_string;
  340. s_debug_dump('C:', $query);
  341. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  342. }
  343. if (strtoupper($response) != 'OK') {
  344. sqimap_asearch_error_box($response, $query, $message);
  345. return array();
  346. }
  347. $messagelist = parseUidList($readin,'SEARCH');
  348. if (empty($messagelist)) //Empty search response, ie '* SEARCH'
  349. return array();
  350. $cnt = count($messagelist);
  351. for ($q = 0; $q < $cnt; $q++)
  352. $id[$q] = trim($messagelist[$q]);
  353. return $id;
  354. }
  355. /**
  356. * @global bool allow_charset_search user setting
  357. * @global array languages sm languages array
  358. * @global string squirrelmail_language user language setting
  359. * @return string the user defined charset if $allow_charset_search is TRUE else zls ('')
  360. */
  361. function sqimap_asearch_get_charset()
  362. {
  363. global $allow_charset_search, $languages, $squirrelmail_language;
  364. if ($allow_charset_search)
  365. return $languages[$squirrelmail_language]['CHARSET'];
  366. return '';
  367. }
  368. /**
  369. * Convert sm internal sort to imap sort taking care of:
  370. * - user defined date sorting (ARRIVAL vs DATE)
  371. * - if the searched mailbox is the sent folder then TO is being used instead of FROM
  372. * - reverse order by using REVERSE
  373. * @param string $mailbox mailbox name to sort
  374. * @param integer $sort_by sm sort criteria index
  375. * @global bool internal_date_sort sort by arrival date instead of message date
  376. * @global string sent_folder sent folder name
  377. * @return string imap sort criteria
  378. */
  379. function sqimap_asearch_get_sort_criteria($mailbox, $sort_by)
  380. {
  381. global $internal_date_sort, $sent_folder;
  382. $sort_opcodes = array ('DATE', 'FROM', 'SUBJECT', 'SIZE');
  383. if ($internal_date_sort == true)
  384. $sort_opcodes[0] = 'ARRIVAL';
  385. // if (handleAsSent($mailbox))
  386. // if (isSentFolder($mailbox))
  387. if ($mailbox == $sent_folder)
  388. $sort_opcodes[1] = 'TO';
  389. return (($sort_by % 2) ? '' : 'REVERSE ') . $sort_opcodes[($sort_by >> 1) & 3];
  390. }
  391. /**
  392. * @param string $cur_mailbox unformatted mailbox name
  393. * @param array $boxes_unformatted selectable mailbox unformatted names array (reference)
  394. * @return array sub mailboxes unformatted names
  395. */
  396. function sqimap_asearch_get_sub_mailboxes($cur_mailbox, &$mboxes_array)
  397. {
  398. $sub_mboxes_array = array();
  399. $boxcount = count($mboxes_array);
  400. for ($boxnum=0; $boxnum < $boxcount; $boxnum++) {
  401. if (isBoxBelow($mboxes_array[$boxnum], $cur_mailbox))
  402. $sub_mboxes_array[] = $mboxes_array[$boxnum];
  403. }
  404. return $sub_mboxes_array;
  405. }
  406. /**
  407. * Create the search query strings for all given criteria and merge results for every mailbox
  408. * @param resource $imapConnection
  409. * @param array $mailbox_array (reference)
  410. * @param array $biop_array (reference)
  411. * @param array $unop_array (reference)
  412. * @param array $where_array (reference)
  413. * @param array $what_array (reference)
  414. * @param array $exclude_array (reference)
  415. * @param array $sub_array (reference)
  416. * @param array $mboxes_array selectable unformatted mailboxes names (reference)
  417. * @return array array(mailbox => array(UIDs))
  418. */
  419. function sqimap_asearch($imapConnection, &$mailbox_array, &$biop_array, &$unop_array, &$where_array, &$what_array, &$exclude_array, &$sub_array, &$mboxes_array)
  420. {
  421. $search_charset = sqimap_asearch_get_charset();
  422. $mbox_search = array();
  423. $search_string = '';
  424. $cur_mailbox = $mailbox_array[0];
  425. $cur_biop = ''; /* Start with ALL */
  426. /* We loop one more time than the real array count, so the last search gets fired */
  427. for ($cur_crit=0,$iCnt=count($where_array); $cur_crit <= $iCnt; ++$cur_crit) {
  428. if (empty($exclude_array[$cur_crit])) {
  429. $next_mailbox = (isset($mailbox_array[$cur_crit])) ? $mailbox_array[$cur_crit] : false;
  430. if ($next_mailbox != $cur_mailbox) {
  431. $search_string = trim($search_string); /* Trim out last space */
  432. if ($cur_mailbox == 'All Folders')
  433. $search_mboxes = $mboxes_array;
  434. else if ((!empty($sub_array[$cur_crit - 1])) || (!in_array($cur_mailbox, $mboxes_array)))
  435. $search_mboxes = sqimap_asearch_get_sub_mailboxes($cur_mailbox, $mboxes_array);
  436. else
  437. $search_mboxes = array($cur_mailbox);
  438. foreach ($search_mboxes as $cur_mailbox) {
  439. if (isset($mbox_search[$cur_mailbox])) {
  440. $mbox_search[$cur_mailbox]['search'] .= ' ' . $search_string;
  441. } else {
  442. $mbox_search[$cur_mailbox]['search'] = $search_string;
  443. }
  444. $mbox_search[$cur_mailbox]['charset'] = $search_charset;
  445. }
  446. $cur_mailbox = $next_mailbox;
  447. $search_string = '';
  448. }
  449. if (isset($where_array[$cur_crit]) && empty($exclude_array[$cur_crit])) {
  450. for ($crit = $cur_crit; $crit < count($where_array); $crit++) {
  451. $criteria = trim(sqimap_asearch_build_criteria($where_array[$crit], $what_array[$crit], $search_charset));
  452. if (!empty($criteria) && empty($exclude_array[$crit])) {
  453. if (asearch_nz($mailbox_array[$crit]) == $cur_mailbox) {
  454. $unop = $unop_array[$crit];
  455. if (!empty($unop)) {
  456. $criteria = $unop . ' ' . $criteria;
  457. }
  458. $aCriteria[] = array($biop_array[$crit], $criteria);
  459. }
  460. }
  461. // unset something
  462. $exclude_array[$crit] = true;
  463. }
  464. $aSearch = array();
  465. for($i=0,$iCnt=count($aCriteria);$i<$iCnt;++$i) {
  466. $cur_biop = $aCriteria[$i][0];
  467. $next_biop = (isset($aCriteria[$i+1][0])) ? $aCriteria[$i+1][0] : false;
  468. if ($next_biop != $cur_biop && $next_biop == 'OR') {
  469. $aSearch[] = 'OR '.$aCriteria[$i][1];
  470. } else if ($cur_biop != 'OR') {
  471. $aSearch[] = 'ALL '.$aCriteria[$i][1];
  472. } else { // OR only supports 2 search keys so we need to create a parenthesized list
  473. $prev_biop = (isset($aCriteria[$i-1][0])) ? $aCriteria[$i-1][0] : false;
  474. if ($prev_biop == $cur_biop) {
  475. $last = $aSearch[$i-1];
  476. if (!substr($last,-1) == ')') {
  477. $aSearch[$i-1] = "(OR $last";
  478. $aSearch[] = $aCriteria[$i][1].')';
  479. } else {
  480. $sEnd = '';
  481. while ($last && substr($last,-1) == ')') {
  482. $last = substr($last,0,-1);
  483. $sEnd .= ')';
  484. }
  485. $aSearch[$i-1] = "(OR $last";
  486. $aSearch[] = $aCriteria[$i][1].$sEnd.')';
  487. }
  488. } else {
  489. $aSearch[] = $aCriteria[$i][1];
  490. }
  491. }
  492. }
  493. $search_string .= implode(' ',$aSearch);
  494. }
  495. }
  496. }
  497. return ($mbox_search);
  498. }
  499. ?>