imap_asearch.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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.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. /* This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc! */
  70. function asearch_nz(&$var)
  71. {
  72. if (isset($var))
  73. return $var;
  74. return '';
  75. }
  76. /* This should give the same results as PHP 4 >= 4.3.0's html_entity_decode() */
  77. function asearch_unhtmlentities($string) {
  78. $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES));
  79. for ($i=127; $i<255; $i++) /* Add &#<dec>; entities */
  80. $trans_tbl['&#' . $i . ';'] = chr($i);
  81. return strtr($string, $trans_tbl);
  82. /* I think the one above is quicker, though it should be benchmarked
  83. $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
  84. return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
  85. */
  86. }
  87. function s_dump($var_name, $var_var, $compact = FALSE)
  88. {
  89. if (!$compact)
  90. echo '<PRE>';
  91. echo htmlentities($var_name) . '=';
  92. print_r($var_var);
  93. if ($compact)
  94. echo "<BR>\n";
  95. else
  96. echo "</PRE>\n";
  97. }
  98. function s_debug_dump($var_name, $var_var, $compact = FALSE)
  99. {
  100. global $imap_asearch_debug_dump;
  101. if ($imap_asearch_debug_dump)
  102. s_dump($var_name, $var_var, $compact);
  103. }
  104. /*
  105. 4.3 String:
  106. A quoted string is a sequence of zero or more 7-bit characters,
  107. excluding CR and LF, with double quote (<">) characters at each end.
  108. 9. Formal Syntax:
  109. quoted-specials = DQUOTE / "\"
  110. */
  111. function sqimap_asearch_encode_string($what, $search_charset)
  112. {
  113. if (strtoupper($search_charset) == 'ISO-2022-JP')
  114. $what = mb_convert_encoding($what, 'JIS', 'auto');
  115. if (ereg("[\"\\\r\n]", $what))
  116. return '{' . strlen($what) . "}\r\n" . $what; /* 4.3 literal form */
  117. return '"' . $what . '"'; /* 4.3 quoted string form */
  118. }
  119. /*
  120. Parses a user date string into an rfc2060 date string (<day number>-<US month TLA>-<4 digit year>)
  121. Returns a preg_match-style array: [0]: fully formatted date, [1]: day, [2]: month, [3]: year
  122. Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
  123. */
  124. function sqimap_asearch_parse_date($what)
  125. {
  126. global $imap_asearch_months;
  127. $what = trim($what);
  128. $what = ereg_replace('[ /\\.,]+', '-', $what);
  129. if ($what) {
  130. preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
  131. if (count($what_parts) == 4) {
  132. $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
  133. /* if (!in_array($what_month, $imap_asearch_months)) {*/
  134. foreach ($imap_asearch_months as $month_number => $month_code) {
  135. if (($what_month == $month_number)
  136. || ($what_month == $month_code)
  137. || ($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
  138. || ($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
  139. ) {
  140. $what_parts[2] = $month_number;
  141. $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
  142. break;
  143. }
  144. }
  145. /* }*/
  146. }
  147. }
  148. else
  149. $what_parts = array();
  150. return $what_parts;
  151. }
  152. function sqimap_asearch_build_criteria($opcode, $what, $search_charset)
  153. {
  154. global $imap_asearch_opcodes;
  155. $criteria = '';
  156. switch ($imap_asearch_opcodes[$opcode]) {
  157. default:
  158. case 'anum':
  159. /* $what = str_replace(' ', '', $what);*/
  160. $what = ereg_replace('[^0-9]+', '', $what);
  161. if ($what != '')
  162. $criteria = $opcode . ' ' . $what . ' ';
  163. break;
  164. case '': /* aflag */
  165. $criteria = $opcode . ' ';
  166. break;
  167. case 'afield': /* HEADER field-name: field-body */
  168. preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
  169. if (count($what_parts) == 3)
  170. $criteria = $opcode . ' ' .
  171. sqimap_asearch_encode_string($what_parts[1], $search_charset) . ' ' .
  172. sqimap_asearch_encode_string($what_parts[2], $search_charset) . ' ';
  173. break;
  174. case 'adate':
  175. $what_parts = sqimap_asearch_parse_date($what);
  176. if (isset($what_parts[0]))
  177. $criteria = $opcode . ' ' . $what_parts[0] . ' ';
  178. break;
  179. case 'akeyword':
  180. case 'astring':
  181. $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $search_charset) . ' ';
  182. break;
  183. case 'asequence':
  184. $what = ereg_replace('[^0-9:\(\)]+', '', $what);
  185. if ($what != '')
  186. $criteria = $opcode . ' ' . $what . ' ';
  187. break;
  188. }
  189. return $criteria;
  190. }
  191. function sqimap_run_search($imapConnection, $search_string, $search_charset)
  192. {
  193. global $allow_charset_search, $uid_support;
  194. /* 6.4.4 try OPTIONAL [CHARSET] specification first */
  195. if ($allow_charset_search && (!empty($search_charset)))
  196. $ss = 'SEARCH CHARSET ' . strtoupper($search_charset) . ' ALL ' . $search_string;
  197. else
  198. $ss = 'SEARCH ALL ' . $search_string;
  199. s_debug_dump('O', $ss);
  200. /* read data back from IMAP */
  201. $readin = sqimap_run_command($imapConnection, $ss, false, $result, $message, $uid_support);
  202. /* 6.4.4 try US-ASCII charset if we receive a tagged NO response */
  203. if (!empty($charset) && strtolower($result) == 'no') {
  204. $ss = 'SEARCH CHARSET "US-ASCII" ALL ' . $search_string;
  205. s_debug_dump('O', $ss);
  206. $readin = sqimap_run_command ($imapConnection, $ss, true, $result, $message); /* no $uid_support? */
  207. }
  208. unset($messagelist);
  209. /* Keep going till we find the SEARCH response */
  210. foreach ($readin as $readin_part) {
  211. s_debug_dump('I', $readin_part);
  212. /* Check to see if a SEARCH response was received */
  213. if (substr($readin_part, 0, 9) == '* SEARCH ') {
  214. $messagelist = preg_split("/ /", substr($readin_part, 9));
  215. } else if (isset($errors)) {
  216. $errors = $errors . $readin_part;
  217. } else {
  218. $errors = $readin_part;
  219. }
  220. }
  221. /* If nothing is found * SEARCH should be the first error else echo errors */
  222. if (isset($errors)) {
  223. if (strstr($errors,'* SEARCH'))
  224. return array();
  225. echo '<!-- ' . htmlspecialchars($errors) . ' -->';
  226. }
  227. if (empty($messagelist))
  228. return array();
  229. $cnt = count($messagelist);
  230. for ($q = 0; $q < $cnt; $q++)
  231. $id[$q] = trim($messagelist[$q]);
  232. return $id;
  233. }
  234. /* replaces $mbox_msgs[$search_mailbox] = array_values(array_unique(array_merge($mbox_msgs[$search_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset))));*/
  235. function sqimap_array_merge_unique($to, $from)
  236. {
  237. if (empty($to))
  238. return $from;
  239. for ($i=0; $i<count($from); $i++) {
  240. if (!in_array($from[$i], $to))
  241. $to[] = $from[$i];
  242. }
  243. return $to;
  244. }
  245. function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $mboxes_array)
  246. {
  247. global $languages, $squirrelmail_language;
  248. /* ??? what are those for ?? */
  249. /* $pos = $search_position;*/
  250. $mbox_msgs = array();
  251. $search_charset = $languages[$squirrelmail_language]['CHARSET'];
  252. $search_string = '';
  253. $cur_mailbox = $mailbox_array[0];
  254. $cur_biop = ''; /* Start with ALL */
  255. /* We loop one more time than the real array count, so the last search gets fired */
  256. for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++) {
  257. if (empty($exclude_array[$cur_crit])) {
  258. $next_mailbox = $mailbox_array[$cur_crit];
  259. if ($next_mailbox != $cur_mailbox) {
  260. $search_string = trim($search_string); /* Trim out last space */
  261. if (($cur_mailbox == 'All Folders') && (!empty($mboxes_array)))
  262. $search_mboxes = $mboxes_array;
  263. else
  264. $search_mboxes = array($cur_mailbox);
  265. foreach ($search_mboxes as $cur_mailbox) {
  266. sqimap_mailbox_select($imapConnection, $cur_mailbox);
  267. s_debug_dump('SELECT',$cur_mailbox);
  268. if (isset($mbox_msgs[$cur_mailbox])) {
  269. if ($cur_biop == 'OR') /* Merge with previous results */
  270. $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset));
  271. else /* Intersect previous results */
  272. $mbox_msgs[$cur_mailbox] = array_values(array_intersect(sqimap_run_search($imapConnection, $search_string, $search_charset), $mbox_msgs[$cur_mailbox]));
  273. }
  274. else /* No previous results */
  275. $mbox_msgs[$cur_mailbox] = sqimap_run_search($imapConnection, $search_string, $search_charset);
  276. if (empty($mbox_msgs[$cur_mailbox])) /* Can happen with intersect, and we need at the end a contiguous array */
  277. unset($mbox_msgs[$cur_mailbox]);
  278. }
  279. $cur_mailbox = $next_mailbox;
  280. $search_string = '';
  281. }
  282. if (isset($where_array[$cur_crit])) {
  283. $criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset);
  284. if (!empty($criteria)) {
  285. $unop = $unop_array[$cur_crit];
  286. if (!empty($unop))
  287. $criteria = $unop . ' ' . $criteria;
  288. /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
  289. $next_biop = '';
  290. for ($next_crit = $cur_crit+1; $next_crit <= count($where_array); $next_crit++) {
  291. if (empty($exclude_array[$next_crit])) {
  292. if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox)
  293. $next_biop = asearch_nz($biop_array[$next_crit]);
  294. break;
  295. }
  296. }
  297. if ($next_biop == 'OR')
  298. $criteria = $next_biop . ' ' . $criteria;
  299. $search_string .= $criteria;
  300. $cur_biop = asearch_nz($biop_array[$cur_crit]);
  301. }
  302. }
  303. }
  304. }
  305. return $mbox_msgs;
  306. }
  307. ?>