6 * This implements functions that manipulate messages
7 * NOTE: Quite a few functions in this file are obsolete
9 * @copyright © 1999-2007 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;
72 if (($move_to_trash == true) && ($bypass_trash != true) &&
73 (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder)) ) {
75 * turn off internal error handling (fourth argument = false) and
76 * ignore copy to trash errors (allows to delete messages when overquota)
78 sqimap_msgs_list_copy ($imap_stream, $id, $trash_folder, false);
80 return sqimap_toggle_flag($imap_stream, $id, '\\Deleted', true, true);
85 * Set a flag on the provided uid list
86 * @param resource imap connection
87 * @param array $id list with uid's
88 * @param string $flag Flags to set/unset flags can be i.e.'\Seen', '\Answered', '\Seen \Answered'
89 * @param bool $set add (true) or remove (false) the provided flag
90 * @param bool $handle_errors Show error messages in case of a NO, BAD or BYE response
91 * @return array $aMessageList array with messages containing the new flags and UID @see parseFetch
93 function sqimap_toggle_flag($imap_stream, $id, $flag, $set, $handle_errors) {
94 $msgs_id = sqimap_message_list_squisher($id);
95 $set_string = ($set ?
'+' : '-');
97 for ($i=0; $i<sizeof($id); $i++
) {
98 $aMessageList["$id[$i]"] = array();
101 $aResponse = sqimap_run_command_list($imap_stream, "STORE $msgs_id ".$set_string."FLAGS ($flag)", $handle_errors, $response, $message, TRUE);
103 // parse the fetch response
104 $parseFetchResults=parseFetch($aResponse,$aMessageList);
106 // some broken IMAP servers do not return UID elements on UID STORE
107 // if this is the case, then we need to do a UID FETCH
109 if (!isset($parseFetchResults[$testkey]['UID'])) {
110 $aResponse = sqimap_run_command_list($imap_stream, "FETCH $msgs_id (FLAGS)", $handle_errors, $response, $message, TRUE);
111 $parseFetchResults = parseFetch($aResponse,$aMessageList);
114 return ($parseFetchResults);
119 * Sort the message list and crunch to be as small as possible
120 * (overflow could happen, so make it small if possible)
121 * @param array $aUid array with uid's
122 * @return string $s message set string
124 function sqimap_message_list_squisher($aUid) {
125 if( !is_array( $aUid ) ) {
128 sort($aUid, SORT_NUMERIC
);
132 for ($i=0,$iCnt=count($aUid);$i<$iCnt;++
$i) {
135 while ($i<($iCnt-1) && $aUid[$i+
1] == $iEnd +
1) {
143 if ($iStart != $iEnd) {
153 * Retrieves an array with a sorted uid list. Sorting is done on the imap server
154 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-17.txt
155 * @param resource $imap_stream IMAP socket connection
156 * @param string $sSortField Field to sort on
157 * @param bool $reverse Reverse order search
158 * @return array $id sorted uid list
160 function sqimap_get_sort_order($imap_stream, $sSortField, $reverse, $search='ALL') {
161 global $default_charset;
165 $sSortField = 'REVERSE '.$sSortField;
167 $query = "SORT ($sSortField) ".strtoupper($default_charset)." $search";
168 // FIX ME sqimap_run_command should return the parsed data accessible by $aDATA['SORT']
169 // use sqimap_run_command_list in case of unsollicited responses. If we don't we could loose the SORT response
170 $aData = sqimap_run_command_list ($imap_stream, $query, false, $response, $message, TRUE);
171 /* fallback to default charset */
172 if ($response == 'NO') {
173 if (strpos($message,'BADCHARSET') !== false ||
174 strpos($message,'character') !== false) {
175 sqm_trigger_imap_error('SQM_IMAP_BADCHARSET',$query, $response, $message);
176 $query = "SORT ($sSortField) US-ASCII $search";
177 $aData = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, TRUE);
179 sqm_trigger_imap_error('SQM_IMAP_ERROR',$query, $response, $message);
181 } else if ($response == 'BAD') {
182 sqm_trigger_imap_error('SQM_IMAP_NO_SORT',$query, $response, $message);
186 if ($response == 'OK') {
187 return parseUidList($aData,'SORT');
195 * Parses a UID list returned on a SORT or SEARCH request
196 * @param array $aData imap response (retrieved from sqimap_run_command_list)
197 * @param string $sCommand issued imap command (SEARCH or SORT)
198 * @return array $aUid uid list
200 function parseUidList($aData,$sCommand) {
202 if (isset($aData) && count($aData)) {
203 for ($i=0,$iCnt=count($aData);$i<$iCnt;++
$i) {
204 for ($j=0,$jCnt=count($aData[$i]);$j<$jCnt;++
$j) {
205 if (preg_match("/^\* $sCommand (.+)$/", $aData[$i][$j], $aMatch)) {
206 $aUid +
= explode(' ', trim($aMatch[1]));
211 return array_unique($aUid);
215 * Retrieves an array with a sorted uid list. Sorting is done by SquirrelMail
217 * @param resource $imap_stream IMAP socket connection
218 * @param string $sSortField Field to sort on
219 * @param bool $reverse Reverse order search
220 * @param array $aUid limit the search to the provided array with uid's default sqimap_get_small_headers uses 1:*
221 * @return array $aUid sorted uid list
223 function get_squirrel_sort($imap_stream, $sSortField, $reverse = false, $aUid = NULL) {
224 if ($sSortField != 'RFC822.SIZE' && $sSortField != 'INTERNALDATE') {
225 $msgs = sqimap_get_small_header_list($imap_stream, $aUid,
226 array($sSortField), array());
228 $msgs = sqimap_get_small_header_list($imap_stream, $aUid,
229 array(), array($sSortField));
232 // sqimap_get_small_header (see above) returns fields in lower case,
233 // but the code below uses all upper case
234 foreach ($msgs as $k => $v)
235 if (isset($msgs[$k][strtolower($sSortField)]))
236 $msgs[$k][strtoupper($sSortField)] = $msgs[$k][strtolower($sSortField)];
240 switch ($sSortField) {
241 // natcasesort section
246 array_walk($msgs, create_function('&$v,&$k,$f',
247 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
248 $addr = reset(parseRFC822Address($v[$f],1));
249 $sPersonal = (isset($addr[SQM_ADDR_PERSONAL]) && $addr[SQM_ADDR_PERSONAL]) ?
250 $addr[SQM_ADDR_PERSONAL] : "";
251 $sEmail = ($addr[SQM_ADDR_HOST]) ?
252 $addr[SQM_ADDR_MAILBOX] . "@".$addr[SQM_ADDR_HOST] :
253 $addr[SQM_ADDR_HOST];
254 $v[$f] = ($sPersonal) ? decodeHeader($sPersonal, true, false):$sEmail;'),$sSortField);
260 array_walk($msgs, create_function('&$v,&$k,$f',
261 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
262 $v[$f] = strtolower(decodeHeader(trim($v[$f]), true, false));
263 $v[$f] = (preg_match("/^(?:(?:vedr|sv|re|aw|fw|fwd|\[\w\]):\s*)*\s*(.*)$/si", $v[$f], $matches)) ?
264 $matches[1] : $v[$f];'),$sSortField);
267 foreach ($msgs as $item) {
268 $aUid[$item['UID']] = $item[$sSortField];
271 $aUid = array_keys($aUid);
273 $aUid = array_reverse($aUid);
276 // \natcasesort section
277 // sort_numeric section
281 array_walk($msgs, create_function('&$v,$k,$f',
282 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
283 $v[$f] = getTimeStamp(explode(" ",$v[$f]));'),$sSortField);
289 // redefine $sSortField to maintain the same namespace between
290 // server-side sorting and SquirrelMail sorting
291 $sSortField = 'SIZE';
293 foreach ($msgs as $item) {
294 $aUid[$item['UID']] = (isset($item[$sSortField])) ?
$item[$sSortField] : 0;
297 arsort($aUid,SORT_NUMERIC
);
299 asort($aUid, SORT_NUMERIC
);
301 $aUid = array_keys($aUid);
303 // \sort_numeric section
305 $aUid = array_reverse($msgs);
312 * Returns an array with each element as a string representing one
313 * message-thread as returned by the IMAP server.
314 * @param resource $imap_stream IMAP socket connection
315 * @param string $search optional search string
317 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
319 function get_thread_sort($imap_stream, $search='ALL') {
320 global $sort_by_ref, $default_charset;
322 if ($sort_by_ref == 1) {
323 $sort_type = 'REFERENCES';
325 $sort_type = 'ORDEREDSUBJECT';
327 $query = "THREAD $sort_type ".strtoupper($default_charset)." $search";
329 // TODO use sqimap_run_command_list as we do in get_server_sort()
330 $sRead = sqimap_run_command ($imap_stream, $query, false, $response, $message, TRUE);
332 /* fallback to default charset */
333 if ($response == 'NO') {
334 if (strpos($message,'BADCHARSET') !== false ||
335 strpos($message,'character') !== false) {
336 sqm_trigger_imap_error('SQM_IMAP_BADCHARSET',$query, $response, $message);
337 $query = "THREAD $sort_type US-ASCII $search";
338 $sRead = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
340 sqm_trigger_imap_error('SQM_IMAP_ERROR',$query, $response, $message);
342 } elseif ($response == 'BAD') {
343 sqm_trigger_imap_error('SQM_IMAP_NO_THREAD',$query, $response, $message);
345 $sThreadResponse = '';
346 if (isset($sRead[0])) {
347 for ($i=0,$iCnt=count($sRead);$i<$iCnt;++
$i) {
348 if (preg_match("/^\* THREAD (.+)$/", $sRead[$i], $aMatch)) {
349 $sThreadResponse = trim($aMatch[1]);
356 if ($response !== 'OK') {
361 * S: * THREAD (2)(3 6 (4 23)(44 7 96))
374 * Notes for future work:
375 * indent_array should contain: indent_level, parent and flags,
377 * To achieve that we need to define the following flags:
382 * a node has sibling nodes if it's not the last node
383 * a node has no sibling nodes if it's the last node
384 * By using binary comparations we can store the flag in one var
387 * -1 par = 0, level = 0, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
388 * \-2 par = 1, level = 1, flag = 0 + 2 = 2 (hasnochildren, isfirst)
389 * |-3 par = 1, level = 1, flag = 1 + 4 = 5 (haschildren, islast)
390 * \-4 par = 3, level = 2, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
391 * \-5 par = 4, level = 3, flag = 0 + 2 + 4 = 6 (hasnochildren, isfirst, islast)
397 $aUidThread = array();
399 $aUidSubThread = array();
400 $aDepthStack = array();
403 if ($sThreadResponse) {
404 for ($i=0,$iCnt = strlen($sThreadResponse);$i<$iCnt;++
$i) {
405 $cChar = $sThreadResponse{$i};
407 case '(': // new sub thread
408 // correction for a subthread of a thread with no parents in thread
409 if (!count($aUidSubThread) && $j > 0) {
412 $aDepthStack[$j] = $l;
415 case ')': // close sub thread
417 $aUidSubThread[] = $sUid;
418 $aIndent[$sUid] = $j +
$l - 1;
424 // show message that starts the thread first.
425 $aUidSubThread = array_reverse($aUidSubThread);
426 // do not use array_merge because it's extremely slow and is causing timeouts
427 foreach ($aUidSubThread as $iUid) {
428 $aUidThread[] = $iUid;
430 $aUidSubThread = array();
432 $aDepthStack = array();
434 $l = $aDepthStack[$j];
437 case ' ': // new child
439 $aUidSubThread[] = $sUid;
440 $aIndent[$sUid] = $j +
$l - 1;
445 default: // part of UID
451 unset($sThreadResponse);
452 // show newest threads first
453 $aUidThread = array_reverse($aUidThread);
454 return array($aUidThread,$aIndent);
458 function elapsedTime($start) {
459 $stop = gettimeofday();
460 $timepassed = 1000000 * ($stop['sec'] - $start['sec']) +
$stop['usec'] - $start['usec'];
465 * Parses a string in an imap response. String starts with " or { which means it
466 * can handle double quoted strings and literal strings
468 * @param string $read imap response
469 * @param integer $i (reference) offset in string
470 * @return string $s parsed string without the double quotes or literal count
472 function parseString($read,&$i) {
478 $iPos = strpos($read,'"',$iPos);
480 if ($iPos && $read{$iPos -1} != '\\') {
481 $s = substr($read,$i,($iPos-$i));
486 if ($iPos > strlen($read)) {
490 } else if ($char == '{') {
493 $iPos = strpos($read,'}',$i);
495 $lit_cnt = substr($read, $i, $iPos - $i);
496 $i +
= strlen($lit_cnt) +
3; /* skip } + \r + \n */
497 /* Now read the literal */
498 $s = ($lit_cnt ?
substr($read,$i,$lit_cnt): '');
500 /* temp bugfix (SM 1.5 will have a working clean version)
501 too much work to implement that version right now */
503 } else { /* should never happen */
504 $i +
= 3; /* } + \r + \n */
516 * Parses a string containing an array from an imap response. String starts with ( and end with )
518 * @param string $read imap response
519 * @param integer $i (reference) offset in string
522 function parseArray($read,&$i) {
523 $i = strpos($read,'(',$i);
524 $i_pos = strpos($read,')',$i);
525 $s = substr($read,$i+
1,$i_pos - $i -1);
526 $a = explode(' ',$s);
537 * Retrieves a list with headers, flags, size or internaldate from the imap server
539 * WARNING: function is not portable between SquirrelMail 1.2.x, 1.4.x and 1.5.x.
540 * Output format, third argument and $msg_list array format requirements differ.
541 * @param stream $imap_stream imap connection
542 * @param array $msg_list array with id's to create a msgs set from
543 * @param array $aHeaderFields (since 1.5.0) requested header fields
544 * @param array $aFetchItems (since 1.5.0) requested other fetch items like FLAGS, RFC822.SIZE
545 * @return array $aMessages associative array with messages. Key is the UID, value is an associative array
548 function sqimap_get_small_header_list($imap_stream, $msg_list,
549 $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type'),
550 $aFetchItems = array('FLAGS', 'RFC822.SIZE', 'INTERNALDATE')) {
552 $aMessageList = array();
555 * Catch other priority headers as well
557 if (in_array('X-Priority',$aHeaderFields,true)) {
558 $aHeaderFields[] = 'Importance';
559 $aHeaderFields[] = 'Priority';
562 $bUidFetch = ! in_array('UID', $aFetchItems, true);
564 /* Get the small headers for each message in $msg_list */
565 if ($msg_list !== NULL) {
566 $msgs_str = sqimap_message_list_squisher($msg_list);
568 * We need to return the data in the same order as the caller supplied
569 * in $msg_list, but IMAP servers are free to return responses in
570 * whatever order they wish... So we need to re-sort manually
573 for ($i = 0; $i < sizeof($msg_list); $i++
) {
574 $aMessageList["$msg_list[$i]"] = array();
586 $query = "FETCH $msgs_str (";
587 if (count($aFetchItems)) {
588 $sFetchItems = implode(' ',$aFetchItems);
590 if (count($aHeaderFields)) {
591 $sHeaderFields = implode(' ',$aHeaderFields);
592 $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
594 $query .= trim($sFetchItems) . ')';
595 $aResponse = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, $bUidFetch);
596 $aMessages = parseFetch($aResponse,$aMessageList);
597 array_reverse($aMessages);
603 * Parses a fetch response, currently it can hande FLAGS, HEADERS, RFC822.SIZE, INTERNALDATE and UID
604 * @param array $aResponse Imap response
605 * @param array $aMessageList Placeholder array for results. The keys of the
606 * placeholder array should be the UID so we can reconstruct the order.
607 * @return array $aMessageList associative array with messages. Key is the UID, value is an associative array
608 * @author Marc Groot Koerkamp
610 function parseFetch(&$aResponse,$aMessageList = array()) {
611 for ($j=0,$iCnt=count($aResponse);$j<$iCnt;++
$j) {
614 $read = implode('',$aResponse[$j]);
616 unset($aResponse[$j]); /* unset does not reindex the array. the for loop is safe */
618 * #id<space>FETCH<space>(
621 /* extract the message id */
622 $i_space = strpos($read,' ',2);/* position 2ed <space> */
623 $id = substr($read,2/* skip "*<space>" */,$i_space -2);
625 $fetch = substr($read,$i_space+
1,5);
626 if (!is_numeric($id) && $fetch !== 'FETCH') {
627 $aMsg['ERROR'] = $read; // htmlspecialchars should be done just before display. this is backend code
630 $i = strpos($read,'(',$i_space+
5);
631 $read = substr($read,$i+
1);
632 $i_len = strlen($read);
634 while ($i < $i_len && $i !== false) {
636 $read = trim(substr($read,$i));
637 $i_len = strlen($read);
638 $i = strpos($read,' ');
639 $arg = substr($read,0,$i);
642 * use allcaps for imap items and lowcaps for headers as key for the $aMsg array
647 $i_pos = strpos($read,' ',$i);
649 $i_pos = strpos($read,')',$i);
652 $unique_id = substr($read,$i,$i_pos-$i);
659 $flags = parseArray($read,$i);
660 if (!$flags) break 3;
662 foreach ($flags as $flag) {
663 $flag = strtolower($flag);
664 $aFlags[$flag] = true;
666 $aMsg['FLAGS'] = $aFlags;
669 $i_pos = strpos($read,' ',$i);
671 $i_pos = strpos($read,')',$i);
674 $aMsg['SIZE'] = substr($read,$i,$i_pos-$i);
681 // sqimap_parse_address($read,$i,$aMsg);
682 break; // to be implemented, moving imap code out of the Message class
683 case 'BODYSTRUCTURE':
684 break; // to be implemented, moving imap code out of the Message class
686 $aMsg['INTERNALDATE'] = trim(str_replace(' ', ' ',parseString($read,$i)));
688 case 'BODY.PEEK[HEADER.FIELDS':
689 case 'BODY[HEADER.FIELDS':
690 $i = strpos($read,'{',$i); // header is always returned as literal because it contain \n characters
691 $header = parseString($read,$i);
692 if ($header === false) break 2;
693 /* First we replace all \r\n by \n, and unfold the header */
694 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
695 /* Now we can make a new header array with
696 each element representing a headerline */
697 $aHdr = explode("\n" , $hdr);
698 $aReceived = array();
699 foreach ($aHdr as $line) {
700 $pos = strpos($line, ':');
702 $field = strtolower(substr($line, 0, $pos));
703 if (!strstr($field,' ')) { /* valid field */
704 $value = trim(substr($line, $pos+
1));
707 $aMsg['date'] = trim(str_replace(' ', ' ', $value));
709 case 'x-priority': $aMsg['x-priority'] = ($value) ?
(int) $value{0} : 3; break;
712 // duplicate code with Rfc822Header.cls:parsePriority()
713 if (!isset($aMsg['x-priority'])) {
714 $aPrio = preg_split('/\s/',trim($value));
715 $sPrio = strtolower(array_shift($aPrio));
716 if (is_numeric($sPrio)) {
717 $iPrio = (int) $sPrio;
718 } elseif ( $sPrio == 'non-urgent' ||
$sPrio == 'low' ) {
720 } elseif ( $sPrio == 'urgent' ||
$sPrio == 'high' ) {
723 // default is normal priority
726 $aMsg['x-priority'] = $iPrio;
731 if ($pos = strpos($type, ";")) {
732 $type = substr($type, 0, $pos);
734 $type = explode("/", $type);
735 if(!is_array($type) ||
count($type) < 2) {
736 $aMsg['content-type'] = array('text','plain');
738 $aMsg['content-type'] = array(strtolower($type[0]),strtolower($type[1]));
742 $aMsg['received'][] = $value;
745 $aMsg[$field] = $value;
757 if (!empty($unique_id)) {
758 $msgi = "$unique_id";
759 $aMsg['UID'] = $unique_id;
763 $aMessageList[$msgi] = $aMsg;
764 $aResponse[$j] = NULL;
766 return $aMessageList;
772 * @author Marc Groot Koerkamp
774 function sqimap_parse_envelope($read, &$i, &$msg) {
778 for ($cnt = strlen($read); ($i < $cnt) && ($read{$i} != ')'); ++
$i) {
779 $char = strtoupper($read{$i});
783 $arg_a[] = parseString($read,$i);
787 /* probably NIL argument */
788 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
795 /* Address structure (with group support)
796 * Note: Group support is useless on SMTP connections
797 * because the protocol doesn't support it
802 for (; $i < $cnt && $read{$i} != ')'; ++
$i) {
803 if ($read{$i} == '(') {
804 $addr = sqimap_parse_address($read, $i);
805 if (($addr[3] == '') && ($addr[2] != '')) {
810 } else if ($group && ($addr[3] == '') && ($addr[2] == '')) {
812 if ($a == ($j+
1)) { /* no group members */
813 $group_addr[4] = $group;
815 $group_addr[0] = "$group: Undisclosed recipients;";
816 $addr_a[] = $group_addr;
832 if (count($arg_a) > 9) {
833 $d = strtr($arg_a[0], array(' ' => ' '));
834 $d = explode(' ', $d);
835 if (!$arg_a[1]) $arg_a[1] = '';
836 $msg['DATE'] = $d; /* argument 1: date */
837 $msg['SUBJECT'] = $arg_a[1]; /* argument 2: subject */
838 $msg['FROM'] = is_array($arg_a[2]) ?
$arg_a[2][0] : ''; /* argument 3: from */
839 $msg['SENDER'] = is_array($arg_a[3]) ?
$arg_a[3][0] : ''; /* argument 4: sender */
840 $msg['REPLY-TO'] = is_array($arg_a[4]) ?
$arg_a[4][0] : ''; /* argument 5: reply-to */
841 $msg['TO'] = $arg_a[5]; /* argument 6: to */
842 $msg['CC'] = $arg_a[6]; /* argument 7: cc */
843 $msg['BCC'] = $arg_a[7]; /* argument 8: bcc */
844 $msg['IN-REPLY-TO'] = $arg_a[8]; /* argument 9: in-reply-to */
845 $msg['MESSAGE-ID'] = $arg_a[9]; /* argument 10: message-id */
853 * @author Marc Groot Koerkamp
855 function sqimap_parse_address($read, &$i) {
857 for (; $read{$i} != ')'; ++
$i) {
858 $char = strtoupper($read{$i});
861 case '"': $arg_a[] = parseString($read,$i); break;
864 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
873 if (count($arg_a) == 4) {
876 // $adr = new AddressStructure();
877 // $adr->personal = $arg_a[0];
878 // $adr->adl = $arg_a[1];
879 // $adr->mailbox = $arg_a[2];
880 // $adr->host = $arg_a[3];
889 * Returns a message array with all the information about a message.
890 * See the documentation folder for more information about this array.
892 * @param resource $imap_stream imap connection
893 * @param integer $id uid of the message
894 * @param string $mailbox used for error handling, can be removed because we should return an error code and generate the message elsewhere
895 * @param int $hide Indicates whether or not to hide any errors: 0 = don't hide, 1 = hide (just exit), 2 = hide (return FALSE), 3 = hide (return error string) (OPTIONAL; default don't hide)
896 * @return mixed Message object or FALSE/error string if error occurred and $hide is set to 2/3
898 function sqimap_get_message($imap_stream, $id, $mailbox, $hide=0) {
899 // typecast to int to prohibit 1:* msgs sets
902 $read = sqimap_run_command($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
904 if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
905 if (trim($regs[1])) {
906 $flags = preg_split('/ /', $regs[1],-1,PREG_SPLIT_NO_EMPTY
);
911 if ($hide == 1) exit;
912 if ($hide == 2) return FALSE;
914 /* the message was not found, maybe the mailbox was modified? */
915 global $sort, $startMessage;
917 $errmessage = _("The server couldn't find the message you requested.");
919 if ($hide == 3) return $errmessage;
921 $errmessage .= '<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).");
923 /* this will include a link back to the message list */
924 error_message($errmessage, $mailbox, $sort, (int) $startMessage);
927 $bodystructure = implode('',$read);
928 $msg = mime_structure($bodystructure,$flags);
929 $read = sqimap_run_command($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
930 $rfc822_header = new Rfc822Header();
931 $rfc822_header->parseHeader($read);
932 $msg->rfc822_header
= $rfc822_header;
934 parse_message_entities($msg, $id, $imap_stream);
940 * Recursively parse embedded messages (if any) in the given
941 * message, building correct rfc822 headers for each one
943 * @param object $msg The message object to scan for attached messages
944 * NOTE: this is passed by reference! Changes made
945 * within will affect the caller's copy of $msg!
946 * @param int $id The top-level message UID on the IMAP server, even
947 * if the $msg being passed in is only an attached entity
949 * @param resource $imap_stream A live connection to the IMAP server.
956 function parse_message_entities(&$msg, $id, $imap_stream) {
958 if (!empty($msg->entities
)) foreach ($msg->entities
as $i => $entity) {
959 if (is_object($entity) && get_class($entity) == 'Message') {
960 if (!empty($entity->rfc822_header
)) {
961 $read = sqimap_run_command($imap_stream, "FETCH $id BODY[". $entity->entity_id
.".HEADER]", true, $response, $message, $uid_support);
962 $rfc822_header = new Rfc822Header();
963 $rfc822_header->parseHeader($read);
964 $msg->entities
[$i]->rfc822_header
= $rfc822_header;
966 parse_message_entities($msg->entities
[$i], $id, $imap_stream);