2bdf5e79f3b9d1f88a22043867b7f8479059fbf3
6 * This implements functions that manipulate messages
7 * NOTE: Quite a few functions in this file are obsolete
9 * @copyright © 1999-2006 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 // use sqimap_run_command_list in case of unsollicited responses. If we don't we could loose the SORT response
166 $aData = sqimap_run_command_list ($imap_stream, $query, false, $response, $message, TRUE);
167 /* fallback to default charset */
168 if ($response == 'NO' && strpos($message,'[BADCHARSET]') !== false) {
169 $query = "SORT ($sSortField) US-ASCII $search";
170 $aData = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, TRUE);
175 if ($response == 'OK') {
176 return parseUidList($aData,'SORT');
184 * Parses a UID list returned on a SORT or SEARCH request
185 * @param array $aData imap response (retrieved from sqimap_run_command_list)
186 * @param string $sCommand issued imap command (SEARCH or SORT)
187 * @return array $aUid uid list
189 function parseUidList($aData,$sCommand) {
191 if (isset($aData) && count($aData)) {
192 for ($i=0,$iCnt=count($aData);$i<$iCnt;++
$i) {
193 for ($j=0,$jCnt=count($aData[$i]);$j<$jCnt;++
$j) {
194 if (preg_match("/^\* $sCommand (.+)$/", $aData[$i][$j], $aMatch)) {
195 $aUid +
= preg_split("/ /", trim($aMatch[1]));
200 return array_unique($aUid);
204 * Retrieves an array with a sorted uid list. Sorting is done by SquirrelMail
206 * @param resource $imap_stream IMAP socket connection
207 * @param string $sSortField Field to sort on
208 * @param bool $reverse Reverse order search
209 * @param array $aUid limit the search to the provided array with uid's default sqimap_get_small_headers uses 1:*
210 * @return array $aUid sorted uid list
212 function get_squirrel_sort($imap_stream, $sSortField, $reverse = false, $aUid = NULL) {
213 if ($sSortField != 'RFC822.SIZE' && $sSortField != 'INTERNALDATE') {
214 $msgs = sqimap_get_small_header_list($imap_stream, $aUid,
215 array($sSortField), array());
217 $msgs = sqimap_get_small_header_list($imap_stream, $aUid,
218 array(), array($sSortField));
222 switch ($sSortField) {
223 // natcasesort section
228 array_walk($msgs, create_function('&$v,&$k,$f',
229 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
230 $addr = reset(parseRFC822Address($v[$f],1));
231 $sPersonal = (isset($addr[SQM_ADDR_PERSONAL]) && $addr[SQM_ADDR_PERSONAL]) ?
232 $addr[SQM_ADDR_PERSONAL] : "";
233 $sEmail = ($addr[SQM_ADDR_HOST]) ?
234 $addr[SQM_ADDR_MAILBOX] . "@".$addr[SQM_ADDR_HOST] :
235 $addr[SQM_ADDR_HOST];
236 $v[$f] = ($sPersonal) ? decodeHeader($sPersonal):$sEmail;'),$sSortField);
242 array_walk($msgs, create_function('&$v,&$k,$f',
243 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
244 $v[$f] = strtolower(decodeHeader(trim($v[$f])));
245 $v[$f] = (preg_match("/^(vedr|sv|re|aw|\[\w\]):\s*(.*)$/si", $v[$f], $matches)) ?
246 $matches[2] : $v[$f];'),$sSortField);
249 foreach ($msgs as $item) {
250 $aUid[$item['UID']] = $item[$sSortField];
253 $aUid = array_keys($aUid);
255 $aUid = array_reverse($aUid);
258 // \natcasesort section
259 // sort_numeric section
263 array_walk($msgs, create_function('&$v,$k,$f',
264 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
265 $v[$f] = getTimeStamp(explode(" ",$v[$f]));'),$sSortField);
271 // redefine $sSortField to maintain the same namespace between
272 // server-side sorting and SquirrelMail sorting
273 $sSortField = 'SIZE';
275 foreach ($msgs as $item) {
276 $aUid[$item['UID']] = (isset($item[$sSortField])) ?
$item[$sSortField] : 0;
279 arsort($aUid,SORT_NUMERIC
);
281 asort($aUid, SORT_NUMERIC
);
283 $aUid = array_keys($aUid);
285 // \sort_numeric section
287 $aUid = array_reverse($msgs);
295 * Returns an indent array for printMessageinfo()
296 * This represents the amount of indent needed (value),
297 * for this message number (key)
301 * Notes for future work:
302 * indent_array should contain: indent_level, parent and flags,
304 * To achieve that we need to define the following flags:
309 * a node has sibling nodes if it's not the last node
310 * a node has no sibling nodes if it's the last node
311 * By using binary comparations we can store the flag in one var
314 * -1 par = 0, level = 0, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
315 * \-2 par = 1, level = 1, flag = 0 + 2 = 2 (hasnochildren, isfirst)
316 * |-3 par = 1, level = 1, flag = 1 + 4 = 5 (haschildren, islast)
317 * \-4 par = 3, level = 2, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
318 * \-5 par = 4, level = 3, flag = 0 + 2 + 4 = 6 (hasnochildren, isfirst, islast)
320 function get_parent_level($thread_new) {
326 * loop through the threads and take unwanted characters out
327 * of the thread string then chop it up
329 for ($i=0;$i<count($thread_new);$i++
) {
330 $thread_new[$i] = preg_replace("/\s\(/", "(", $thread_new[$i]);
331 $thread_new[$i] = preg_replace("/(\d+)/", "$1|", $thread_new[$i]);
332 $thread_new[$i] = preg_split("/\|/", $thread_new[$i], -1, PREG_SPLIT_NO_EMPTY
);
334 $indent_array = array();
336 $thread_new = array();
338 /* looping through the parts of one message thread */
340 for ($i=0;$i<count($thread_new);$i++
) {
341 /* first grab the parent, it does not indent */
343 if (isset($thread_new[$i][0])) {
344 if (preg_match("/(\d+)/", $thread_new[$i][0], $regs)) {
348 $indent_array[$parent] = 0;
351 * now the children, checking each thread portion for
352 * ),(, and space, adjusting the level and space values
353 * to get the indent level
360 for ($k=1,$iCnt=count($thread_new[$i])-1;$k<$iCnt;++
$k) {
361 $chars = count_chars($thread_new[$i][$k], 1);
362 if (isset($chars['40'])) { /* testing for ( */
363 $level +
= $chars['40'];
365 if (isset($chars['41'])) { /* testing for ) */
366 $level -= $chars['41'];
368 /* if we were faking lets stop, this portion
369 * of the thread is over
371 if ($level == $cutoff) {
375 if (isset($chars['32'])) { /* testing for space */
376 if (!isset($spaces[$level])) {
379 $spaces[$level] +
= $chars['32'];
381 for ($x=0;$x<=$level;$x++
) {
382 if (isset($spaces[$x])) {
383 $spaces_total +
= $spaces[$x];
386 $indent = $level +
$spaces_total;
387 /* must have run into a message that broke the thread
388 * so we are adjusting for that portion
391 $indent = $indent +
1;
393 if (preg_match("/(\d+)/", $thread_new[$i][$k], $regs)) {
396 /* the thread must be broken if $indent == 0
397 * so indent the message once and start faking it
404 /* dont need abs but if indent was negative
407 $indent_array[$child] = ($indent < 0) ?
0 : $indent;
411 return $indent_array;
416 * Returns an array with each element as a string representing one
417 * message-thread as returned by the IMAP server.
418 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
420 function get_thread_sort($imap_stream, $search='ALL') {
421 global $thread_new, $sort_by_ref, $default_charset, $server_sort_array, $indent_array;
423 $thread_temp = array ();
424 if ($sort_by_ref == 1) {
425 $sort_type = 'REFERENCES';
427 $sort_type = 'ORDEREDSUBJECT';
429 $query = "THREAD $sort_type ".strtoupper($default_charset)." $search";
431 $thread_test = sqimap_run_command ($imap_stream, $query, false, $response, $message, TRUE);
432 /* fallback to default charset */
433 if ($response == 'NO' && strpos($message,'[BADCHARSET]') !== false) {
434 $query = "THREAD $sort_type US-ASCII $search";
435 $thread_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
437 if (isset($thread_test[0])) {
438 for ($i=0,$iCnt=count($thread_test);$i<$iCnt;++
$i) {
439 if (preg_match("/^\* THREAD (.+)$/", $thread_test[$i], $regs)) {
440 $thread_list = trim($regs[1]);
447 if (!preg_match("/OK/", $response)) {
448 $server_sort_array = 'no';
449 return $server_sort_array;
451 if (isset($thread_list)) {
452 $thread_temp = preg_split("//", $thread_list, -1, PREG_SPLIT_NO_EMPTY
);
456 $thread_new = array();
460 * parse the thread response into separate threads
465 * [2] => (1599 759 959 37)
467 * [4] => ((933)(1891))
468 * [5] => (1030 (1497)(845)(1637))
470 for ($i=0,$iCnt=count($thread_temp);$i<$iCnt;$i++
) {
471 if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
472 $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
473 } elseif ($thread_temp[$i] == '(') {
474 $thread_new[$k] .= $thread_temp[$i];
476 } elseif ($thread_temp[$i] == ')') {
478 $thread_new[$k] .= $thread_temp[$i];
479 $counter = $counter - 1;
481 $thread_new[$k] .= $thread_temp[$i];
483 $thread_new[$k] = "";
484 $counter = $counter - 1;
489 $thread_new = array_reverse($thread_new);
490 /* place the threads after each other in one string */
491 $thread_list = implode(" ", $thread_new);
492 $thread_list = str_replace("(", " ", $thread_list);
493 $thread_list = str_replace(")", " ", $thread_list);
494 $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY
);
495 $server_sort_array = $thread_list;
497 $indent_array = get_parent_level ($thread_new);
498 return array($thread_list,$indent_array);
502 function elapsedTime($start) {
503 $stop = gettimeofday();
504 $timepassed = 1000000 * ($stop['sec'] - $start['sec']) +
$stop['usec'] - $start['usec'];
510 * Normalise the different Priority headers into a uniform value,
511 * namely that of the X-Priority header (1, 3, 5). Supports:
512 * Prioirty, X-Priority, Importance.
513 * X-MS-Mail-Priority is not parsed because it always coincides
514 * with one of the other headers.
516 * FIXME: DUPLICATE CODE ALERT:
517 * NOTE: this is actually a duplicate from the function in
518 * class/mime/Rfc822Header.php.
519 * @todo obsolate function or use it instead of code block in parseFetch()
521 function parsePriority($sValue) {
522 $aValue = split('/\w/',trim($sValue));
523 $value = strtolower(array_shift($aValue));
524 if ( is_numeric($value) ) {
527 if ( $value == 'urgent' ||
$value == 'high' ) {
529 } elseif ( $value == 'non-urgent' ||
$value == 'low' ) {
536 * Parses a string in an imap response. String starts with " or { which means it
537 * can handle double quoted strings and literal strings
539 * @param string $read imap response
540 * @param integer $i (reference) offset in string
541 * @return string $s parsed string without the double quotes or literal count
543 function parseString($read,&$i) {
549 $iPos = strpos($read,'"',$iPos);
551 if ($iPos && $read{$iPos -1} != '\\') {
552 $s = substr($read,$i,($iPos-$i));
557 if ($iPos > strlen($read)) {
561 } else if ($char == '{') {
564 $iPos = strpos($read,'}',$i);
566 $lit_cnt = substr($read, $i, $iPos - $i);
567 $i +
= strlen($lit_cnt) +
3; /* skip } + \r + \n */
568 /* Now read the literal */
569 $s = ($lit_cnt ?
substr($read,$i,$lit_cnt): '');
571 /* temp bugfix (SM 1.5 will have a working clean version)
572 too much work to implement that version right now */
574 } else { /* should never happen */
575 $i +
= 3; /* } + \r + \n */
587 * Parses a string containing an array from an imap response. String starts with ( and end with )
589 * @param string $read imap response
590 * @param integer $i (reference) offset in string
593 function parseArray($read,&$i) {
594 $i = strpos($read,'(',$i);
595 $i_pos = strpos($read,')',$i);
596 $s = substr($read,$i+
1,$i_pos - $i -1);
597 $a = explode(' ',$s);
608 * Retrieves a list with headers, flags, size or internaldate from the imap server
610 * WARNING: function is not portable between SquirrelMail 1.2.x, 1.4.x and 1.5.x.
611 * Output format, third argument and $msg_list array format requirements differ.
612 * @param stream $imap_stream imap connection
613 * @param array $msg_list array with id's to create a msgs set from
614 * @param array $aHeaderFields (since 1.5.0) requested header fields
615 * @param array $aFetchItems (since 1.5.0) requested other fetch items like FLAGS, RFC822.SIZE
616 * @return array $aMessages associative array with messages. Key is the UID, value is an associative array
619 function sqimap_get_small_header_list($imap_stream, $msg_list,
620 $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type'),
621 $aFetchItems = array('FLAGS', 'RFC822.SIZE', 'INTERNALDATE')) {
623 $aMessageList = array();
626 * Catch other priority headers as well
628 if (in_array('X-Priority',$aHeaderFields,true)) {
629 $aHeaderFields[] = 'Importance';
630 $aHeaderFields[] = 'Priority';
633 $bUidFetch = ! in_array('UID', $aFetchItems, true);
635 /* Get the small headers for each message in $msg_list */
636 if ($msg_list !== NULL) {
637 $msgs_str = sqimap_message_list_squisher($msg_list);
639 * We need to return the data in the same order as the caller supplied
640 * in $msg_list, but IMAP servers are free to return responses in
641 * whatever order they wish... So we need to re-sort manually
644 for ($i = 0; $i < sizeof($msg_list); $i++
) {
645 $aMessageList["$msg_list[$i]"] = array();
657 $query = "FETCH $msgs_str (";
658 if (count($aFetchItems)) {
659 $sFetchItems = implode(' ',$aFetchItems);
661 if (count($aHeaderFields)) {
662 $sHeaderFields = implode(' ',$aHeaderFields);
663 $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
665 $query .= trim($sFetchItems) . ')';
666 $aResponse = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, $bUidFetch);
667 $aMessages = parseFetch($aResponse,$aMessageList);
668 array_reverse($aMessages);
674 * Parses a fetch response, currently it can hande FLAGS, HEADERS, RFC822.SIZE, INTERNALDATE and UID
675 * @param array $aResponse Imap response
676 * @param array $aMessageList Placeholder array for results. The keys of the
677 * placeholder array should be the UID so we can reconstruct the order.
678 * @return array $aMessageList associative array with messages. Key is the UID, value is an associative array
679 * @author Marc Groot Koerkamp
681 function parseFetch($aResponse,$aMessageList = array()) {
682 for ($j=0,$iCnt=count($aResponse);$j<$iCnt;++
$j) {
685 $read = implode('',$aResponse[$j]);
687 unset($aResponse[$j]); /* unset does not reindex the array. the for loop is safe */
689 * #id<space>FETCH<space>(
692 /* extract the message id */
693 $i_space = strpos($read,' ',2);/* position 2ed <space> */
694 $id = substr($read,2/* skip "*<space>" */,$i_space -2);
696 $fetch = substr($read,$i_space+
1,5);
697 if (!is_numeric($id) && $fetch !== 'FETCH') {
698 $aMsg['ERROR'] = $read; // htmlspecialchars should be done just before display. this is backend code
701 $i = strpos($read,'(',$i_space+
5);
702 $read = substr($read,$i+
1);
703 $i_len = strlen($read);
705 while ($i < $i_len && $i !== false) {
707 $read = trim(substr($read,$i));
708 $i_len = strlen($read);
709 $i = strpos($read,' ');
710 $arg = substr($read,0,$i);
713 * use allcaps for imap items and lowcaps for headers as key for the $aMsg array
718 $i_pos = strpos($read,' ',$i);
720 $i_pos = strpos($read,')',$i);
723 $unique_id = substr($read,$i,$i_pos-$i);
730 $flags = parseArray($read,$i);
731 if (!$flags) break 3;
733 foreach ($flags as $flag) {
734 $flag = strtolower($flag);
735 $aFlags[$flag] = true;
737 $aMsg['FLAGS'] = $aFlags;
740 $i_pos = strpos($read,' ',$i);
742 $i_pos = strpos($read,')',$i);
745 $aMsg['SIZE'] = substr($read,$i,$i_pos-$i);
752 // sqimap_parse_address($read,$i,$aMsg);
753 break; // to be implemented, moving imap code out of the Message class
754 case 'BODYSTRUCTURE':
755 break; // to be implemented, moving imap code out of the Message class
757 $aMsg['INTERNALDATE'] = trim(str_replace(' ', ' ',parseString($read,$i)));
759 case 'BODY.PEEK[HEADER.FIELDS':
760 case 'BODY[HEADER.FIELDS':
761 $i = strpos($read,'{',$i); // header is always returned as literal because it contain \n characters
762 $header = parseString($read,$i);
763 if ($header === false) break 2;
764 /* First we replace all \r\n by \n, and unfold the header */
765 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
766 /* Now we can make a new header array with
767 each element representing a headerline */
768 $aHdr = explode("\n" , $hdr);
769 $aReceived = array();
770 foreach ($aHdr as $line) {
771 $pos = strpos($line, ':');
773 $field = strtolower(substr($line, 0, $pos));
774 if (!strstr($field,' ')) { /* valid field */
775 $value = trim(substr($line, $pos+
1));
778 $aMsg['date'] = trim(str_replace(' ', ' ', $value));
780 case 'x-priority': $aMsg['x-priority'] = ($value) ?
(int) $value{0} : 3; break;
783 if (!isset($aMsg['x-priority'])) {
784 $aPrio = split('/\w/',trim($value));
785 $sPrio = strtolower(array_shift($aPrio));
786 if (is_numeric($sPrio)) {
787 $iPrio = (int) $sPrio;
788 } elseif ( $sPrio == 'non-urgent' ||
$sPrio == 'low' ) {
790 } elseif ( $sPrio == 'urgent' ||
$sPrio == 'high' ) {
793 // default is normal priority
796 $aMsg['x-priority'] = $iPrio;
801 if ($pos = strpos($type, ";")) {
802 $type = substr($type, 0, $pos);
804 $type = explode("/", $type);
805 if(!is_array($type) ||
count($type) < 2) {
806 $aMsg['content-type'] = array('text','plain');
808 $aMsg['content-type'] = array(strtolower($type[0]),strtolower($type[1]));
812 $aMsg['received'][] = $value;
815 $aMsg[$field] = $value;
827 if (!empty($unique_id)) {
828 $msgi = "$unique_id";
829 $aMsg['UID'] = $unique_id;
833 $aMessageList[$msgi] = $aMsg;
835 return $aMessageList;
841 * @author Marc Groot Koerkamp
843 function sqimap_parse_envelope($read, &$i, &$msg) {
847 for ($cnt = strlen($read); ($i < $cnt) && ($read{$i} != ')'); ++
$i) {
848 $char = strtoupper($read{$i});
852 $arg_a[] = parseString($read,$i);
856 /* probably NIL argument */
857 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
864 /* Address structure (with group support)
865 * Note: Group support is useless on SMTP connections
866 * because the protocol doesn't support it
871 for (; $i < $cnt && $read{$i} != ')'; ++
$i) {
872 if ($read{$i} == '(') {
873 $addr = sqimap_parse_address($read, $i);
874 if (($addr[3] == '') && ($addr[2] != '')) {
879 } else if ($group && ($addr[3] == '') && ($addr[2] == '')) {
881 if ($a == ($j+
1)) { /* no group members */
882 $group_addr[4] = $group;
884 $group_addr[0] = "$group: Undisclosed recipients;";
885 $addr_a[] = $group_addr;
901 if (count($arg_a) > 9) {
902 $d = strtr($arg_a[0], array(' ' => ' '));
903 $d = explode(' ', $d);
904 if (!$arg_a[1]) $arg_a[1] = '';
905 $msg['DATE'] = $d; /* argument 1: date */
906 $msg['SUBJECT'] = $arg_a[1]; /* argument 2: subject */
907 $msg['FROM'] = is_array($arg_a[2]) ?
$arg_a[2][0] : ''; /* argument 3: from */
908 $msg['SENDER'] = is_array($arg_a[3]) ?
$arg_a[3][0] : ''; /* argument 4: sender */
909 $msg['REPLY-TO'] = is_array($arg_a[4]) ?
$arg_a[4][0] : ''; /* argument 5: reply-to */
910 $msg['TO'] = $arg_a[5]; /* argument 6: to */
911 $msg['CC'] = $arg_a[6]; /* argument 7: cc */
912 $msg['BCC'] = $arg_a[7]; /* argument 8: bcc */
913 $msg['IN-REPLY-TO'] = $arg_a[8]; /* argument 9: in-reply-to */
914 $msg['MESSAGE-ID'] = $arg_a[9]; /* argument 10: message-id */
922 * @author Marc Groot Koerkamp
924 function sqimap_parse_address($read, &$i) {
926 for (; $read{$i} != ')'; ++
$i) {
927 $char = strtoupper($read{$i});
930 case '"': $arg_a[] = parseString($read,$i); break;
933 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
942 if (count($arg_a) == 4) {
945 // $adr = new AddressStructure();
946 // $adr->personal = $arg_a[0];
947 // $adr->adl = $arg_a[1];
948 // $adr->mailbox = $arg_a[2];
949 // $adr->host = $arg_a[3];
958 * Returns a message array with all the information about a message.
959 * See the documentation folder for more information about this array.
961 * @param resource $imap_stream imap connection
962 * @param integer $id uid of the message
963 * @param string $mailbox used for error handling, can be removed because we should return an error code and generate the message elsewhere
964 * @return Message Message object
966 function sqimap_get_message($imap_stream, $id, $mailbox) {
967 // typecast to int to prohibit 1:* msgs sets
970 $read = sqimap_run_command($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
972 if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
973 if (trim($regs[1])) {
974 $flags = preg_split('/ /', $regs[1],-1,'PREG_SPLIT_NI_EMPTY');
978 /* the message was not found, maybe the mailbox was modified? */
979 global $sort, $startMessage, $color;
981 $errmessage = _("The server couldn't find the message you requested.") .
982 '<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).");
983 /* this will include a link back to the message list */
984 error_message($errmessage, $mailbox, $sort, (int) $startMessage, $color);
987 $bodystructure = implode('',$read);
988 $msg = mime_structure($bodystructure,$flags);
989 $read = sqimap_run_command($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
990 $rfc822_header = new Rfc822Header();
991 $rfc822_header->parseHeader($read);
992 $msg->rfc822_header
= $rfc822_header;