imap_asearch.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. * @author Alex Lemaresquier - Brainstorm - alex at brainstorm.fr
  10. * See README file for infos.
  11. * @package squirrelmail
  12. *
  13. */
  14. /** This functionality requires the IMAP and date functions */
  15. require_once(SM_PATH . 'functions/imap_general.php');
  16. require_once(SM_PATH . 'functions/date.php');
  17. /** Set to TRUE to dump the imap dialogue */
  18. $imap_asearch_debug_dump = FALSE;
  19. $imap_asearch_opcodes = array(
  20. /* <message set> => 'asequence', */
  21. /*'ALL' is binary operator */
  22. 'ANSWERED' => '',
  23. 'BCC' => 'astring',
  24. 'BEFORE' => 'adate',
  25. 'BODY' => 'astring',
  26. 'CC' => 'astring',
  27. 'DELETED' => '',
  28. 'DRAFT' => '',
  29. 'FLAGGED' => '',
  30. 'FROM' => 'astring',
  31. 'HEADER' => 'afield', /* Special syntax for this one, see below */
  32. 'KEYWORD' => 'akeyword',
  33. 'LARGER' => 'anum',
  34. 'NEW' => '',
  35. /*'NOT' is unary operator */
  36. 'OLD' => '',
  37. 'ON' => 'adate',
  38. /*'OR' is binary operator */
  39. 'RECENT' => '',
  40. 'SEEN' => '',
  41. 'SENTBEFORE' => 'adate',
  42. 'SENTON' => 'adate',
  43. 'SENTSINCE' => 'adate',
  44. 'SINCE' => 'adate',
  45. 'SMALLER' => 'anum',
  46. 'SUBJECT' => 'astring',
  47. 'TEXT' => 'astring',
  48. 'TO' => 'astring',
  49. 'UID' => 'asequence',
  50. 'UNANSWERED' => '',
  51. 'UNDELETED' => '',
  52. 'UNDRAFT' => '',
  53. 'UNFLAGGED' => '',
  54. 'UNKEYWORD' => 'akeyword',
  55. 'UNSEEN' => ''
  56. );
  57. $imap_asearch_months = array(
  58. '01' => 'jan',
  59. '02' => 'feb',
  60. '03' => 'mar',
  61. '04' => 'apr',
  62. '05' => 'may',
  63. '06' => 'jun',
  64. '07' => 'jul',
  65. '08' => 'aug',
  66. '09' => 'sep',
  67. '10' => 'oct',
  68. '11' => 'nov',
  69. '12' => 'dec'
  70. );
  71. $imap_error_titles = array(
  72. 'OK' => '',
  73. 'NO' => _("ERROR : Could not complete request."),
  74. 'BAD' => _("ERROR : Bad or malformed request."),
  75. 'BYE' => _("ERROR : Imap server closed the connection.")
  76. );
  77. // why can't this just use sqimap_error_box() ?
  78. // It does, indeed I isolated sqimap_error_box() as a stand-alone function just for this purpose ;)
  79. function sqimap_asearch_error_box($response, $query, $message)
  80. {
  81. global $imap_error_titles;
  82. //if (!array_key_exists($response, $imap_error_titles)) //php 4.0.6 compatibility
  83. if (!in_array($response, array_keys($imap_error_titles)))
  84. $title = _("ERROR : Unknown imap response.");
  85. else
  86. $title = $imap_error_titles[$response];
  87. $message_title = _("Reason Given: ");
  88. if (function_exists('sqimap_error_box'))
  89. sqimap_error_box($title, $query, $message_title, $message);
  90. else { //Straight copy of 1.5 imap_general.php:sqimap_error_box(). Can be removed at a later time
  91. global $color;
  92. require_once(SM_PATH . 'functions/display_messages.php');
  93. $string = "<font color=$color[2]><b>\n" . $title . "</b><br>\n";
  94. if ($query != '')
  95. $string .= _("Query:") . ' ' . htmlspecialchars($query) . '<br>';
  96. if ($message_title != '')
  97. $string .= $message_title;
  98. if ($message != '')
  99. $string .= htmlspecialchars($message);
  100. $string .= "</font><br>\n";
  101. error_box($string,$color);
  102. }
  103. }
  104. /**
  105. * This is to avoid the E_NOTICE warnings signaled by marc AT squirrelmail.org. Thanks Marc!
  106. */
  107. function asearch_nz(&$var)
  108. {
  109. if (isset($var))
  110. return $var;
  111. return '';
  112. }
  113. /**
  114. * This should give the same results as PHP 4 >= 4.3.0's html_entity_decode(),
  115. * except it doesn't handle hex constructs
  116. */
  117. function asearch_unhtmlentities($string) {
  118. $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES));
  119. for ($i=127; $i<255; $i++) /* Add &#<dec>; entities */
  120. $trans_tbl['&#' . $i . ';'] = chr($i);
  121. return strtr($string, $trans_tbl);
  122. /* I think the one above is quicker, though it should be benchmarked
  123. $string = strtr($string, array_flip(get_html_translation_table(HTML_ENTITIES)));
  124. return preg_replace("/&#([0-9]+);/E", "chr('\\1')", $string);
  125. */
  126. }
  127. function s_debug_dump($var_name, $var_var)
  128. {
  129. global $imap_asearch_debug_dump;
  130. if ($imap_asearch_debug_dump) {
  131. if (function_exists('sm_print_r')) //Only exists since 1.4.2
  132. sm_print_r($var_name, $var_var); //Better be the 'varargs' version ;)
  133. else {
  134. echo '<pre>';
  135. echo htmlentities($var_name);
  136. print_r($var_var);
  137. echo '</pre>';
  138. }
  139. }
  140. }
  141. /*
  142. 4.3 String:
  143. A quoted string is a sequence of zero or more 7-bit characters,
  144. excluding CR and LF, with double quote (<">) characters at each end.
  145. 9. Formal Syntax:
  146. quoted-specials = DQUOTE / "\"
  147. */
  148. function sqimap_asearch_encode_string($what, $charset)
  149. {
  150. if (strtoupper($charset) == 'ISO-2022-JP') // This should be now handled in imap_utf7_local?
  151. $what = mb_convert_encoding($what, 'JIS', 'auto');
  152. //if (ereg("[\"\\\r\n\x80-\xff]", $what))
  153. if (preg_match('/["\\\\\r\n\x80-\xff]/', $what))
  154. return '{' . strlen($what) . "}\r\n" . $what; // 4.3 literal form
  155. return '"' . $what . '"'; // 4.3 quoted string form
  156. }
  157. /**
  158. * Parses a user date string into an rfc2060 date string
  159. * (<day number>-<US month TLA>-<4 digit year>).
  160. * Returns a preg_match-style array: [0]: fully formatted date,
  161. * [1]: day, [2]: month, [3]: year
  162. * Handles space, slash, backslash, dot and comma as separators (and dash of course ;=)
  163. */
  164. function sqimap_asearch_parse_date($what)
  165. {
  166. global $imap_asearch_months;
  167. $what = trim($what);
  168. $what = ereg_replace('[ /\\.,]+', '-', $what);
  169. if ($what) {
  170. preg_match('/^([0-9]+)-+([^\-]+)-+([0-9]+)$/', $what, $what_parts);
  171. if (count($what_parts) == 4) {
  172. $what_month = strtolower(asearch_unhtmlentities($what_parts[2]));
  173. /* if (!in_array($what_month, $imap_asearch_months)) {*/
  174. foreach ($imap_asearch_months as $month_number => $month_code) {
  175. if (($what_month == $month_number)
  176. || ($what_month == $month_code)
  177. || ($what_month == strtolower(asearch_unhtmlentities(getMonthName($month_number))))
  178. || ($what_month == strtolower(asearch_unhtmlentities(getMonthAbrv($month_number))))
  179. ) {
  180. $what_parts[2] = $month_number;
  181. $what_parts[0] = $what_parts[1] . '-' . $month_code . '-' . $what_parts[3];
  182. break;
  183. }
  184. }
  185. /* }*/
  186. }
  187. }
  188. else
  189. $what_parts = array();
  190. return $what_parts;
  191. }
  192. function sqimap_asearch_build_criteria($opcode, $what, $charset)
  193. {
  194. global $imap_asearch_opcodes;
  195. $criteria = '';
  196. switch ($imap_asearch_opcodes[$opcode]) {
  197. default:
  198. case 'anum':
  199. /* $what = str_replace(' ', '', $what);*/
  200. $what = ereg_replace('[^0-9]+', '', $what);
  201. if ($what != '')
  202. $criteria = $opcode . ' ' . $what . ' ';
  203. break;
  204. case '': /* aflag */
  205. $criteria = $opcode . ' ';
  206. break;
  207. case 'afield': /* HEADER field-name: field-body */
  208. preg_match('/^([^:]+):(.*)$/', $what, $what_parts);
  209. if (count($what_parts) == 3)
  210. $criteria = $opcode . ' ' .
  211. sqimap_asearch_encode_string($what_parts[1], $charset) . ' ' .
  212. sqimap_asearch_encode_string($what_parts[2], $charset) . ' ';
  213. break;
  214. case 'adate':
  215. $what_parts = sqimap_asearch_parse_date($what);
  216. if (isset($what_parts[0]))
  217. $criteria = $opcode . ' ' . $what_parts[0] . ' ';
  218. break;
  219. case 'akeyword':
  220. case 'astring':
  221. $criteria = $opcode . ' ' . sqimap_asearch_encode_string($what, $charset) . ' ';
  222. break;
  223. case 'asequence':
  224. $what = ereg_replace('[^0-9:\(\)]+', '', $what);
  225. if ($what != '')
  226. $criteria = $opcode . ' ' . $what . ' ';
  227. break;
  228. }
  229. return $criteria;
  230. }
  231. function sqimap_run_search($imapConnection, $search_string, $search_charset)
  232. {
  233. global $uid_support;
  234. /* 6.4.4 try OPTIONAL [CHARSET] specification first */
  235. if ($search_charset != '')
  236. $query = 'SEARCH CHARSET "' . strtoupper($search_charset) . '" ALL ' . $search_string;
  237. else
  238. $query = 'SEARCH ALL ' . $search_string;
  239. s_debug_dump('C:', $query);
  240. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
  241. /* 6.4.4 try US-ASCII charset if we tried an OPTIONAL [CHARSET] and received a tagged NO response (SHOULD be [BADCHARSET]) */
  242. if (($search_charset != '') && (strtoupper($response) == 'NO')) {
  243. $query = 'SEARCH CHARSET US-ASCII ALL ' . $search_string;
  244. s_debug_dump('C:', $query);
  245. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
  246. }
  247. if (strtoupper($response) != 'OK') {
  248. sqimap_asearch_error_box($response, $query, $message);
  249. return array();
  250. }
  251. unset($messagelist);
  252. /* Keep going till we find the * SEARCH response */
  253. foreach ($readin as $readin_part) {
  254. s_debug_dump('S:', $readin_part);
  255. if (substr($readin_part, 0, 9) == '* SEARCH ') {
  256. $messagelist = preg_split("/ /", substr($readin_part, 9));
  257. break; // Should be the last anyway
  258. }
  259. /* else {
  260. if (isset($errors))
  261. $errors = $errors . $readin_part;
  262. else
  263. $errors = $readin_part;
  264. }*/
  265. }
  266. /* If nothing is found * SEARCH should be the first error else echo errors */
  267. /*if (isset($errors)) {
  268. if (strstr($errors,'* SEARCH'))
  269. return array();
  270. echo '<!-- ' . htmlspecialchars($errors) . ' -->';
  271. }*/
  272. if (empty($messagelist)) //Empty search response, ie '* SEARCH'
  273. return array();
  274. $cnt = count($messagelist);
  275. for ($q = 0; $q < $cnt; $q++)
  276. $id[$q] = trim($messagelist[$q]);
  277. return $id;
  278. }
  279. function sqimap_run_sort($imapConnection, $search_string, $search_charset, $sort_criteria)
  280. {
  281. global $uid_support;
  282. if ($search_charset == '')
  283. $search_charset = 'US-ASCII';
  284. $query = 'SORT (' . $sort_criteria . ') ' . strtoupper($search_charset) . ' ALL ' . $search_string;
  285. s_debug_dump('C:', $query);
  286. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
  287. /* 6.4 try US-ASCII charset if we received a tagged NO response (SHOULD be [BADCHARSET]) */
  288. if (($search_charset != 'US-ASCII') && (strtoupper($response) == 'NO')) {
  289. $query = 'SORT (' . $sort_criteria . ') US-ASCII ALL ' . $search_string;
  290. s_debug_dump('C:', $query);
  291. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
  292. }
  293. if (strtoupper($response) != 'OK') {
  294. // sqimap_asearch_error_box($response, $query, $message);
  295. // return array();
  296. return sqimap_run_search($imapConnection, $search_string, $search_charset); // Fell back to standard search
  297. }
  298. /* Keep going till we find the * SORT response */
  299. foreach ($readin as $readin_part) {
  300. s_debug_dump('S:', $readin_part);
  301. if (substr($readin_part, 0, 7) == '* SORT ') {
  302. $messagelist = preg_split("/ /", substr($readin_part, 7));
  303. break; // Should be the last anyway
  304. }
  305. }
  306. if (empty($messagelist)) //Empty search response, ie '* SORT'
  307. return array();
  308. $cnt = count($messagelist);
  309. for ($q = 0; $q < $cnt; $q++)
  310. $id[$q] = trim($messagelist[$q]);
  311. return $id;
  312. }
  313. function sqimap_run_thread($imapConnection, $search_string, $search_charset, $thread_algorithm)
  314. {
  315. global $thread_new, $server_sort_array;
  316. if (sqsession_is_registered('thread_new'))
  317. sqsession_unregister('thread_new');
  318. if (sqsession_is_registered('server_sort_array'))
  319. sqsession_unregister('server_sort_array');
  320. $thread_new = array();
  321. $thread_new[0] = "";
  322. $server_sort_array = array();
  323. global $uid_support;
  324. if ($search_charset == '')
  325. $search_charset = 'US-ASCII';
  326. $query = 'THREAD ' . $thread_algorithm . ' ' . strtoupper($search_charset) . ' ALL ' . $search_string;
  327. s_debug_dump('C:', $query);
  328. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
  329. /* 6.4 try US-ASCII charset if we received a tagged NO response (SHOULD be [BADCHARSET]) */
  330. if (($search_charset != 'US-ASCII') && (strtoupper($response) == 'NO')) {
  331. $query = 'THREAD ' . $thread_algorithm . ' US-ASCII ALL ' . $search_string;
  332. s_debug_dump('C:', $query);
  333. $readin = sqimap_run_command($imapConnection, $query, false, $response, $message, $uid_support);
  334. }
  335. if (strtoupper($response) != 'OK') {
  336. // sqimap_asearch_error_box($response, $query, $message);
  337. // return array();
  338. return sqimap_run_search($imapConnection, $search_string, $search_charset); // Fell back to standard search
  339. }
  340. /* Keep going till we find the * THREAD response */
  341. foreach ($readin as $readin_part) {
  342. s_debug_dump('S:', $readin_part);
  343. if (substr($readin_part, 0, 9) == '* THREAD ') {
  344. $thread_temp = preg_split("//", substr($readin_part, 9), -1, PREG_SPLIT_NO_EMPTY);
  345. break; // Should be the last anyway
  346. }
  347. }
  348. if (empty($thread_temp)) //Empty search response, ie '* THREAD'
  349. return array();
  350. $char_count = count($thread_temp);
  351. $counter = 0;
  352. $k = 0;
  353. for ($i=0;$i<$char_count;$i++) {
  354. if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
  355. $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
  356. }
  357. elseif ($thread_temp[$i] == '(') {
  358. $thread_new[$k] .= $thread_temp[$i];
  359. $counter++;
  360. }
  361. elseif ($thread_temp[$i] == ')') {
  362. if ($counter > 1) {
  363. $thread_new[$k] .= $thread_temp[$i];
  364. $counter = $counter - 1;
  365. }
  366. else {
  367. $thread_new[$k] .= $thread_temp[$i];
  368. $k++;
  369. $thread_new[$k] = "";
  370. $counter = $counter - 1;
  371. }
  372. }
  373. }
  374. sqsession_register($thread_new, 'thread_new');
  375. $thread_new = array_reverse($thread_new);
  376. $thread_list = implode(" ", $thread_new);
  377. $thread_list = str_replace("(", " ", $thread_list);
  378. $thread_list = str_replace(")", " ", $thread_list);
  379. $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
  380. $server_sort_array = $thread_list;
  381. sqsession_register($server_sort_array, 'server_sort_array');
  382. return $thread_list;
  383. }
  384. function sqimap_asearch_get_charset()
  385. {
  386. global $allow_charset_search, $languages, $squirrelmail_language;
  387. if ($allow_charset_search)
  388. return $languages[$squirrelmail_language]['CHARSET'];
  389. return '';
  390. }
  391. function sqimap_asearch_get_sort_criteria($mailbox, $sort_by)
  392. {
  393. global $internal_date_sort, $sent_folder;
  394. $sort_opcodes = array ('DATE', 'FROM', 'SUBJECT');
  395. if ($internal_date_sort == true)
  396. $sort_opcodes[0] = 'ARRIVAL';
  397. // if (handleAsSent($mailbox))
  398. // if (isSentFolder($mailbox))
  399. if ($mailbox == $sent_folder)
  400. $sort_opcodes[1] = 'TO';
  401. return (($sort_by % 2) ? '' : 'REVERSE ') . $sort_opcodes[$sort_by >> 1];
  402. }
  403. /* replaces $mbox_msgs[$search_mailbox] = array_values(array_unique(array_merge($mbox_msgs[$search_mailbox], sqimap_run_search($imapConnection, $search_string, $search_charset))));*/
  404. function sqimap_array_merge_unique($to, $from)
  405. {
  406. if (empty($to))
  407. return $from;
  408. for ($i=0; $i<count($from); $i++) {
  409. if (!in_array($from[$i], $to))
  410. $to[] = $from[$i];
  411. }
  412. return $to;
  413. }
  414. function sqimap_asearch($imapConnection, $mailbox_array, $biop_array, $unop_array, $where_array, $what_array, $exclude_array, $mboxes_array)
  415. {
  416. global $allow_server_sort, $sort, $allow_thread_sort, $thread_sort_messages;
  417. global $data_dir, $username;
  418. $search_charset = sqimap_asearch_get_charset();
  419. $mbox_msgs = array();
  420. $search_string = '';
  421. $cur_mailbox = $mailbox_array[0];
  422. $cur_biop = ''; /* Start with ALL */
  423. /* We loop one more time than the real array count, so the last search gets fired */
  424. for ($cur_crit = 0; $cur_crit <= count($where_array); $cur_crit++) {
  425. if (empty($exclude_array[$cur_crit])) {
  426. $next_mailbox = $mailbox_array[$cur_crit];
  427. if ($next_mailbox != $cur_mailbox) {
  428. $search_string = trim($search_string); /* Trim out last space */
  429. if (($cur_mailbox == 'All Folders') && (!empty($mboxes_array)))
  430. $search_mboxes = $mboxes_array;
  431. else
  432. $search_mboxes = array($cur_mailbox);
  433. foreach ($search_mboxes as $cur_mailbox) {
  434. s_debug_dump('C:SELECT:', $cur_mailbox);
  435. sqimap_mailbox_select($imapConnection, $cur_mailbox);
  436. $thread_sort_messages = $allow_thread_sort && getPref($data_dir, $username, 'thread_' . $cur_mailbox);
  437. if ($thread_sort_messages) {
  438. $thread_algorithm = 'REFERENCES';
  439. $found_msgs = sqimap_run_thread($imapConnection, $search_string, $search_charset, $thread_algorithm);
  440. }
  441. else
  442. if (($allow_server_sort) && ($sort < 6)) {
  443. $sort_criteria = sqimap_asearch_get_sort_criteria($cur_mailbox, $sort);
  444. $found_msgs = sqimap_run_sort($imapConnection, $search_string, $search_charset, $sort_criteria);
  445. }
  446. else
  447. $found_msgs = sqimap_run_search($imapConnection, $search_string, $search_charset);
  448. if (isset($mbox_msgs[$cur_mailbox])) {
  449. if ($cur_biop == 'OR') /* Merge with previous results */
  450. $mbox_msgs[$cur_mailbox] = sqimap_array_merge_unique($mbox_msgs[$cur_mailbox], $found_msgs);
  451. else /* Intersect previous results */
  452. $mbox_msgs[$cur_mailbox] = array_values(array_intersect($found_msgs, $mbox_msgs[$cur_mailbox]));
  453. }
  454. else /* No previous results */
  455. $mbox_msgs[$cur_mailbox] = $found_msgs;
  456. if (empty($mbox_msgs[$cur_mailbox])) /* Can happen with intersect, and we need at the end a contiguous array */
  457. unset($mbox_msgs[$cur_mailbox]);
  458. }
  459. $cur_mailbox = $next_mailbox;
  460. $search_string = '';
  461. }
  462. if (isset($where_array[$cur_crit])) {
  463. $criteria = sqimap_asearch_build_criteria($where_array[$cur_crit], $what_array[$cur_crit], $search_charset);
  464. if (!empty($criteria)) {
  465. $unop = $unop_array[$cur_crit];
  466. if (!empty($unop))
  467. $criteria = $unop . ' ' . $criteria;
  468. /* We need to infix the next non-excluded criteria's biop if it's the same mailbox */
  469. $next_biop = '';
  470. for ($next_crit = $cur_crit+1; $next_crit <= count($where_array); $next_crit++) {
  471. if (empty($exclude_array[$next_crit])) {
  472. if (asearch_nz($mailbox_array[$next_crit]) == $cur_mailbox)
  473. $next_biop = asearch_nz($biop_array[$next_crit]);
  474. break;
  475. }
  476. }
  477. if ($next_biop == 'OR')
  478. $criteria = $next_biop . ' ' . $criteria;
  479. $search_string .= $criteria;
  480. $cur_biop = asearch_nz($biop_array[$cur_crit]);
  481. }
  482. }
  483. }
  484. }
  485. return $mbox_msgs;
  486. }
  487. ?>