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 * @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
46 function sqimap_msgs_list_move($imap_stream, $id, $mailbox, $handle_errors = true, $source_mailbox = false) {
47 if ($source_mailbox!==false && $source_mailbox==$mailbox) {
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);
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
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;
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);
78 return sqimap_toggle_flag($imap_stream, $id, '\\Deleted', true, true);
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
94 function sqimap_toggle_flag($imap_stream, $id, $flag, $set, $handle_errors) {
95 $msgs_id = sqimap_message_list_squisher($id);
96 $set_string = ($set ?
'+' : '-');
98 for ($i=0; $i<sizeof($id); $i++
) {
99 $aMessageList["$id[$i]"] = array();
102 $aResponse = sqimap_run_command_list($imap_stream, "STORE $msgs_id ".$set_string."FLAGS ($flag)", $handle_errors, $response, $message, TRUE);
104 // parse the fetch response
105 $parseFetchResults=parseFetch($aResponse,$aMessageList);
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
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);
115 return ($parseFetchResults);
120 * Sort the message list and crunch to be as small as possible
121 * (overflow could happen, so make it small if possible)
123 function sqimap_message_list_squisher($messages_array) {
124 if( !is_array( $messages_array ) ) {
125 return $messages_array;
128 sort($messages_array, SORT_NUMERIC
);
130 while ($messages_array) {
131 $start = array_shift($messages_array);
133 while (isset($messages_array[0]) && $messages_array[0] == $end +
1) {
134 $end = array_shift($messages_array);
136 if ($msgs_str != '') {
140 if ($start != $end) {
141 $msgs_str .= ':' . $end;
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
156 function sqimap_get_sort_order($imap_stream, $sSortField, $reverse, $search='ALL') {
157 global $default_charset;
161 $sSortField = 'REVERSE '.$sSortField;
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);
173 if ($response == 'OK') {
174 return parseUidList($aData,'SORT');
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
187 function parseUidList($aData,$sCommand) {
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]));
196 return array_unique($aUid);
200 * Retrieves an array with a sorted uid list. Sorting is done by SquirrelMail
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
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());
213 $msgs = sqimap_get_small_header_list($imap_stream, $aUid,
214 array(), array($sSortField));
218 switch ($sSortField) {
219 // natcasesort section
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);
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);
245 foreach ($msgs as $item) {
246 $aUid[$item['UID']] = $item[$sSortField];
249 $aUid = array_keys($aUid);
251 $aUid = array_reverse($aUid);
254 // \natcasesort section
255 // sort_numeric section
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);
267 // redefine $sSortField to maintain the same namespace between
268 // server-side sorting and SquirrelMail sorting
269 $sSortField = 'SIZE';
271 foreach ($msgs as $item) {
272 $aUid[$item['UID']] = (isset($item[$sSortField])) ?
$item[$sSortField] : 0;
275 arsort($aUid,SORT_NUMERIC
);
277 asort($aUid, SORT_NUMERIC
);
279 $aUid = array_keys($aUid);
281 // \sort_numeric section
283 $aUid = array_reverse($msgs);
291 * Returns an indent array for printMessageinfo()
292 * This represents the amount of indent needed (value),
293 * for this message number (key)
297 * Notes for future work:
298 * indent_array should contain: indent_level, parent and flags,
300 * To achieve that we need to define the following flags:
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
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)
316 function get_parent_level($thread_new) {
322 * loop through the threads and take unwanted characters out
323 * of the thread string then chop it up
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
);
330 $indent_array = array();
332 $thread_new = array();
334 /* looping through the parts of one message thread */
336 for ($i=0;$i<count($thread_new);$i++
) {
337 /* first grab the parent, it does not indent */
339 if (isset($thread_new[$i][0])) {
340 if (preg_match("/(\d+)/", $thread_new[$i][0], $regs)) {
344 $indent_array[$parent] = 0;
347 * now the children, checking each thread portion for
348 * ),(, and space, adjusting the level and space values
349 * to get the indent level
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'];
361 if (isset($chars['41'])) { /* testing for ) */
362 $level -= $chars['41'];
364 /* if we were faking lets stop, this portion
365 * of the thread is over
367 if ($level == $cutoff) {
371 if (isset($chars['32'])) { /* testing for space */
372 if (!isset($spaces[$level])) {
375 $spaces[$level] +
= $chars['32'];
377 for ($x=0;$x<=$level;$x++
) {
378 if (isset($spaces[$x])) {
379 $spaces_total +
= $spaces[$x];
382 $indent = $level +
$spaces_total;
383 /* must have run into a message that broke the thread
384 * so we are adjusting for that portion
387 $indent = $indent +
1;
389 if (preg_match("/(\d+)/", $thread_new[$i][$k], $regs)) {
392 /* the thread must be broken if $indent == 0
393 * so indent the message once and start faking it
400 /* dont need abs but if indent was negative
403 $indent_array[$child] = ($indent < 0) ?
0 : $indent;
407 return $indent_array;
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
416 function get_thread_sort($imap_stream, $search='ALL') {
417 global $thread_new, $sort_by_ref, $default_charset, $server_sort_array, $indent_array;
419 $thread_temp = array ();
420 if ($sort_by_ref == 1) {
421 $sort_type = 'REFERENCES';
423 $sort_type = 'ORDEREDSUBJECT';
425 $query = "THREAD $sort_type ".strtoupper($default_charset)." $search";
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);
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]);
443 if (!preg_match("/OK/", $response)) {
444 $server_sort_array = 'no';
445 return $server_sort_array;
447 if (isset($thread_list)) {
448 $thread_temp = preg_split("//", $thread_list, -1, PREG_SPLIT_NO_EMPTY
);
452 $thread_new = array();
456 * parse the thread response into separate threads
461 * [2] => (1599 759 959 37)
463 * [4] => ((933)(1891))
464 * [5] => (1030 (1497)(845)(1637))
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];
472 } elseif ($thread_temp[$i] == ')') {
474 $thread_new[$k] .= $thread_temp[$i];
475 $counter = $counter - 1;
477 $thread_new[$k] .= $thread_temp[$i];
479 $thread_new[$k] = "";
480 $counter = $counter - 1;
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;
493 $indent_array = get_parent_level ($thread_new);
494 return array($thread_list,$indent_array);
498 function elapsedTime($start) {
499 $stop = gettimeofday();
500 $timepassed = 1000000 * ($stop['sec'] - $start['sec']) +
$stop['usec'] - $start['usec'];
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.
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()
517 function parsePriority($sValue) {
518 $aValue = split('/\w/',trim($sValue));
519 $value = strtolower(array_shift($aValue));
520 if ( is_numeric($value) ) {
523 if ( $value == 'urgent' ||
$value == 'high' ) {
525 } elseif ( $value == 'non-urgent' ||
$value == 'low' ) {
532 * Parses a string in an imap response. String starts with " or { which means it
533 * can handle double quoted strings and literal strings
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
539 function parseString($read,&$i) {
545 $iPos = strpos($read,'"',$iPos);
547 if ($iPos && $read{$iPos -1} != '\\') {
548 $s = substr($read,$i,($iPos-$i));
553 if ($iPos > strlen($read)) {
557 } else if ($char == '{') {
560 $iPos = strpos($read,'}',$i);
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): '');
567 /* temp bugfix (SM 1.5 will have a working clean version)
568 too much work to implement that version right now */
570 } else { /* should never happen */
571 $i +
= 3; /* } + \r + \n */
583 * Parses a string containing an array from an imap response. String starts with ( and end with )
585 * @param string $read imap response
586 * @param integer $i (reference) offset in string
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);
604 * Retrieves a list with headers, flags, size or internaldate from the imap server
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
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')) {
619 $aMessageList = array();
622 * Catch other priority headers as well
624 if (in_array('X-Priority',$aHeaderFields,true)) {
625 $aHeaderFields[] = 'Importance';
626 $aHeaderFields[] = 'Priority';
629 $bUidFetch = ! in_array('UID', $aFetchItems, true);
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);
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
640 for ($i = 0; $i < sizeof($msg_list); $i++
) {
641 $aMessageList["$msg_list[$i]"] = array();
653 $query = "FETCH $msgs_str (";
654 if (count($aFetchItems)) {
655 $sFetchItems = implode(' ',$aFetchItems);
657 if (count($aHeaderFields)) {
658 $sHeaderFields = implode(' ',$aHeaderFields);
659 $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
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);
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
677 function parseFetch($aResponse,$aMessageList = array()) {
678 for ($j=0,$iCnt=count($aResponse);$j<$iCnt;++
$j) {
681 $read = implode('',$aResponse[$j]);
683 unset($aResponse[$j]); /* unset does not reindex the array. the for loop is safe */
685 * #id<space>FETCH<space>(
688 /* extract the message id */
689 $i_space = strpos($read,' ',2);/* position 2ed <space> */
690 $id = substr($read,2/* skip "*<space>" */,$i_space -2);
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
697 $i = strpos($read,'(',$i_space+
5);
698 $read = substr($read,$i+
1);
699 $i_len = strlen($read);
701 while ($i < $i_len && $i !== false) {
703 $read = trim(substr($read,$i));
704 $i_len = strlen($read);
705 $i = strpos($read,' ');
706 $arg = substr($read,0,$i);
709 * use allcaps for imap items and lowcaps for headers as key for the $aMsg array
714 $i_pos = strpos($read,' ',$i);
716 $i_pos = strpos($read,')',$i);
719 $unique_id = substr($read,$i,$i_pos-$i);
726 $flags = parseArray($read,$i);
727 if (!$flags) break 3;
729 foreach ($flags as $flag) {
730 $flag = strtolower($flag);
731 $aFlags[$flag] = true;
733 $aMsg['FLAGS'] = $aFlags;
736 $i_pos = strpos($read,' ',$i);
738 $i_pos = strpos($read,')',$i);
741 $aMsg['SIZE'] = substr($read,$i,$i_pos-$i);
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
753 $aMsg['INTERNALDATE'] = trim(str_replace(' ', ' ',parseString($read,$i)));
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, ':');
769 $field = strtolower(substr($line, 0, $pos));
770 if (!strstr($field,' ')) { /* valid field */
771 $value = trim(substr($line, $pos+
1));
774 $aMsg['date'] = trim(str_replace(' ', ' ', $value));
776 case 'x-priority': $aMsg['x-priority'] = ($value) ?
(int) $value{0} : 3; break;
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' ) {
786 } elseif ( $sPrio == 'urgent' ||
$sPrio == 'high' ) {
789 // default is normal priority
792 $aMsg['x-priority'] = $iPrio;
797 if ($pos = strpos($type, ";")) {
798 $type = substr($type, 0, $pos);
800 $type = explode("/", $type);
801 if(!is_array($type) ||
count($type) < 2) {
802 $aMsg['content-type'] = array('text','plain');
804 $aMsg['content-type'] = array(strtolower($type[0]),strtolower($type[1]));
808 $aMsg['received'][] = $value;
811 $aMsg[$field] = $value;
823 if (!empty($unique_id)) {
824 $msgi = "$unique_id";
825 $aMsg['UID'] = $unique_id;
829 $aMessageList[$msgi] = $aMsg;
831 return $aMessageList;
837 * @author Marc Groot Koerkamp
839 function sqimap_parse_envelope($read, &$i, &$msg) {
843 for ($cnt = strlen($read); ($i < $cnt) && ($read{$i} != ')'); ++
$i) {
844 $char = strtoupper($read{$i});
848 $arg_a[] = parseString($read,$i);
852 /* probably NIL argument */
853 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
860 /* Address structure (with group support)
861 * Note: Group support is useless on SMTP connections
862 * because the protocol doesn't support it
867 for (; $i < $cnt && $read{$i} != ')'; ++
$i) {
868 if ($read{$i} == '(') {
869 $addr = sqimap_parse_address($read, $i);
870 if (($addr[3] == '') && ($addr[2] != '')) {
875 } else if ($group && ($addr[3] == '') && ($addr[2] == '')) {
877 if ($a == ($j+
1)) { /* no group members */
878 $group_addr[4] = $group;
880 $group_addr[0] = "$group: Undisclosed recipients;";
881 $addr_a[] = $group_addr;
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 */
918 * @author Marc Groot Koerkamp
920 function sqimap_parse_address($read, &$i) {
922 for (; $read{$i} != ')'; ++
$i) {
923 $char = strtoupper($read{$i});
926 case '"': $arg_a[] = parseString($read,$i); break;
929 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
938 if (count($arg_a) == 4) {
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];
954 * Returns a message array with all the information about a message.
955 * See the documentation folder for more information about this array.
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
962 function sqimap_get_message($imap_stream, $id, $mailbox) {
963 // typecast to int to prohibit 1:* msgs sets
966 $read = sqimap_run_command($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
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');
974 /* the message was not found, maybe the mailbox was modified? */
975 global $sort, $startMessage, $color;
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);
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;