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