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