PageRenderTime 51ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/branches/DEVEL_MARC/squirrelmail/functions/imap_asearch.php

#
PHP | 527 lines | 344 code | 29 blank | 154 comment | 100 complexity | 7554bb60bcaf4980466a7d3314514b9c MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0
  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: imap_asearch.php 8458 2004-12-22 23:04:46Z stekkel $
  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. */
  324. function sqimap_run_search($imapConnection, $search_string, $search_charset)
  325. {
  326. //For some reason, this seems to happen and forbids searching servers not allowing OPTIONAL [CHARSET]
  327. if (strtoupper($search_charset) == 'US-ASCII')
  328. $search_charset = '';
  329. /* 6.4.4 try OPTIONAL [CHARSET] specification first */
  330. if ($search_charset != '')
  331. $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ' . $search_string;
  332. else
  333. $query = 'SEARCH ' . $search_string;
  334. s_debug_dump('C:', $query);
  335. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  336. /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
  337. if (($search_charset != '') && (strtoupper($response) == 'NO')) {
  338. $query = 'SEARCH CHARSET US-ASCII ' . $search_string;
  339. s_debug_dump('C:', $query);
  340. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, TRUE);
  341. }
  342. if (strtoupper($response) != 'OK') {
  343. sqimap_asearch_error_box($response, $query, $message);
  344. return array();
  345. }
  346. $messagelist = parseUidList($readin,'SEARCH');
  347. if (empty($messagelist)) //Empty search response, ie '* SEARCH'
  348. return array();
  349. $cnt = count($messagelist);
  350. for ($q = 0; $q < $cnt; $q++)
  351. $id[$q] = trim($messagelist[$q]);
  352. return $id;
  353. }
  354. /**
  355. * @global bool allow_charset_search user setting
  356. * @global array languages sm languages array
  357. * @global string squirrelmail_language user language setting
  358. * @return string the user defined charset if $allow_charset_search is TRUE else zls ('')
  359. */
  360. function sqimap_asearch_get_charset()
  361. {
  362. global $allow_charset_search, $languages, $squirrelmail_language;
  363. if ($allow_charset_search)
  364. return $languages[$squirrelmail_language]['CHARSET'];
  365. return '';
  366. }
  367. /**
  368. * Convert sm internal sort to imap sort taking care of:
  369. * - user defined date sorting (ARRIVAL vs DATE)
  370. * - if the searched mailbox is the sent folder then TO is being used instead of FROM
  371. * - reverse order by using REVERSE
  372. * @param string $mailbox mailbox name to sort
  373. * @param integer $sort_by sm sort criteria index
  374. * @global bool internal_date_sort sort by arrival date instead of message date
  375. * @global string sent_folder sent folder name
  376. * @return string imap sort criteria
  377. */
  378. function sqimap_asearch_get_sort_criteria($mailbox, $sort_by)
  379. {
  380. global $internal_date_sort, $sent_folder;
  381. $sort_opcodes = array ('DATE', 'FROM', 'SUBJECT', 'SIZE');
  382. if ($internal_date_sort == true)
  383. $sort_opcodes[0] = 'ARRIVAL';
  384. // if (handleAsSent($mailbox))
  385. // if (isSentFolder($mailbox))
  386. if ($mailbox == $sent_folder)
  387. $sort_opcodes[1] = 'TO';
  388. return (($sort_by % 2) ? '' : 'REVERSE ') . $sort_opcodes[($sort_by >> 1) & 3];
  389. }
  390. /**
  391. * @param string $cur_mailbox unformatted mailbox name
  392. * @param array $boxes_unformatted selectable mailbox unformatted names array (reference)
  393. * @return array sub mailboxes unformatted names
  394. */
  395. function sqimap_asearch_get_sub_mailboxes($cur_mailbox, &$mboxes_array)
  396. {
  397. $sub_mboxes_array = array();
  398. $boxcount = count($mboxes_array);
  399. for ($boxnum=0; $boxnum < $boxcount; $boxnum++) {
  400. if (isBoxBelow($mboxes_array[$boxnum], $cur_mailbox))
  401. $sub_mboxes_array[] = $mboxes_array[$boxnum];
  402. }
  403. return $sub_mboxes_array;
  404. }
  405. /**
  406. * Create the search query strings for all given criteria and merge results for every mailbox
  407. * @param resource $imapConnection
  408. * @param array $mailbox_array (reference)
  409. * @param array $biop_array (reference)
  410. * @param array $unop_array (reference)
  411. * @param array $where_array (reference)
  412. * @param array $what_array (reference)
  413. * @param array $exclude_array (reference)
  414. * @param array $sub_array (reference)
  415. * @param array $mboxes_array selectable unformatted mailboxes names (reference)
  416. * @return array array(mailbox => array(UIDs))
  417. */
  418. function sqimap_asearch($imapConnection, &$mailbox_array, &$biop_array, &$unop_array, &$where_array, &$what_array, &$exclude_array, &$sub_array, &$mboxes_array)
  419. {
  420. $search_charset = sqimap_asearch_get_charset();
  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. ?>