6 * This implements functions that manipulate messages
7 * NOTE: Quite a few functions in this file are obsolete
9 * @copyright © 1999-2005 The SquirrelMail Project Team
10 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
12 * @package squirrelmail
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
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') {
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
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);
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
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;
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);
73 return sqimap_toggle_flag($imap_stream, $id, '\\Deleted', true, true);
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
89 function sqimap_toggle_flag($imap_stream, $id, $flag, $set, $handle_errors) {
90 $msgs_id = sqimap_message_list_squisher($id);
91 $set_string = ($set ?
'+' : '-');
93 for ($i=0; $i<sizeof($id); $i++
) {
94 $aMessageList["$id[$i]"] = array();
97 $aResponse = sqimap_run_command_list($imap_stream, "STORE $msgs_id ".$set_string."FLAGS ($flag)", $handle_errors, $response, $message, TRUE);
99 // parse the fetch response
100 $parseFetchResults=parseFetch($aResponse,$aMessageList);
102 // some broken IMAP servers do not return UID elements on UID STORE
103 // if this is the case, then we need to do a UID FETCH
105 if (!isset($parseFetchResults[$testkey]['UID'])) {
106 $aResponse = sqimap_run_command_list($imap_stream, "FETCH $msgs_id (FLAGS)", $handle_errors, $response, $message, TRUE);
107 $parseFetchResults = parseFetch($aResponse,$aMessageList);
110 return ($parseFetchResults);
115 * Sort the message list and crunch to be as small as possible
116 * (overflow could happen, so make it small if possible)
118 function sqimap_message_list_squisher($messages_array) {
119 if( !is_array( $messages_array ) ) {
120 return $messages_array;
123 sort($messages_array, SORT_NUMERIC
);
125 while ($messages_array) {
126 $start = array_shift($messages_array);
128 while (isset($messages_array[0]) && $messages_array[0] == $end +
1) {
129 $end = array_shift($messages_array);
131 if ($msgs_str != '') {
135 if ($start != $end) {
136 $msgs_str .= ':' . $end;
144 * Retrieves an array with a sorted uid list. Sorting is done on the imap server
145 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-17.txt
146 * @param resource $imap_stream IMAP socket connection
147 * @param string $sSortField Field to sort on
148 * @param bool $reverse Reverse order search
149 * @return array $id sorted uid list
151 function sqimap_get_sort_order($imap_stream, $sSortField, $reverse, $search='ALL') {
152 global $default_charset;
156 $sSortField = 'REVERSE '.$sSortField;
158 $query = "SORT ($sSortField) ".strtoupper($default_charset)." $search";
159 // FIX ME sqimap_run_command should return the parsed data accessible by $aDATA['SORT']
160 $aData = sqimap_run_command ($imap_stream, $query, false, $response, $message, TRUE);
161 /* fallback to default charset */
162 if ($response == 'NO' && strpos($message,'[BADCHARSET]') !== false) {
163 $query = "SORT ($sSortField) US-ASCII $search";
164 $aData = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
168 if ($response == 'OK') {
169 return parseUidList($aData,'SORT');
177 * Parses a UID list returned on a SORT or SEARCH request
178 * @param array $aData imap response
179 * @param string $sCommand issued imap command (SEARCH or SORT)
180 * @return array $aUid uid list
182 function parseUidList($aData,$sCommand) {
184 if (isset($aData) && count($aData)) {
185 for ($i=0,$iCnt=count($aData);$i<$iCnt;++
$i) {
186 if (preg_match("/^\* $sCommand (.+)$/", $aData[$i], $aMatch)) {
187 $aUid +
= preg_split("/ /", trim($aMatch[1]));
191 return array_unique($aUid);
195 * Retrieves an array with a sorted uid list. Sorting is done by SquirrelMail
197 * @param resource $imap_stream IMAP socket connection
198 * @param string $sSortField Field to sort on
199 * @param bool $reverse Reverse order search
200 * @param array $aUid limit the search to the provided array with uid's default sqimap_get_small_headers uses 1:*
201 * @return array $aUid sorted uid list
203 function get_squirrel_sort($imap_stream, $sSortField, $reverse = false, $aUid = NULL) {
204 if ($sSortField != 'RFC822.SIZE' && $sSortField != 'INTERNALDATE') {
205 $msgs = sqimap_get_small_header_list($imap_stream, $aUid,
206 array($sSortField), array());
208 $msgs = sqimap_get_small_header_list($imap_stream, $aUid,
209 array(), array($sSortField));
213 switch ($sSortField) {
214 // natcasesort section
219 array_walk($msgs, create_function('&$v,&$k,$f',
220 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
221 $addr = reset(parseRFC822Address($v[$f],1));
222 $sPersonal = (isset($addr[SQM_ADDR_PERSONAL]) && $addr[SQM_ADDR_PERSONAL]) ?
223 $addr[SQM_ADDR_PERSONAL] : "";
224 $sEmail = ($addr[SQM_ADDR_HOST]) ?
225 $addr[SQM_ADDR_MAILBOX] . "@".$addr[SQM_ADDR_HOST] :
226 $addr[SQM_ADDR_HOST];
227 $v[$f] = ($sPersonal) ? decodeHeader($sPersonal):$sEmail;'),$sSortField);
233 array_walk($msgs, create_function('&$v,&$k,$f',
234 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
235 $v[$f] = strtolower(decodeHeader(trim($v[$f])));
236 $v[$f] = (preg_match("/^(vedr|sv|re|aw|\[\w\]):\s*(.*)$/si", $v[$f], $matches)) ?
237 $matches[2] : $v[$f];'),$sSortField);
240 foreach ($msgs as $item) {
241 $aUid[$item['UID']] = $item[$sSortField];
244 $aUid = array_keys($aUid);
246 $aUid = array_reverse($aUid);
249 // \natcasesort section
250 // sort_numeric section
254 array_walk($msgs, create_function('&$v,$k,$f',
255 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
256 $v[$f] = getTimeStamp(explode(" ",$v[$f]));'),$sSortField);
262 // redefine $sSortField to maintain the same namespace between
263 // server-side sorting and SquirrelMail sorting
264 $sSortField = 'SIZE';
266 foreach ($msgs as $item) {
267 $aUid[$item['UID']] = (isset($item[$sSortField])) ?
$item[$sSortField] : 0;
270 arsort($aUid,SORT_NUMERIC
);
272 asort($aUid, SORT_NUMERIC
);
274 $aUid = array_keys($aUid);
276 // \sort_numeric section
278 $aUid = array_reverse($msgs);
286 * Returns an indent array for printMessageinfo()
287 * This represents the amount of indent needed (value),
288 * for this message number (key)
292 * Notes for future work:
293 * indent_array should contain: indent_level, parent and flags,
295 * To achieve that we need to define the following flags:
300 * a node has sibling nodes if it's not the last node
301 * a node has no sibling nodes if it's the last node
302 * By using binary comparations we can store the flag in one var
305 * -1 par = 0, level = 0, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
306 * \-2 par = 1, level = 1, flag = 0 + 2 = 2 (hasnochildren, isfirst)
307 * |-3 par = 1, level = 1, flag = 1 + 4 = 5 (haschildren, islast)
308 * \-4 par = 3, level = 2, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
309 * \-5 par = 4, level = 3, flag = 0 + 2 + 4 = 6 (hasnochildren, isfirst, islast)
311 function get_parent_level($thread_new) {
317 * loop through the threads and take unwanted characters out
318 * of the thread string then chop it up
320 for ($i=0;$i<count($thread_new);$i++
) {
321 $thread_new[$i] = preg_replace("/\s\(/", "(", $thread_new[$i]);
322 $thread_new[$i] = preg_replace("/(\d+)/", "$1|", $thread_new[$i]);
323 $thread_new[$i] = preg_split("/\|/", $thread_new[$i], -1, PREG_SPLIT_NO_EMPTY
);
325 $indent_array = array();
327 $thread_new = array();
329 /* looping through the parts of one message thread */
331 for ($i=0;$i<count($thread_new);$i++
) {
332 /* first grab the parent, it does not indent */
334 if (isset($thread_new[$i][0])) {
335 if (preg_match("/(\d+)/", $thread_new[$i][0], $regs)) {
339 $indent_array[$parent] = 0;
342 * now the children, checking each thread portion for
343 * ),(, and space, adjusting the level and space values
344 * to get the indent level
351 for ($k=1,$iCnt=count($thread_new[$i])-1;$k<$iCnt;++
$k) {
352 $chars = count_chars($thread_new[$i][$k], 1);
353 if (isset($chars['40'])) { /* testing for ( */
354 $level +
= $chars['40'];
356 if (isset($chars['41'])) { /* testing for ) */
357 $level -= $chars['41'];
359 /* if we were faking lets stop, this portion
360 * of the thread is over
362 if ($level == $cutoff) {
366 if (isset($chars['32'])) { /* testing for space */
367 if (!isset($spaces[$level])) {
370 $spaces[$level] +
= $chars['32'];
372 for ($x=0;$x<=$level;$x++
) {
373 if (isset($spaces[$x])) {
374 $spaces_total +
= $spaces[$x];
377 $indent = $level +
$spaces_total;
378 /* must have run into a message that broke the thread
379 * so we are adjusting for that portion
382 $indent = $indent +
1;
384 if (preg_match("/(\d+)/", $thread_new[$i][$k], $regs)) {
387 /* the thread must be broken if $indent == 0
388 * so indent the message once and start faking it
395 /* dont need abs but if indent was negative
398 $indent_array[$child] = ($indent < 0) ?
0 : $indent;
402 return $indent_array;
407 * Returns an array with each element as a string representing one
408 * message-thread as returned by the IMAP server.
409 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
411 function get_thread_sort($imap_stream, $search='ALL') {
412 global $thread_new, $sort_by_ref, $default_charset, $server_sort_array, $indent_array;
414 $thread_temp = array ();
415 if ($sort_by_ref == 1) {
416 $sort_type = 'REFERENCES';
418 $sort_type = 'ORDEREDSUBJECT';
420 $query = "THREAD $sort_type ".strtoupper($default_charset)." $search";
422 $thread_test = sqimap_run_command ($imap_stream, $query, false, $response, $message, TRUE);
423 /* fallback to default charset */
424 if ($response == 'NO' && strpos($message,'[BADCHARSET]') !== false) {
425 $query = "THREAD $sort_type US-ASCII $search";
426 $thread_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
428 if (isset($thread_test[0])) {
429 for ($i=0,$iCnt=count($thread_test);$i<$iCnt;++
$i) {
430 if (preg_match("/^\* THREAD (.+)$/", $thread_test[$i], $regs)) {
431 $thread_list = trim($regs[1]);
438 if (!preg_match("/OK/", $response)) {
439 $server_sort_array = 'no';
440 return $server_sort_array;
442 if (isset($thread_list)) {
443 $thread_temp = preg_split("//", $thread_list, -1, PREG_SPLIT_NO_EMPTY
);
447 $thread_new = array();
451 * parse the thread response into separate threads
456 * [2] => (1599 759 959 37)
458 * [4] => ((933)(1891))
459 * [5] => (1030 (1497)(845)(1637))
461 for ($i=0,$iCnt=count($thread_temp);$i<$iCnt;$i++
) {
462 if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
463 $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
464 } elseif ($thread_temp[$i] == '(') {
465 $thread_new[$k] .= $thread_temp[$i];
467 } elseif ($thread_temp[$i] == ')') {
469 $thread_new[$k] .= $thread_temp[$i];
470 $counter = $counter - 1;
472 $thread_new[$k] .= $thread_temp[$i];
474 $thread_new[$k] = "";
475 $counter = $counter - 1;
480 $thread_new = array_reverse($thread_new);
481 /* place the threads after each other in one string */
482 $thread_list = implode(" ", $thread_new);
483 $thread_list = str_replace("(", " ", $thread_list);
484 $thread_list = str_replace(")", " ", $thread_list);
485 $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY
);
486 $server_sort_array = $thread_list;
488 $indent_array = get_parent_level ($thread_new);
489 return array($thread_list,$indent_array);
493 function elapsedTime($start) {
494 $stop = gettimeofday();
495 $timepassed = 1000000 * ($stop['sec'] - $start['sec']) +
$stop['usec'] - $start['usec'];
501 * Normalise the different Priority headers into a uniform value,
502 * namely that of the X-Priority header (1, 3, 5). Supports:
503 * Prioirty, X-Priority, Importance.
504 * X-MS-Mail-Priority is not parsed because it always coincides
505 * with one of the other headers.
507 * FIXME: DUPLICATE CODE ALERT:
508 * NOTE: this is actually a duplicate from the function in
509 * class/mime/Rfc822Header.php.
510 * @todo obsolate function or use it instead of code block in parseFetch()
512 function parsePriority($sValue) {
513 $aValue = split('/\w/',trim($sValue));
514 $value = strtolower(array_shift($aValue));
515 if ( is_numeric($value) ) {
518 if ( $value == 'urgent' ||
$value == 'high' ) {
520 } elseif ( $value == 'non-urgent' ||
$value == 'low' ) {
527 * Parses a string in an imap response. String starts with " or { which means it
528 * can handle double quoted strings and literal strings
530 * @param string $read imap response
531 * @param integer $i (reference) offset in string
532 * @return string $s parsed string without the double quotes or literal count
534 function parseString($read,&$i) {
540 $iPos = strpos($read,'"',$iPos);
542 if ($iPos && $read{$iPos -1} != '\\') {
543 $s = substr($read,$i,($iPos-$i));
548 if ($iPos > strlen($read)) {
552 } else if ($char == '{') {
555 $iPos = strpos($read,'}',$i);
557 $lit_cnt = substr($read, $i, $iPos - $i);
558 $i +
= strlen($lit_cnt) +
3; /* skip } + \r + \n */
559 /* Now read the literal */
560 $s = ($lit_cnt ?
substr($read,$i,$lit_cnt): '');
562 /* temp bugfix (SM 1.5 will have a working clean version)
563 too much work to implement that version right now */
565 } else { /* should never happen */
566 $i +
= 3; /* } + \r + \n */
578 * Parses a string containing an array from an imap response. String starts with ( and end with )
580 * @param string $read imap response
581 * @param integer $i (reference) offset in string
584 function parseArray($read,&$i) {
585 $i = strpos($read,'(',$i);
586 $i_pos = strpos($read,')',$i);
587 $s = substr($read,$i+
1,$i_pos - $i -1);
588 $a = explode(' ',$s);
599 * Retrieves a list with headers, flags, size or internaldate from the imap server
601 * WARNING: function is not portable between SquirrelMail 1.2.x, 1.4.x and 1.5.x.
602 * Output format, third argument and $msg_list array format requirements differ.
603 * @param stream $imap_stream imap connection
604 * @param array $msg_list array with id's to create a msgs set from
605 * @param array $aHeaderFields (since 1.5.0) requested header fields
606 * @param array $aFetchItems (since 1.5.0) requested other fetch items like FLAGS, RFC822.SIZE
607 * @return array $aMessages associative array with messages. Key is the UID, value is an associative array
610 function sqimap_get_small_header_list($imap_stream, $msg_list,
611 $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type'),
612 $aFetchItems = array('FLAGS', 'RFC822.SIZE', 'INTERNALDATE')) {
614 $aMessageList = array();
617 * Catch other priority headers as well
619 if (in_array('X-Priority',$aHeaderFields,true)) {
620 $aHeaderFields[] = 'Importance';
621 $aHeaderFields[] = 'Priority';
624 $bUidFetch = ! in_array('UID', $aFetchItems, true);
626 /* Get the small headers for each message in $msg_list */
627 if ($msg_list !== NULL) {
628 $msgs_str = sqimap_message_list_squisher($msg_list);
630 * We need to return the data in the same order as the caller supplied
631 * in $msg_list, but IMAP servers are free to return responses in
632 * whatever order they wish... So we need to re-sort manually
635 for ($i = 0; $i < sizeof($msg_list); $i++
) {
636 $aMessageList["$msg_list[$i]"] = array();
648 $query = "FETCH $msgs_str (";
649 if (count($aFetchItems)) {
650 $sFetchItems = implode(' ',$aFetchItems);
652 if (count($aHeaderFields)) {
653 $sHeaderFields = implode(' ',$aHeaderFields);
654 $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
656 $query .= trim($sFetchItems) . ')';
657 $aResponse = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, $bUidFetch);
658 $aMessages = parseFetch($aResponse,$aMessageList);
659 array_reverse($aMessages);
665 * Parses a fetch response, currently it can hande FLAGS, HEADERS, RFC822.SIZE, INTERNALDATE and UID
666 * @param array $aResponse Imap response
667 * @param array $aMessageList Placeholder array for results. The keys of the
668 * placeholder array should be the UID so we can reconstruct the order.
669 * @return array $aMessageList associative array with messages. Key is the UID, value is an associative array
670 * @author Marc Groot Koerkamp
672 function parseFetch($aResponse,$aMessageList = array()) {
673 for ($j=0,$iCnt=count($aResponse);$j<$iCnt;++
$j) {
676 $read = implode('',$aResponse[$j]);
678 unset($aResponse[$j]); /* unset does not reindex the array. the for loop is safe */
680 * #id<space>FETCH<space>(
683 /* extract the message id */
684 $i_space = strpos($read,' ',2);/* position 2ed <space> */
685 $id = substr($read,2/* skip "*<space>" */,$i_space -2);
687 $fetch = substr($read,$i_space+
1,5);
688 if (!is_numeric($id) && $fetch !== 'FETCH') {
689 $aMsg['ERROR'] = $read; // htmlspecialchars should be done just before display. this is backend code
692 $i = strpos($read,'(',$i_space+
5);
693 $read = substr($read,$i+
1);
694 $i_len = strlen($read);
696 while ($i < $i_len && $i !== false) {
698 $read = trim(substr($read,$i));
699 $i_len = strlen($read);
700 $i = strpos($read,' ');
701 $arg = substr($read,0,$i);
704 * use allcaps for imap items and lowcaps for headers as key for the $aMsg array
709 $i_pos = strpos($read,' ',$i);
711 $i_pos = strpos($read,')',$i);
714 $unique_id = substr($read,$i,$i_pos-$i);
721 $flags = parseArray($read,$i);
722 if (!$flags) break 3;
724 foreach ($flags as $flag) {
725 $flag = strtolower($flag);
726 $aFlags[$flag] = true;
728 $aMsg['FLAGS'] = $aFlags;
731 $i_pos = strpos($read,' ',$i);
733 $i_pos = strpos($read,')',$i);
736 $aMsg['SIZE'] = substr($read,$i,$i_pos-$i);
743 // sqimap_parse_address($read,$i,$aMsg);
744 break; // to be implemented, moving imap code out of the Message class
745 case 'BODYSTRUCTURE':
746 break; // to be implemented, moving imap code out of the Message class
748 $aMsg['INTERNALDATE'] = trim(str_replace(' ', ' ',parseString($read,$i)));
750 case 'BODY.PEEK[HEADER.FIELDS':
751 case 'BODY[HEADER.FIELDS':
752 $i = strpos($read,'{',$i); // header is always returned as literal because it contain \n characters
753 $header = parseString($read,$i);
754 if ($header === false) break 2;
755 /* First we replace all \r\n by \n, and unfold the header */
756 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
757 /* Now we can make a new header array with
758 each element representing a headerline */
759 $aHdr = explode("\n" , $hdr);
760 $aReceived = array();
761 foreach ($aHdr as $line) {
762 $pos = strpos($line, ':');
764 $field = strtolower(substr($line, 0, $pos));
765 if (!strstr($field,' ')) { /* valid field */
766 $value = trim(substr($line, $pos+
1));
769 $aMsg['date'] = trim(str_replace(' ', ' ', $value));
771 case 'x-priority': $aMsg['x-priority'] = ($value) ?
(int) $value{0} : 3; break;
774 if (!isset($aMsg['x-priority'])) {
775 $aPrio = split('/\w/',trim($value));
776 $sPrio = strtolower(array_shift($aPrio));
777 if (is_numeric($sPrio)) {
778 $iPrio = (int) $sPrio;
779 } elseif ( $sPrio == 'non-urgent' ||
$sPrio == 'low' ) {
781 } elseif ( $sPrio == 'urgent' ||
$sPrio == 'high' ) {
784 // default is normal priority
787 $aMsg['x-priority'] = $iPrio;
792 if ($pos = strpos($type, ";")) {
793 $type = substr($type, 0, $pos);
795 $type = explode("/", $type);
796 if(!is_array($type) ||
count($type) < 2) {
797 $aMsg['content-type'] = array('text','plain');
799 $aMsg['content-type'] = array(strtolower($type[0]),strtolower($type[1]));
803 $aMsg['received'][] = $value;
806 $aMsg[$field] = $value;
818 if (!empty($unique_id)) {
819 $msgi = "$unique_id";
820 $aMsg['UID'] = $unique_id;
824 $aMessageList[$msgi] = $aMsg;
826 return $aMessageList;
832 * @author Marc Groot Koerkamp
834 function sqimap_parse_envelope($read, &$i, &$msg) {
838 for ($cnt = strlen($read); ($i < $cnt) && ($read{$i} != ')'); ++
$i) {
839 $char = strtoupper($read{$i});
843 $arg_a[] = parseString($read,$i);
847 /* probably NIL argument */
848 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
855 /* Address structure (with group support)
856 * Note: Group support is useless on SMTP connections
857 * because the protocol doesn't support it
862 for (; $i < $cnt && $read{$i} != ')'; ++
$i) {
863 if ($read{$i} == '(') {
864 $addr = sqimap_parse_address($read, $i);
865 if (($addr[3] == '') && ($addr[2] != '')) {
870 } else if ($group && ($addr[3] == '') && ($addr[2] == '')) {
872 if ($a == ($j+
1)) { /* no group members */
873 $group_addr[4] = $group;
875 $group_addr[0] = "$group: Undisclosed recipients;";
876 $addr_a[] = $group_addr;
892 if (count($arg_a) > 9) {
893 $d = strtr($arg_a[0], array(' ' => ' '));
894 $d = explode(' ', $d);
895 if (!$arg_a[1]) $arg_a[1] = '';
896 $msg['DATE'] = $d; /* argument 1: date */
897 $msg['SUBJECT'] = $arg_a[1]; /* argument 2: subject */
898 $msg['FROM'] = is_array($arg_a[2]) ?
$arg_a[2][0] : ''; /* argument 3: from */
899 $msg['SENDER'] = is_array($arg_a[3]) ?
$arg_a[3][0] : ''; /* argument 4: sender */
900 $msg['REPLY-TO'] = is_array($arg_a[4]) ?
$arg_a[4][0] : ''; /* argument 5: reply-to */
901 $msg['TO'] = $arg_a[5]; /* argument 6: to */
902 $msg['CC'] = $arg_a[6]; /* argument 7: cc */
903 $msg['BCC'] = $arg_a[7]; /* argument 8: bcc */
904 $msg['IN-REPLY-TO'] = $arg_a[8]; /* argument 9: in-reply-to */
905 $msg['MESSAGE-ID'] = $arg_a[9]; /* argument 10: message-id */
913 * @author Marc Groot Koerkamp
915 function sqimap_parse_address($read, &$i) {
917 for (; $read{$i} != ')'; ++
$i) {
918 $char = strtoupper($read{$i});
921 case '"': $arg_a[] = parseString($read,$i); break;
924 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
933 if (count($arg_a) == 4) {
936 // $adr = new AddressStructure();
937 // $adr->personal = $arg_a[0];
938 // $adr->adl = $arg_a[1];
939 // $adr->mailbox = $arg_a[2];
940 // $adr->host = $arg_a[3];
949 * Returns a message array with all the information about a message.
950 * See the documentation folder for more information about this array.
952 * @param resource $imap_stream imap connection
953 * @param integer $id uid of the message
954 * @param string $mailbox used for error handling, can be removed because we should return an error code and generate the message elsewhere
955 * @return Message Message object
957 function sqimap_get_message($imap_stream, $id, $mailbox) {
958 // typecast to int to prohibit 1:* msgs sets
961 $read = sqimap_run_command($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
963 if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
964 if (trim($regs[1])) {
965 $flags = preg_split('/ /', $regs[1],-1,'PREG_SPLIT_NI_EMPTY');
969 /* the message was not found, maybe the mailbox was modified? */
970 global $sort, $startMessage, $color;
972 $errmessage = _("The server couldn't find the message you requested.") .
973 '<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).");
974 /* this will include a link back to the message list */
975 error_message($errmessage, $mailbox, $sort, (int) $startMessage, $color);
978 $bodystructure = implode('',$read);
979 $msg = mime_structure($bodystructure,$flags);
980 $read = sqimap_run_command($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
981 $rfc822_header = new Rfc822Header();
982 $rfc822_header->parseHeader($read);
983 $msg->rfc822_header
= $rfc822_header;