imap_asearch.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. <?php
  2. /**
  3. * imap_search.php
  4. *
  5. * Copyright (c) 1999-2003 The SquirrelMail Project Team
  6. * Licensed under the GNU GPL. For full terms see the file COPYING.
  7. *
  8. * IMAP asearch routines
  9. * Alex Lemaresquier - Brainstorm - alex at brainstorm.fr
  10. * See README file for infos.
  11. *
  12. */
  13. require_once(SM_PATH . 'functions/imap_general.php');
  14. require_once(SM_PATH . 'functions/date.php');
  15. /* Set to TRUE to dump the imap dialogue */
  16. $imap_asearch_debug_dump = FALSE;
  17. $imap_asearch_opcodes = array(
  18. /* <message set> => 'asequence', */
  19. /*'ALL' is binary operator */
  20. 'ANSWERED' => '',
  21. 'BCC' => 'astring',
  22. 'BEFORE' => 'adate',
  23. 'BODY' => 'astring',
  24. 'CC' => 'astring',
  25. 'DELETED' => '',
  26. 'DRAFT' => '',
  27. 'FLAGGED' => '',
  28. 'FROM' => 'astring',
  29. 'HEADER' => 'afield', /* Special syntax for this one, see below */
  30. 'KEYWORD' => 'akeyword',
  31. 'LARGER' => 'anum',
  32. 'NEW' => '',
  33. /*'NOT' is unary operator */
  34. 'OLD' => '',
  35. 'ON' => 'adate',
  36. /*'OR' is binary operator */
  37. 'RECENT' => '',
  38. 'SEEN' => '',
  39. 'SENTBEFORE' => 'adate',
  40. 'SENTON' => 'adate',
  41. 'SENTSINCE' => 'adate',
  42. 'SINCE' => 'adate',
  43. 'SMALLER' => 'anum',
  44. 'SUBJECT' => 'astring',
  45. 'TEXT' => 'astring',
  46. 'TO' => 'astring',
  47. 'UID' => 'asequence',
  48. 'UNANSWERED' => '',
  49. 'UNDELETED' => '',
  50. 'UNDRAFT' => '',
  51. 'UNFLAGGED' => '',
  52. 'UNKEYWORD' => 'akeyword',
  53. 'UNSEEN' => ''
  54. );
  55. $imap_asearch_months = array(
  56. '01' => 'jan',
  57. '02' => 'feb',
  58. '03' => 'mar',
  59. '04' => 'apr',
  60. '05' => 'may',
  61. '06' => 'jun',
  62. '07' => 'jul',
  63. '08' => 'aug',
  64. '09' => 'sep',
  65. '10' => 'oct',
  66. '11' => 'nov',
  67. '12' => 'dec'
  68. );
  69. $imap_error_titles = array(
  70. 'OK' => '',
  71. 'NO' => _("ERROR : Could not complete request."),
  72. 'BAD' => _("ERROR : Bad or malformed request."),
  73. 'BYE' => _("ERROR : Imap server closed the connection.")
  74. );
  75. function sqimap_asearch_error_box($response, $query, $message)
  76. {
  77. global $imap_error_titles;
  78. //if (!array_key_exists($response, $imap_error_titles)) //php 4.0.6 compatibility
  79. if (!in_array($response, array_keys($imap_error_titles)))
  80. $title = _("ERROR : Unknown imap response.");
  81. else
  82. $title = $imap_error_titles[$response];
  83. sqimap_error_box($title, $query, _("Reason Given: "), $message);
  84. }
  85. /* This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc! */
  86. function asearch_nz(&$var)
  87. {
  88. if (isset($var))
  89. return $var;
  90. return '';
  91. }
  92. /* This should give the same results as PHP 4 >= 4.3.0's html_entity_decode() */
  93. function asearch_unhtmlentities($string) {
  94. $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES));
  95. for ($i=127; $i<255; $i++) /* Add &#<dec>; entities */
  96. $trans_tbl['&#' . $i . ';'] = chr($i);
  97. return strtr($string, $trans_tbl);
  98. /* I think the one above is quicker, though it should be benchmarked
  99. $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
  100. return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
  101. */
  102. }
  103. function s_debug_dump($var_name, $var_var)
  104. {
  105. global $imap_asearch_debug_dump;
  106. if ($imap_asearch_debug_dump)
  107. sm_print_r($var_name, $var_var);
  108. }
  109. /*
  110. 4.3 String:
  111. A quoted string is a sequence of zero or more 7-bit characters,
  112. excluding CR and LF, with double quote (<">) characters at each end.
  113. 9. Formal Syntax:
  114. quoted-specials = DQUOTE / "\"
  115. */
  116. function sqimap_asearch_encode_string($what, $search_charset)
  117. {
  118. if (strtoupper($search_charset) == 'ISO-2022-JP')
  119. $what = mb_convert_encoding($what, 'JIS', 'auto');
  120. //if (ereg("[\"\\\r\n\x80-\xff]", $what))
  121. if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
  122. return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
  123. return '"' . $what . '"'; /* 4.3 quoted string form */
  124. }
  125. /*
  126. Parses a user date string into an rfc2060 date string (<day number>-<US month TLA>-<4 digit year>)
  127. Returns a preg_match-style array: [0]: fully formatted date, [1]: day, [2]: month, [3]: year
  128. Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
  129. */
  130. function sqimap_asearch_parse_date($what)
  131. {
  132. global $imap_asearch_months;
  133. $what = trim($what);
  134. $what = ereg_replace('[ /\\.,]+', '-', $what);
  135. if ($what) {
  136. preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
  137. if (count($what_parts) == 4) {
  138. $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
  139. /* if (!in_array($what_month, $imap_asearch_months)) {*/
  140. foreach ($imap_asearch_months as $month_number => $month_code) {
  141. if (($what_month == $month_number)
  142. || ($what_month == $month_code)
  143. || ($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
  144. || ($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
  145. ) {
  146. $what_parts[2] = $month_number;
  147. $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
  148. break;
  149. }
  150. }
  151. /* }*/
  152. }
  153. }
  154. else
  155. $what_parts = array();
  156. return $what_parts;
  157. }
  158. function sqimap_asearch_build_criteria($opcode, $what, $search_charset)
  159. {
  160. global $imap_asearch_opcodes;
  161. $criteria = '';
  162. switch ($imap_asearch_opcodes[$opcode]) {
  163. default:
  164. case 'anum':
  165. /* $what = str_replace(' ', '', $what);*/
  166. $what = ereg_replace('[^0-9]+', '', $what);
  167. if ($what != '')
  168. $criteria = $opcode . ' ' . $what . ' ';
  169. break;
  170. case '': /* aflag */
  171. $criteria = $opcode . ' ';
  172. break;
  173. case 'afield': /* HEADER field-name: field-body */
  174. preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
  175. if (count($what_parts) == 3)
  176. $criteria = $opcode . ' ' .
  177. sqimap_asearch_encode_string($what_parts[1], $search_charset) . ' ' .
  178. sqimap_asearch_encode_string($what_parts[2], $search_charset) . ' ';
  179. break;
  180. case 'adate':
  181. $what_parts = sqimap_asearch_parse_date($what);
  182. if (isset($what_parts[0]))
  183. $criteria = $opcode . ' ' . $what_parts[0] . ' ';
  184. break;
  185. case 'akeyword':
  186. case 'astring':
  187. $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $search_charset) . ' ';
  188. break;
  189. case 'asequence':
  190. $what = ereg_replace('[^0-9:\(\)]+', '', $what);
  191. if ($what != '')
  192. $criteria = $opcode . ' ' . $what . ' ';
  193. break;
  194. }
  195. return $criteria;
  196. }
  197. function sqimap_run_search($imapConnection, $search_string, $search_charset)
  198. {
  199. global $allow_charset_search, $uid_support;
  200. /* 6.4.4 try OPTIONAL [CHARSET] specification first */
  201. if ($allow_charset_search && (!empty($search_charset)))
  202. $query = 'SEARCH CHARSET ' . strtoupper($search_charset) . ' ALL ' . $search_string;
  203. else
  204. $query = 'SEARCH ALL ' . $search_string;
  205. s_debug_dump('C:', $query);
  206. /* read data back from IMAP */
  207. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
  208. /* 6.4.4 try US-ASCII charset if we receive a tagged NO response */
  209. if ((!empty($charset)) && (strtoupper($response) == 'NO')) {
  210. $query = 'SEARCH CHARSET "US-ASCII" ALL ' . $search_string;
  211. s_debug_dump('C:', $query);
  212. $readin = sqimap_run_command ($imapConnection, $query, false, $response, $message, $uid_support); /* added $uid_support */
  213. }
  214. if (strtoupper($response) != 'OK') {
  215. sqimap_asearch_error_box($response, $query, $message);
  216. return array();
  217. }
  218. unset($messagelist);
  219. /* Keep going till we find the SEARCH response */
  220. foreach ($readin as $readin_part) {
  221. s_debug_dump('S:', $readin_part);
  222. /* Check to see if a SEARCH response was received */
  223. if (substr($readin_part, 0, 9) == '* SEARCH ') {
  224. $messagelist = preg_split("/ /", substr($readin_part, 9));
  225. break; // Should be the last anyway
  226. }
  227. /* else {
  228. if (isset($errors))
  229. $errors = $errors . $readin_part;
  230. else
  231. $errors = $readin_part;
  232. }*/
  233. }
  234. /* If nothing is found * SEARCH should be the first error else echo errors */
  235. /*if (isset($errors)) {
  236. if (strstr($errors,'* SEARCH'))
  237. return array();
  238. echo '<!-- ' . htmlspecialchars($errors) . ' -->';
  239. }*/
  240. if (empty($messagelist)) //Empty search response, ie '* SEARCH'
  241. return array();
  242. $cnt = count($messagelist);
  243. for ($q = 0; $q < $cnt; $q++)
  244. $id[$q] = trim($messagelist[$q]);
  245. return $id;
  246. }
  247. /* replaces $mbox_msgs[$search_mailbox] = array_values(array_unique(array_merge($mbox_msgs[$search_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset))));*/
  248. function sqimap_array_merge_unique($to, $from)
  249. {
  250. if (empty($to))
  251. return $from;
  252. for ($i=0; $i<count($from); $i++) {
  253. if (!in_array($from[$i], $to))
  254. $to[] = $from[$i];
  255. }
  256. return $to;
  257. }
  258. function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $mboxes_array)
  259. {
  260. global $languages, $squirrelmail_language;
  261. /* ??? what are those for ?? */
  262. /* $pos = $search_position;*/
  263. $mbox_msgs = array();
  264. $search_charset = $languages[$squirrelmail_language]['CHARSET'];
  265. $search_string = '';
  266. $cur_mailbox = $mailbox_array[0];
  267. $cur_biop = ''; /* Start with ALL */
  268. /* We loop one more time than the real array count, so the last search gets fired */
  269. for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++) {
  270. if (empty($exclude_array[$cur_crit])) {
  271. $next_mailbox = $mailbox_array[$cur_crit];
  272. if ($next_mailbox != $cur_mailbox) {
  273. $search_string = trim($search_string); /* Trim out last space */
  274. if (($cur_mailbox == 'All Folders') && (!empty($mboxes_array)))
  275. $search_mboxes = $mboxes_array;
  276. else
  277. $search_mboxes = array($cur_mailbox);
  278. foreach ($search_mboxes as $cur_mailbox) {
  279. sqimap_mailbox_select($imapConnection, $cur_mailbox);
  280. s_debug_dump('C:SELECT:', $cur_mailbox);
  281. if (isset($mbox_msgs[$cur_mailbox])) {
  282. if ($cur_biop == 'OR') /* Merge with previous results */
  283. $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset));
  284. else /* Intersect previous results */
  285. $mbox_msgs[$cur_mailbox] = array_values(array_intersect(sqimap_run_search($imapConnection, $search_string, $search_charset), $mbox_msgs[$cur_mailbox]));
  286. }
  287. else /* No previous results */
  288. $mbox_msgs[$cur_mailbox] = sqimap_run_search($imapConnection, $search_string, $search_charset);
  289. if (empty($mbox_msgs[$cur_mailbox])) /* Can happen with intersect, and we need at the end a contiguous array */
  290. unset($mbox_msgs[$cur_mailbox]);
  291. }
  292. $cur_mailbox = $next_mailbox;
  293. $search_string = '';
  294. }
  295. if (isset($where_array[$cur_crit])) {
  296. $criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset);
  297. if (!empty($criteria)) {
  298. $unop = $unop_array[$cur_crit];
  299. if (!empty($unop))
  300. $criteria = $unop . ' ' . $criteria;
  301. /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
  302. $next_biop = '';
  303. for ($next_crit = $cur_crit+1; $next_crit <= count($where_array); $next_crit++) {
  304. if (empty($exclude_array[$next_crit])) {
  305. if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox)
  306. $next_biop = asearch_nz($biop_array[$next_crit]);
  307. break;
  308. }
  309. }
  310. if ($next_biop == 'OR')
  311. $criteria = $next_biop . ' ' . $criteria;
  312. $search_string .= $criteria;
  313. $cur_biop = asearch_nz($biop_array[$cur_crit]);
  314. }
  315. }
  316. }
  317. }
  318. return $mbox_msgs;
  319. }
  320. ?>