don't issue imap commands when target mailbox is same as source mailbox.
[squirrelmail.git] / functions / imap_messages.php
1 <?php
2
3 /**
4 * imap_messages.php
5 *
6 * This implements functions that manipulate messages
7 * NOTE: Quite a few functions in this file are obsolete
8 *
9 * @copyright &copy; 1999-2005 The SquirrelMail Project Team
10 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
11 * @version $Id$
12 * @package squirrelmail
13 * @subpackage imap
14 */
15
16
17 /**
18 * Copy a set of messages ($id) to another mailbox ($mailbox)
19 * @param int $imap_stream The resource ID for the IMAP socket
20 * @param string $id The list of messages to copy
21 * @param string $mailbox The destination to copy to
22 * @param bool $handle_errors Show error messages in case of a NO, BAD or BYE response
23 * @return bool If the copy completed without errors
24 */
25 function sqimap_msgs_list_copy($imap_stream, $id, $mailbox, $handle_errors = true) {
26 $msgs_id = sqimap_message_list_squisher($id);
27 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($mailbox), $handle_errors, $response, $message, TRUE);
28 if ($response == 'OK') {
29 return true;
30 } else {
31 return false;
32 }
33 }
34
35
36 /**
37 * Move a set of messages ($id) to another mailbox. Deletes the originals.
38 * @param int $imap_stream The resource ID for the IMAP socket
39 * @param string $id The list of messages to move
40 * @param string $mailbox The destination to move to
41 * @param bool $handle_errors Show error messages in case of a NO, BAD or BYE response
42 * @param string $source_mailbox (since 1.5.1) name of source mailbox. It is used to
43 * validate that target mailbox != source mailbox.
44 * @return bool If the move completed without errors
45 */
46 function sqimap_msgs_list_move($imap_stream, $id, $mailbox, $handle_errors = true, $source_mailbox = false) {
47 if ($source_mailbox!==false && $source_mailbox==$mailbox) {
48 return false;
49 }
50 $msgs_id = sqimap_message_list_squisher($id);
51 if (sqimap_msgs_list_copy ($imap_stream, $id, $mailbox, $handle_errors)) {
52 return sqimap_toggle_flag($imap_stream, $id, '\\Deleted', true, true);
53 } else {
54 return false;
55 }
56 }
57
58
59 /**
60 * Deletes a message and move it to trash or expunge the mailbox
61 * @param resource imap connection
62 * @param string $mailbox mailbox, used for checking if it concerns the trash_folder
63 * @param array $id list with uid's
64 * @param bool $bypass_trash (since 1.5.0) skip copy to trash
65 * @return array $aMessageList array with messages containing the new flags and UID @see parseFetch
66 * @since 1.4.0
67 */
68 function sqimap_msgs_list_delete($imap_stream, $mailbox, $id, $bypass_trash=false) {
69 // FIX ME, remove globals by introducing an associative array with properties
70 // as 4th argument as replacement for the bypass_trash var
71 global $move_to_trash, $trash_folder;
72 $bRes = true;
73 if (($move_to_trash == true) && ($bypass_trash != true) &&
74 (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder)) ) {
75 $bRes = sqimap_msgs_list_copy ($imap_stream, $id, $trash_folder);
76 }
77 if ($bRes) {
78 return sqimap_toggle_flag($imap_stream, $id, '\\Deleted', true, true);
79 } else {
80 return false;
81 }
82 }
83
84
85 /**
86 * Set a flag on the provided uid list
87 * @param resource imap connection
88 * @param array $id list with uid's
89 * @param string $flag Flags to set/unset flags can be i.e.'\Seen', '\Answered', '\Seen \Answered'
90 * @param bool $set add (true) or remove (false) the provided flag
91 * @param bool $handle_errors Show error messages in case of a NO, BAD or BYE response
92 * @return array $aMessageList array with messages containing the new flags and UID @see parseFetch
93 */
94 function sqimap_toggle_flag($imap_stream, $id, $flag, $set, $handle_errors) {
95 $msgs_id = sqimap_message_list_squisher($id);
96 $set_string = ($set ? '+' : '-');
97
98 for ($i=0; $i<sizeof($id); $i++) {
99 $aMessageList["$id[$i]"] = array();
100 }
101
102 $aResponse = sqimap_run_command_list($imap_stream, "STORE $msgs_id ".$set_string."FLAGS ($flag)", $handle_errors, $response, $message, TRUE);
103
104 // parse the fetch response
105 $parseFetchResults=parseFetch($aResponse,$aMessageList);
106
107 // some broken IMAP servers do not return UID elements on UID STORE
108 // if this is the case, then we need to do a UID FETCH
109 $testkey=$id[0];
110 if (!isset($parseFetchResults[$testkey]['UID'])) {
111 $aResponse = sqimap_run_command_list($imap_stream, "FETCH $msgs_id (FLAGS)", $handle_errors, $response, $message, TRUE);
112 $parseFetchResults = parseFetch($aResponse,$aMessageList);
113 }
114
115 return ($parseFetchResults);
116 }
117
118
119 /**
120 * Sort the message list and crunch to be as small as possible
121 * (overflow could happen, so make it small if possible)
122 */
123 function sqimap_message_list_squisher($messages_array) {
124 if( !is_array( $messages_array ) ) {
125 return $messages_array;
126 }
127
128 sort($messages_array, SORT_NUMERIC);
129 $msgs_str = '';
130 while ($messages_array) {
131 $start = array_shift($messages_array);
132 $end = $start;
133 while (isset($messages_array[0]) && $messages_array[0] == $end + 1) {
134 $end = array_shift($messages_array);
135 }
136 if ($msgs_str != '') {
137 $msgs_str .= ',';
138 }
139 $msgs_str .= $start;
140 if ($start != $end) {
141 $msgs_str .= ':' . $end;
142 }
143 }
144 return $msgs_str;
145 }
146
147
148 /**
149 * Retrieves an array with a sorted uid list. Sorting is done on the imap server
150 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-17.txt
151 * @param resource $imap_stream IMAP socket connection
152 * @param string $sSortField Field to sort on
153 * @param bool $reverse Reverse order search
154 * @return array $id sorted uid list
155 */
156 function sqimap_get_sort_order($imap_stream, $sSortField, $reverse, $search='ALL') {
157 global $default_charset;
158
159 if ($sSortField) {
160 if ($reverse) {
161 $sSortField = 'REVERSE '.$sSortField;
162 }
163 $query = "SORT ($sSortField) ".strtoupper($default_charset)." $search";
164 // FIX ME sqimap_run_command should return the parsed data accessible by $aDATA['SORT']
165 $aData = sqimap_run_command ($imap_stream, $query, false, $response, $message, TRUE);
166 /* fallback to default charset */
167 if ($response == 'NO' && strpos($message,'[BADCHARSET]') !== false) {
168 $query = "SORT ($sSortField) US-ASCII $search";
169 $aData = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
170 }
171 }
172
173 if ($response == 'OK') {
174 return parseUidList($aData,'SORT');
175 } else {
176 return false;
177 }
178 }
179
180
181 /**
182 * Parses a UID list returned on a SORT or SEARCH request
183 * @param array $aData imap response
184 * @param string $sCommand issued imap command (SEARCH or SORT)
185 * @return array $aUid uid list
186 */
187 function parseUidList($aData,$sCommand) {
188 $aUid = array();
189 if (isset($aData) && count($aData)) {
190 for ($i=0,$iCnt=count($aData);$i<$iCnt;++$i) {
191 if (preg_match("/^\* $sCommand (.+)$/", $aData[$i], $aMatch)) {
192 $aUid += preg_split("/ /", trim($aMatch[1]));
193 }
194 }
195 }
196 return array_unique($aUid);
197 }
198
199 /**
200 * Retrieves an array with a sorted uid list. Sorting is done by SquirrelMail
201 *
202 * @param resource $imap_stream IMAP socket connection
203 * @param string $sSortField Field to sort on
204 * @param bool $reverse Reverse order search
205 * @param array $aUid limit the search to the provided array with uid's default sqimap_get_small_headers uses 1:*
206 * @return array $aUid sorted uid list
207 */
208 function get_squirrel_sort($imap_stream, $sSortField, $reverse = false, $aUid = NULL) {
209 if ($sSortField != 'RFC822.SIZE' && $sSortField != 'INTERNALDATE') {
210 $msgs = sqimap_get_small_header_list($imap_stream, $aUid,
211 array($sSortField), array());
212 } else {
213 $msgs = sqimap_get_small_header_list($imap_stream, $aUid,
214 array(), array($sSortField));
215 }
216 $aUid = array();
217 $walk = false;
218 switch ($sSortField) {
219 // natcasesort section
220 case 'FROM':
221 case 'TO':
222 case 'CC':
223 if(!$walk) {
224 array_walk($msgs, create_function('&$v,&$k,$f',
225 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
226 $addr = reset(parseRFC822Address($v[$f],1));
227 $sPersonal = (isset($addr[SQM_ADDR_PERSONAL]) && $addr[SQM_ADDR_PERSONAL]) ?
228 $addr[SQM_ADDR_PERSONAL] : "";
229 $sEmail = ($addr[SQM_ADDR_HOST]) ?
230 $addr[SQM_ADDR_MAILBOX] . "@".$addr[SQM_ADDR_HOST] :
231 $addr[SQM_ADDR_HOST];
232 $v[$f] = ($sPersonal) ? decodeHeader($sPersonal):$sEmail;'),$sSortField);
233 $walk = true;
234 }
235 // nobreak
236 case 'SUBJECT':
237 if(!$walk) {
238 array_walk($msgs, create_function('&$v,&$k,$f',
239 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
240 $v[$f] = strtolower(decodeHeader(trim($v[$f])));
241 $v[$f] = (preg_match("/^(vedr|sv|re|aw|\[\w\]):\s*(.*)$/si", $v[$f], $matches)) ?
242 $matches[2] : $v[$f];'),$sSortField);
243 $walk = true;
244 }
245 foreach ($msgs as $item) {
246 $aUid[$item['UID']] = $item[$sSortField];
247 }
248 natcasesort($aUid);
249 $aUid = array_keys($aUid);
250 if ($reverse) {
251 $aUid = array_reverse($aUid);
252 }
253 break;
254 // \natcasesort section
255 // sort_numeric section
256 case 'DATE':
257 case 'INTERNALDATE':
258 if(!$walk) {
259 array_walk($msgs, create_function('&$v,$k,$f',
260 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
261 $v[$f] = getTimeStamp(explode(" ",$v[$f]));'),$sSortField);
262 $walk = true;
263 }
264 // nobreak;
265 case 'RFC822.SIZE':
266 if(!$walk) {
267 // redefine $sSortField to maintain the same namespace between
268 // server-side sorting and SquirrelMail sorting
269 $sSortField = 'SIZE';
270 }
271 foreach ($msgs as $item) {
272 $aUid[$item['UID']] = (isset($item[$sSortField])) ? $item[$sSortField] : 0;
273 }
274 if ($reverse) {
275 arsort($aUid,SORT_NUMERIC);
276 } else {
277 asort($aUid, SORT_NUMERIC);
278 }
279 $aUid = array_keys($aUid);
280 break;
281 // \sort_numeric section
282 case 'UID':
283 $aUid = array_reverse($msgs);
284 break;
285 }
286 return $aUid;
287 }
288
289
290 /**
291 * Returns an indent array for printMessageinfo()
292 * This represents the amount of indent needed (value),
293 * for this message number (key)
294 */
295
296 /*
297 * Notes for future work:
298 * indent_array should contain: indent_level, parent and flags,
299 * sibling notes ..
300 * To achieve that we need to define the following flags:
301 * 0: hasnochildren
302 * 1: haschildren
303 * 2: is first
304 * 4: is last
305 * a node has sibling nodes if it's not the last node
306 * a node has no sibling nodes if it's the last node
307 * By using binary comparations we can store the flag in one var
308 *
309 * example:
310 * -1 par = 0, level = 0, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
311 * \-2 par = 1, level = 1, flag = 0 + 2 = 2 (hasnochildren, isfirst)
312 * |-3 par = 1, level = 1, flag = 1 + 4 = 5 (haschildren, islast)
313 * \-4 par = 3, level = 2, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
314 * \-5 par = 4, level = 3, flag = 0 + 2 + 4 = 6 (hasnochildren, isfirst, islast)
315 */
316 function get_parent_level($thread_new) {
317 $parent = '';
318 $child = '';
319 $cutoff = 0;
320
321 /*
322 * loop through the threads and take unwanted characters out
323 * of the thread string then chop it up
324 */
325 for ($i=0;$i<count($thread_new);$i++) {
326 $thread_new[$i] = preg_replace("/\s\(/", "(", $thread_new[$i]);
327 $thread_new[$i] = preg_replace("/(\d+)/", "$1|", $thread_new[$i]);
328 $thread_new[$i] = preg_split("/\|/", $thread_new[$i], -1, PREG_SPLIT_NO_EMPTY);
329 }
330 $indent_array = array();
331 if (!$thread_new) {
332 $thread_new = array();
333 }
334 /* looping through the parts of one message thread */
335
336 for ($i=0;$i<count($thread_new);$i++) {
337 /* first grab the parent, it does not indent */
338
339 if (isset($thread_new[$i][0])) {
340 if (preg_match("/(\d+)/", $thread_new[$i][0], $regs)) {
341 $parent = $regs[1];
342 }
343 }
344 $indent_array[$parent] = 0;
345
346 /*
347 * now the children, checking each thread portion for
348 * ),(, and space, adjusting the level and space values
349 * to get the indent level
350 */
351 $level = 0;
352 $spaces = array();
353 $spaces_total = 0;
354 $indent = 0;
355 $fake = FALSE;
356 for ($k=1,$iCnt=count($thread_new[$i])-1;$k<$iCnt;++$k) {
357 $chars = count_chars($thread_new[$i][$k], 1);
358 if (isset($chars['40'])) { /* testing for ( */
359 $level += $chars['40'];
360 }
361 if (isset($chars['41'])) { /* testing for ) */
362 $level -= $chars['41'];
363 $spaces[$level] = 0;
364 /* if we were faking lets stop, this portion
365 * of the thread is over
366 */
367 if ($level == $cutoff) {
368 $fake = FALSE;
369 }
370 }
371 if (isset($chars['32'])) { /* testing for space */
372 if (!isset($spaces[$level])) {
373 $spaces[$level] = 0;
374 }
375 $spaces[$level] += $chars['32'];
376 }
377 for ($x=0;$x<=$level;$x++) {
378 if (isset($spaces[$x])) {
379 $spaces_total += $spaces[$x];
380 }
381 }
382 $indent = $level + $spaces_total;
383 /* must have run into a message that broke the thread
384 * so we are adjusting for that portion
385 */
386 if ($fake == TRUE) {
387 $indent = $indent +1;
388 }
389 if (preg_match("/(\d+)/", $thread_new[$i][$k], $regs)) {
390 $child = $regs[1];
391 }
392 /* the thread must be broken if $indent == 0
393 * so indent the message once and start faking it
394 */
395 if ($indent == 0) {
396 $indent = 1;
397 $fake = TRUE;
398 $cutoff = $level;
399 }
400 /* dont need abs but if indent was negative
401 * errors would occur
402 */
403 $indent_array[$child] = ($indent < 0) ? 0 : $indent;
404 $spaces_total = 0;
405 }
406 }
407 return $indent_array;
408 }
409
410
411 /**
412 * Returns an array with each element as a string representing one
413 * message-thread as returned by the IMAP server.
414 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
415 */
416 function get_thread_sort($imap_stream, $search='ALL') {
417 global $thread_new, $sort_by_ref, $default_charset, $server_sort_array, $indent_array;
418
419 $thread_temp = array ();
420 if ($sort_by_ref == 1) {
421 $sort_type = 'REFERENCES';
422 } else {
423 $sort_type = 'ORDEREDSUBJECT';
424 }
425 $query = "THREAD $sort_type ".strtoupper($default_charset)." $search";
426
427 $thread_test = sqimap_run_command ($imap_stream, $query, false, $response, $message, TRUE);
428 /* fallback to default charset */
429 if ($response == 'NO' && strpos($message,'[BADCHARSET]') !== false) {
430 $query = "THREAD $sort_type US-ASCII $search";
431 $thread_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
432 }
433 if (isset($thread_test[0])) {
434 for ($i=0,$iCnt=count($thread_test);$i<$iCnt;++$i) {
435 if (preg_match("/^\* THREAD (.+)$/", $thread_test[$i], $regs)) {
436 $thread_list = trim($regs[1]);
437 break;
438 }
439 }
440 } else {
441 $thread_list = "";
442 }
443 if (!preg_match("/OK/", $response)) {
444 $server_sort_array = 'no';
445 return $server_sort_array;
446 }
447 if (isset($thread_list)) {
448 $thread_temp = preg_split("//", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
449 }
450
451 $counter = 0;
452 $thread_new = array();
453 $k = 0;
454 $thread_new[0] = "";
455 /*
456 * parse the thread response into separate threads
457 *
458 * example:
459 * [0] => (540)
460 * [1] => (1386)
461 * [2] => (1599 759 959 37)
462 * [3] => (492 1787)
463 * [4] => ((933)(1891))
464 * [5] => (1030 (1497)(845)(1637))
465 */
466 for ($i=0,$iCnt=count($thread_temp);$i<$iCnt;$i++) {
467 if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
468 $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
469 } elseif ($thread_temp[$i] == '(') {
470 $thread_new[$k] .= $thread_temp[$i];
471 $counter++;
472 } elseif ($thread_temp[$i] == ')') {
473 if ($counter > 1) {
474 $thread_new[$k] .= $thread_temp[$i];
475 $counter = $counter - 1;
476 } else {
477 $thread_new[$k] .= $thread_temp[$i];
478 $k++;
479 $thread_new[$k] = "";
480 $counter = $counter - 1;
481 }
482 }
483 }
484
485 $thread_new = array_reverse($thread_new);
486 /* place the threads after each other in one string */
487 $thread_list = implode(" ", $thread_new);
488 $thread_list = str_replace("(", " ", $thread_list);
489 $thread_list = str_replace(")", " ", $thread_list);
490 $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY);
491 $server_sort_array = $thread_list;
492
493 $indent_array = get_parent_level ($thread_new);
494 return array($thread_list,$indent_array);
495 }
496
497
498 function elapsedTime($start) {
499 $stop = gettimeofday();
500 $timepassed = 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'];
501 return $timepassed;
502 }
503
504
505 /**
506 * Normalise the different Priority headers into a uniform value,
507 * namely that of the X-Priority header (1, 3, 5). Supports:
508 * Prioirty, X-Priority, Importance.
509 * X-MS-Mail-Priority is not parsed because it always coincides
510 * with one of the other headers.
511 *
512 * FIXME: DUPLICATE CODE ALERT:
513 * NOTE: this is actually a duplicate from the function in
514 * class/mime/Rfc822Header.php.
515 * @todo obsolate function or use it instead of code block in parseFetch()
516 */
517 function parsePriority($sValue) {
518 $aValue = split('/\w/',trim($sValue));
519 $value = strtolower(array_shift($aValue));
520 if ( is_numeric($value) ) {
521 return $value;
522 }
523 if ( $value == 'urgent' || $value == 'high' ) {
524 return 1;
525 } elseif ( $value == 'non-urgent' || $value == 'low' ) {
526 return 5;
527 }
528 return 3;
529 }
530
531 /**
532 * Parses a string in an imap response. String starts with " or { which means it
533 * can handle double quoted strings and literal strings
534 *
535 * @param string $read imap response
536 * @param integer $i (reference) offset in string
537 * @return string $s parsed string without the double quotes or literal count
538 */
539 function parseString($read,&$i) {
540 $char = $read{$i};
541 $s = '';
542 if ($char == '"') {
543 $iPos = ++$i;
544 while (true) {
545 $iPos = strpos($read,'"',$iPos);
546 if (!$iPos) break;
547 if ($iPos && $read{$iPos -1} != '\\') {
548 $s = substr($read,$i,($iPos-$i));
549 $i = $iPos;
550 break;
551 }
552 $iPos++;
553 if ($iPos > strlen($read)) {
554 break;
555 }
556 }
557 } else if ($char == '{') {
558 $lit_cnt = '';
559 ++$i;
560 $iPos = strpos($read,'}',$i);
561 if ($iPos) {
562 $lit_cnt = substr($read, $i, $iPos - $i);
563 $i += strlen($lit_cnt) + 3; /* skip } + \r + \n */
564 /* Now read the literal */
565 $s = ($lit_cnt ? substr($read,$i,$lit_cnt): '');
566 $i += $lit_cnt;
567 /* temp bugfix (SM 1.5 will have a working clean version)
568 too much work to implement that version right now */
569 --$i;
570 } else { /* should never happen */
571 $i += 3; /* } + \r + \n */
572 $s = '';
573 }
574 } else {
575 return false;
576 }
577 ++$i;
578 return $s;
579 }
580
581
582 /**
583 * Parses a string containing an array from an imap response. String starts with ( and end with )
584 *
585 * @param string $read imap response
586 * @param integer $i (reference) offset in string
587 * @return array $a
588 */
589 function parseArray($read,&$i) {
590 $i = strpos($read,'(',$i);
591 $i_pos = strpos($read,')',$i);
592 $s = substr($read,$i+1,$i_pos - $i -1);
593 $a = explode(' ',$s);
594 if ($i_pos) {
595 $i = $i_pos+1;
596 return $a;
597 } else {
598 return false;
599 }
600 }
601
602
603 /**
604 * Retrieves a list with headers, flags, size or internaldate from the imap server
605 *
606 * WARNING: function is not portable between SquirrelMail 1.2.x, 1.4.x and 1.5.x.
607 * Output format, third argument and $msg_list array format requirements differ.
608 * @param stream $imap_stream imap connection
609 * @param array $msg_list array with id's to create a msgs set from
610 * @param array $aHeaderFields (since 1.5.0) requested header fields
611 * @param array $aFetchItems (since 1.5.0) requested other fetch items like FLAGS, RFC822.SIZE
612 * @return array $aMessages associative array with messages. Key is the UID, value is an associative array
613 * @since 1.1.3
614 */
615 function sqimap_get_small_header_list($imap_stream, $msg_list,
616 $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type'),
617 $aFetchItems = array('FLAGS', 'RFC822.SIZE', 'INTERNALDATE')) {
618
619 $aMessageList = array();
620
621 /**
622 * Catch other priority headers as well
623 */
624 if (in_array('X-Priority',$aHeaderFields,true)) {
625 $aHeaderFields[] = 'Importance';
626 $aHeaderFields[] = 'Priority';
627 }
628
629 $bUidFetch = ! in_array('UID', $aFetchItems, true);
630
631 /* Get the small headers for each message in $msg_list */
632 if ($msg_list !== NULL) {
633 $msgs_str = sqimap_message_list_squisher($msg_list);
634 /*
635 * We need to return the data in the same order as the caller supplied
636 * in $msg_list, but IMAP servers are free to return responses in
637 * whatever order they wish... So we need to re-sort manually
638 */
639 if ($bUidFetch) {
640 for ($i = 0; $i < sizeof($msg_list); $i++) {
641 $aMessageList["$msg_list[$i]"] = array();
642 }
643 }
644 } else {
645 $msgs_str = '1:*';
646 }
647
648 /*
649 * Create the query
650 */
651
652 $sFetchItems = '';
653 $query = "FETCH $msgs_str (";
654 if (count($aFetchItems)) {
655 $sFetchItems = implode(' ',$aFetchItems);
656 }
657 if (count($aHeaderFields)) {
658 $sHeaderFields = implode(' ',$aHeaderFields);
659 $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
660 }
661 $query .= trim($sFetchItems) . ')';
662 $aResponse = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, $bUidFetch);
663 $aMessages = parseFetch($aResponse,$aMessageList);
664 array_reverse($aMessages);
665 return $aMessages;
666 }
667
668
669 /**
670 * Parses a fetch response, currently it can hande FLAGS, HEADERS, RFC822.SIZE, INTERNALDATE and UID
671 * @param array $aResponse Imap response
672 * @param array $aMessageList Placeholder array for results. The keys of the
673 * placeholder array should be the UID so we can reconstruct the order.
674 * @return array $aMessageList associative array with messages. Key is the UID, value is an associative array
675 * @author Marc Groot Koerkamp
676 */
677 function parseFetch($aResponse,$aMessageList = array()) {
678 for ($j=0,$iCnt=count($aResponse);$j<$iCnt;++$j) {
679 $aMsg = array();
680
681 $read = implode('',$aResponse[$j]);
682 // free up memmory
683 unset($aResponse[$j]); /* unset does not reindex the array. the for loop is safe */
684 /*
685 * #id<space>FETCH<space>(
686 */
687
688 /* extract the message id */
689 $i_space = strpos($read,' ',2);/* position 2ed <space> */
690 $id = substr($read,2/* skip "*<space>" */,$i_space -2);
691 $aMsg['ID'] = $id;
692 $fetch = substr($read,$i_space+1,5);
693 if (!is_numeric($id) && $fetch !== 'FETCH') {
694 $aMsg['ERROR'] = $read; // htmlspecialchars should be done just before display. this is backend code
695 break;
696 }
697 $i = strpos($read,'(',$i_space+5);
698 $read = substr($read,$i+1);
699 $i_len = strlen($read);
700 $i = 0;
701 while ($i < $i_len && $i !== false) {
702 /* get argument */
703 $read = trim(substr($read,$i));
704 $i_len = strlen($read);
705 $i = strpos($read,' ');
706 $arg = substr($read,0,$i);
707 ++$i;
708 /*
709 * use allcaps for imap items and lowcaps for headers as key for the $aMsg array
710 */
711 switch ($arg)
712 {
713 case 'UID':
714 $i_pos = strpos($read,' ',$i);
715 if (!$i_pos) {
716 $i_pos = strpos($read,')',$i);
717 }
718 if ($i_pos) {
719 $unique_id = substr($read,$i,$i_pos-$i);
720 $i = $i_pos+1;
721 } else {
722 break 3;
723 }
724 break;
725 case 'FLAGS':
726 $flags = parseArray($read,$i);
727 if (!$flags) break 3;
728 $aFlags = array();
729 foreach ($flags as $flag) {
730 $flag = strtolower($flag);
731 $aFlags[$flag] = true;
732 }
733 $aMsg['FLAGS'] = $aFlags;
734 break;
735 case 'RFC822.SIZE':
736 $i_pos = strpos($read,' ',$i);
737 if (!$i_pos) {
738 $i_pos = strpos($read,')',$i);
739 }
740 if ($i_pos) {
741 $aMsg['SIZE'] = substr($read,$i,$i_pos-$i);
742 $i = $i_pos+1;
743 } else {
744 break 3;
745 }
746 break;
747 case 'ENVELOPE':
748 // sqimap_parse_address($read,$i,$aMsg);
749 break; // to be implemented, moving imap code out of the Message class
750 case 'BODYSTRUCTURE':
751 break; // to be implemented, moving imap code out of the Message class
752 case 'INTERNALDATE':
753 $aMsg['INTERNALDATE'] = trim(str_replace(' ', ' ',parseString($read,$i)));
754 break;
755 case 'BODY.PEEK[HEADER.FIELDS':
756 case 'BODY[HEADER.FIELDS':
757 $i = strpos($read,'{',$i); // header is always returned as literal because it contain \n characters
758 $header = parseString($read,$i);
759 if ($header === false) break 2;
760 /* First we replace all \r\n by \n, and unfold the header */
761 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
762 /* Now we can make a new header array with
763 each element representing a headerline */
764 $aHdr = explode("\n" , $hdr);
765 $aReceived = array();
766 foreach ($aHdr as $line) {
767 $pos = strpos($line, ':');
768 if ($pos > 0) {
769 $field = strtolower(substr($line, 0, $pos));
770 if (!strstr($field,' ')) { /* valid field */
771 $value = trim(substr($line, $pos+1));
772 switch($field) {
773 case 'date':
774 $aMsg['date'] = trim(str_replace(' ', ' ', $value));
775 break;
776 case 'x-priority': $aMsg['x-priority'] = ($value) ? (int) $value{0} : 3; break;
777 case 'priority':
778 case 'importance':
779 if (!isset($aMsg['x-priority'])) {
780 $aPrio = split('/\w/',trim($value));
781 $sPrio = strtolower(array_shift($aPrio));
782 if (is_numeric($sPrio)) {
783 $iPrio = (int) $sPrio;
784 } elseif ( $sPrio == 'non-urgent' || $sPrio == 'low' ) {
785 $iPrio = 3;
786 } elseif ( $sPrio == 'urgent' || $sPrio == 'high' ) {
787 $iPrio = 1;
788 } else {
789 // default is normal priority
790 $iPrio = 3;
791 }
792 $aMsg['x-priority'] = $iPrio;
793 }
794 break;
795 case 'content-type':
796 $type = $value;
797 if ($pos = strpos($type, ";")) {
798 $type = substr($type, 0, $pos);
799 }
800 $type = explode("/", $type);
801 if(!is_array($type) || count($type) < 2) {
802 $aMsg['content-type'] = array('text','plain');
803 } else {
804 $aMsg['content-type'] = array(strtolower($type[0]),strtolower($type[1]));
805 }
806 break;
807 case 'received':
808 $aMsg['received'][] = $value;
809 break;
810 default:
811 $aMsg[$field] = $value;
812 break;
813 }
814 }
815 }
816 }
817 break;
818 default:
819 ++$i;
820 break;
821 }
822 }
823 if (!empty($unique_id)) {
824 $msgi = "$unique_id";
825 $aMsg['UID'] = $unique_id;
826 } else {
827 $msgi = '';
828 }
829 $aMessageList[$msgi] = $aMsg;
830 }
831 return $aMessageList;
832 }
833
834 /**
835 * Work in process
836 * @private
837 * @author Marc Groot Koerkamp
838 */
839 function sqimap_parse_envelope($read, &$i, &$msg) {
840 $arg_no = 0;
841 $arg_a = array();
842 ++$i;
843 for ($cnt = strlen($read); ($i < $cnt) && ($read{$i} != ')'); ++$i) {
844 $char = strtoupper($read{$i});
845 switch ($char) {
846 case '{':
847 case '"':
848 $arg_a[] = parseString($read,$i);
849 ++$arg_no;
850 break;
851 case 'N':
852 /* probably NIL argument */
853 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
854 $arg_a[] = '';
855 ++$arg_no;
856 $i += 2;
857 }
858 break;
859 case '(':
860 /* Address structure (with group support)
861 * Note: Group support is useless on SMTP connections
862 * because the protocol doesn't support it
863 */
864 $addr_a = array();
865 $group = '';
866 $a=0;
867 for (; $i < $cnt && $read{$i} != ')'; ++$i) {
868 if ($read{$i} == '(') {
869 $addr = sqimap_parse_address($read, $i);
870 if (($addr[3] == '') && ($addr[2] != '')) {
871 /* start of group */
872 $group = $addr[2];
873 $group_addr = $addr;
874 $j = $a;
875 } else if ($group && ($addr[3] == '') && ($addr[2] == '')) {
876 /* end group */
877 if ($a == ($j+1)) { /* no group members */
878 $group_addr[4] = $group;
879 $group_addr[2] = '';
880 $group_addr[0] = "$group: Undisclosed recipients;";
881 $addr_a[] = $group_addr;
882 $group ='';
883 }
884 } else {
885 $addr[4] = $group;
886 $addr_a[] = $addr;
887 }
888 ++$a;
889 }
890 }
891 $arg_a[] = $addr_a;
892 break;
893 default: break;
894 }
895 }
896
897 if (count($arg_a) > 9) {
898 $d = strtr($arg_a[0], array(' ' => ' '));
899 $d = explode(' ', $d);
900 if (!$arg_a[1]) $arg_a[1] = '';
901 $msg['DATE'] = $d; /* argument 1: date */
902 $msg['SUBJECT'] = $arg_a[1]; /* argument 2: subject */
903 $msg['FROM'] = is_array($arg_a[2]) ? $arg_a[2][0] : ''; /* argument 3: from */
904 $msg['SENDER'] = is_array($arg_a[3]) ? $arg_a[3][0] : ''; /* argument 4: sender */
905 $msg['REPLY-TO'] = is_array($arg_a[4]) ? $arg_a[4][0] : ''; /* argument 5: reply-to */
906 $msg['TO'] = $arg_a[5]; /* argument 6: to */
907 $msg['CC'] = $arg_a[6]; /* argument 7: cc */
908 $msg['BCC'] = $arg_a[7]; /* argument 8: bcc */
909 $msg['IN-REPLY-TO'] = $arg_a[8]; /* argument 9: in-reply-to */
910 $msg['MESSAGE-ID'] = $arg_a[9]; /* argument 10: message-id */
911 }
912 }
913
914
915 /**
916 * Work in process
917 * @private
918 * @author Marc Groot Koerkamp
919 */
920 function sqimap_parse_address($read, &$i) {
921 $arg_a = array();
922 for (; $read{$i} != ')'; ++$i) {
923 $char = strtoupper($read{$i});
924 switch ($char) {
925 case '{':
926 case '"': $arg_a[] = parseString($read,$i); break;
927 case 'n':
928 case 'N':
929 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
930 $arg_a[] = '';
931 $i += 2;
932 }
933 break;
934 default: break;
935 }
936 }
937
938 if (count($arg_a) == 4) {
939 return $arg_a;
940
941 // $adr = new AddressStructure();
942 // $adr->personal = $arg_a[0];
943 // $adr->adl = $arg_a[1];
944 // $adr->mailbox = $arg_a[2];
945 // $adr->host = $arg_a[3];
946 } else {
947 $adr = '';
948 }
949 return $adr;
950 }
951
952
953 /**
954 * Returns a message array with all the information about a message.
955 * See the documentation folder for more information about this array.
956 *
957 * @param resource $imap_stream imap connection
958 * @param integer $id uid of the message
959 * @param string $mailbox used for error handling, can be removed because we should return an error code and generate the message elsewhere
960 * @return Message Message object
961 */
962 function sqimap_get_message($imap_stream, $id, $mailbox) {
963 // typecast to int to prohibit 1:* msgs sets
964 $id = (int) $id;
965 $flags = array();
966 $read = sqimap_run_command($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
967 if ($read) {
968 if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
969 if (trim($regs[1])) {
970 $flags = preg_split('/ /', $regs[1],-1,'PREG_SPLIT_NI_EMPTY');
971 }
972 }
973 } else {
974 /* the message was not found, maybe the mailbox was modified? */
975 global $sort, $startMessage, $color;
976
977 $errmessage = _("The server couldn't find the message you requested.") .
978 '<p>'._("Most probably your message list was out of date and the message has been moved away or deleted (perhaps by another program accessing the same mailbox).");
979 /* this will include a link back to the message list */
980 error_message($errmessage, $mailbox, $sort, (int) $startMessage, $color);
981 exit;
982 }
983 $bodystructure = implode('',$read);
984 $msg = mime_structure($bodystructure,$flags);
985 $read = sqimap_run_command($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
986 $rfc822_header = new Rfc822Header();
987 $rfc822_header->parseHeader($read);
988 $msg->rfc822_header = $rfc822_header;
989 return $msg;
990 }
991
992 ?>