6 * This implements functions that manipulate messages
7 * NOTE: Quite a few functions in this file are obsolete
9 * @copyright 1999-2022 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 mixed $id Normally an array which is a list with message UIDs to be copied
21 * or a string range such as "1:*" or a simple integer
22 * @param string $mailbox The destination to copy to
23 * @param bool $handle_errors Show error messages in case of a NO, BAD or BYE response
24 * @return bool If the copy completed without errors
26 function sqimap_msgs_list_copy($imap_stream, $id, $mailbox, $handle_errors = true) {
27 $msgs_id = sqimap_message_list_squisher($id);
28 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($mailbox), $handle_errors, $response, $message, TRUE);
29 if ($response == 'OK') {
38 * Move a set of messages ($id) to another mailbox. Deletes the originals.
39 * @param int $imap_stream The resource ID for the IMAP socket
40 * @param string $id The list of messages to move
41 * @param string $mailbox The destination to move to
42 * @param bool $handle_errors Show error messages in case of a NO, BAD or BYE response
43 * @param string $source_mailbox (since 1.5.1) name of source mailbox. It is used to
44 * validate that target mailbox != source mailbox.
45 * @return bool If the move completed without errors
47 function sqimap_msgs_list_move($imap_stream, $id, $mailbox, $handle_errors = true, $source_mailbox = false) {
48 if ($source_mailbox!==false && $source_mailbox==$mailbox) {
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 mixed $id Normally an array which is a list with message UIDs to be deleted
64 * or a string range such as "1:*" or a simple integer
65 * @param bool $bypass_trash (since 1.5.0) skip copy to trash
66 * @return array $aMessageList array with messages containing the new flags and UID @see parseFetch
69 function sqimap_msgs_list_delete($imap_stream, $mailbox, $id, $bypass_trash=false) {
70 // FIXME: Remove globals by introducing an associative array with properties as 4th argument as replacement for the $bypass_trash variable.
71 global $move_to_trash, $trash_folder, $mark_as_read_upon_delete;
72 if ($mark_as_read_upon_delete)
73 sqimap_toggle_flag($imap_stream, $id, '\\Seen', true, true);
74 if (($move_to_trash == true) && ($bypass_trash != true) &&
75 (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder)) ) {
77 * turn off internal error handling (fourth argument = false) and
78 * ignore copy to trash errors (allows to delete messages when overquota)
80 sqimap_msgs_list_copy ($imap_stream, $id, $trash_folder, false);
82 return sqimap_toggle_flag($imap_stream, $id, '\\Deleted', true, true);
87 * Set a flag on the provided uid list
88 * @param resource imap connection
89 * @param mixed $id Normally an array which is a list with message UIDs to be flagged
90 * or a string range such as "1:*" or a simple integer
91 * @param string $flag Flags to set/unset flags can be i.e.'\Seen', '\Answered', '\Seen \Answered'
92 * @param bool $set add (true) or remove (false) the provided flag
93 * @param bool $handle_errors Show error messages in case of a NO, BAD or BYE response
94 * @return array $aMessageList array with messages containing the new flags and UID @see parseFetch
96 function sqimap_toggle_flag($imap_stream, $id, $flag, $set, $handle_errors) {
97 $msgs_id = sqimap_message_list_squisher($id);
98 $set_string = ($set ?
'+' : '-');
101 * We need to return the data in the same order as the caller supplied
102 * in $id, but IMAP servers are free to return responses in
103 * whatever order they wish... So we need to re-sort manually
105 $aMessageList = array();
107 for ($i=0; $i<count($id); $i++
) {
108 $aMessageList[$id[$i]] = array();
112 $aResponse = sqimap_run_command_list($imap_stream, "STORE $msgs_id ".$set_string."FLAGS ($flag)", $handle_errors, $response, $message, TRUE);
114 // parse the fetch response
115 $parseFetchResults=parseFetch($aResponse,$aMessageList);
117 // some broken IMAP servers do not return UID elements on UID STORE
118 // if this is the case, then we need to do a UID FETCH
119 if (!empty($parseFetchResults)
120 && !isset(reset($parseFetchResults)['UID'])) {
121 $aResponse = sqimap_run_command_list($imap_stream, "FETCH $msgs_id (FLAGS)", $handle_errors, $response, $message, TRUE);
122 $parseFetchResults = parseFetch($aResponse,$aMessageList);
125 return ($parseFetchResults);
130 * Sort the message list and crunch to be as small as possible
131 * (overflow could happen, so make it small if possible)
132 * @param array $aUid array with uid's
133 * @return string $s message set string
135 function sqimap_message_list_squisher($aUid) {
136 if( !is_array( $aUid ) ) {
139 sort($aUid, SORT_NUMERIC
);
143 for ($i=0,$iCnt=count($aUid);$i<$iCnt;++
$i) {
146 while ($i<($iCnt-1) && $aUid[$i+
1] == $iEnd +
1) {
154 if ($iStart != $iEnd) {
164 * Retrieves an array with a sorted uid list. Sorting is done on the imap server
165 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-17.txt
166 * @param resource $imap_stream IMAP socket connection
167 * @param string $sSortField Field to sort on
168 * @param bool $reverse Reverse order search
169 * @return array $id sorted uid list
171 function sqimap_get_sort_order($imap_stream, $sSortField, $reverse, $search='ALL') {
172 global $default_charset;
176 $sSortField = 'REVERSE '.$sSortField;
178 $query = "SORT ($sSortField) ".strtoupper($default_charset)." $search";
179 // FIXME: sqimap_run_command() should return the parsed data accessible by $aDATA['SORT']
180 // use sqimap_run_command_list() in case of unsolicited responses. If we don't we could loose the SORT response.
181 $aData = sqimap_run_command_list ($imap_stream, $query, false, $response, $message, TRUE);
182 /* fallback to default charset */
183 if ($response == 'NO') {
184 if (strpos($message,'BADCHARSET') !== false ||
185 strpos($message,'character') !== false) {
186 sqm_trigger_imap_error('SQM_IMAP_BADCHARSET',$query, $response, $message);
187 $query = "SORT ($sSortField) US-ASCII $search";
188 $aData = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, TRUE);
190 sqm_trigger_imap_error('SQM_IMAP_ERROR',$query, $response, $message);
192 } else if ($response == 'BAD') {
193 sqm_trigger_imap_error('SQM_IMAP_NO_SORT',$query, $response, $message);
197 if ($response == 'OK') {
198 return parseUidList($aData,'SORT');
206 * Parses a UID list returned on a SORT or SEARCH request
207 * @param array $aData imap response (retrieved from sqimap_run_command_list)
208 * @param string $sCommand issued imap command (SEARCH or SORT)
209 * @return array $aUid uid list
211 function parseUidList($aData,$sCommand) {
213 if (isset($aData) && count($aData)) {
214 for ($i=0,$iCnt=count($aData);$i<$iCnt;++
$i) {
215 for ($j=0,$jCnt=count($aData[$i]);$j<$jCnt;++
$j) {
216 if (preg_match("/^\* $sCommand (.+)$/", $aData[$i][$j], $aMatch)) {
217 $aUid +
= explode(' ', trim($aMatch[1]));
222 return array_unique($aUid);
226 * Retrieves an array with a sorted uid list. Sorting is done by SquirrelMail
228 * @param resource $imap_stream IMAP socket connection
229 * @param string $sSortField Field to sort on
230 * @param bool $reverse Reverse order search
231 * @param array $aUid limit the search to the provided array with uid's default sqimap_get_small_headers uses 1:*
232 * @return array $aUid sorted uid list
234 function get_squirrel_sort($imap_stream, $sSortField, $reverse = false, $aUid = NULL) {
235 if ($sSortField != 'RFC822.SIZE' && $sSortField != 'INTERNALDATE') {
236 $msgs = sqimap_get_small_header_list($imap_stream, $aUid,
237 array($sSortField), array());
239 $msgs = sqimap_get_small_header_list($imap_stream, $aUid,
240 array(), array($sSortField));
243 // sqimap_get_small_header (see above) returns fields in lower case,
244 // but the code below uses all upper case
245 foreach ($msgs as $k => $v)
246 if (isset($msgs[$k][strtolower($sSortField)]))
247 $msgs[$k][strtoupper($sSortField)] = $msgs[$k][strtolower($sSortField)];
251 switch ($sSortField) {
252 // natcasesort section
257 if (check_php_version(5, 3, 0))
258 $walk_function = function(&$v,&$k,$f) {
259 $v[$f] = (isset($v[$f])) ?
$v[$f] : "";
260 $addr = reset(parseRFC822Address($v[$f],1));
261 $sPersonal = (isset($addr[SQM_ADDR_PERSONAL
]) && $addr[SQM_ADDR_PERSONAL
]) ?
262 $addr[SQM_ADDR_PERSONAL
] : "";
263 $sEmail = ($addr[SQM_ADDR_HOST
]) ?
264 $addr[SQM_ADDR_MAILBOX
] . "@".$addr[SQM_ADDR_HOST
] :
265 $addr[SQM_ADDR_HOST
];
266 $v[$f] = ($sPersonal) ?
decodeHeader($sPersonal, true, false):$sEmail;
269 $walk_function = create_function('&$v,&$k,$f',
270 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
271 $addr = reset(parseRFC822Address($v[$f],1));
272 $sPersonal = (isset($addr[SQM_ADDR_PERSONAL]) && $addr[SQM_ADDR_PERSONAL]) ?
273 $addr[SQM_ADDR_PERSONAL] : "";
274 $sEmail = ($addr[SQM_ADDR_HOST]) ?
275 $addr[SQM_ADDR_MAILBOX] . "@".$addr[SQM_ADDR_HOST] :
276 $addr[SQM_ADDR_HOST];
277 $v[$f] = ($sPersonal) ? decodeHeader($sPersonal, true, false):$sEmail;');
278 array_walk($msgs, $walk_function, $sSortField);
284 if (check_php_version(5, 3, 0))
285 $walk_function = function(&$v,&$k,$f) {
286 $v[$f] = (isset($v[$f])) ?
$v[$f] : "";
287 $v[$f] = strtolower(decodeHeader(trim($v[$f]), true, false));
288 $v[$f] = (preg_match("/^(?:(?:vedr|sv|re|aw|fw|fwd|\[\w\]):\s*)*\s*(.*)$/si", $v[$f], $matches)) ?
289 $matches[1] : $v[$f];
292 $walk_function = create_function('&$v,&$k,$f',
293 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
294 $v[$f] = strtolower(decodeHeader(trim($v[$f]), true, false));
295 $v[$f] = (preg_match("/^(?:(?:vedr|sv|re|aw|fw|fwd|\[\w\]):\s*)*\s*(.*)$/si", $v[$f], $matches)) ?
296 $matches[1] : $v[$f];');
297 array_walk($msgs, $walk_function, $sSortField);
300 foreach ($msgs as $item) {
301 $aUid[$item['UID']] = $item[$sSortField];
304 $aUid = array_keys($aUid);
306 $aUid = array_reverse($aUid);
309 // \natcasesort section
310 // sort_numeric section
314 if (check_php_version(5, 3, 0))
315 $walk_function = function(&$v,$k,$f) {
316 $v[$f] = (isset($v[$f])) ?
$v[$f] : "";
317 $v[$f] = getTimeStamp(explode(" ",$v[$f]));
320 $walk_function = create_function('&$v,$k,$f',
321 '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
322 $v[$f] = getTimeStamp(explode(" ",$v[$f]));');
323 array_walk($msgs, $walk_function, $sSortField);
329 // redefine $sSortField to maintain the same namespace between
330 // server-side sorting and SquirrelMail sorting
331 $sSortField = 'SIZE';
333 foreach ($msgs as $item) {
334 $aUid[$item['UID']] = (isset($item[$sSortField])) ?
$item[$sSortField] : 0;
337 arsort($aUid,SORT_NUMERIC
);
339 asort($aUid, SORT_NUMERIC
);
341 $aUid = array_keys($aUid);
343 // \sort_numeric section
345 $aUid = array_reverse($msgs);
352 * Returns an array with each element as a string representing one
353 * message-thread as returned by the IMAP server.
354 * @param resource $imap_stream IMAP socket connection
355 * @param string $search optional search string
357 * @link http://www.ietf.org/internet-drafts/draft-ietf-imapext-sort-13.txt
359 function get_thread_sort($imap_stream, $search='ALL') {
360 global $sort_by_ref, $default_charset;
362 if ($sort_by_ref == 1) {
363 $sort_type = 'REFERENCES';
365 $sort_type = 'ORDEREDSUBJECT';
367 $query = "THREAD $sort_type ".strtoupper($default_charset)." $search";
369 // TODO use sqimap_run_command_list as we do in get_server_sort()
370 $sRead = sqimap_run_command ($imap_stream, $query, false, $response, $message, TRUE);
372 /* fallback to default charset */
373 if ($response == 'NO') {
374 if (strpos($message,'BADCHARSET') !== false ||
375 strpos($message,'character') !== false) {
376 sqm_trigger_imap_error('SQM_IMAP_BADCHARSET',$query, $response, $message);
377 $query = "THREAD $sort_type US-ASCII $search";
378 $sRead = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
380 sqm_trigger_imap_error('SQM_IMAP_ERROR',$query, $response, $message);
382 } elseif ($response == 'BAD') {
383 sqm_trigger_imap_error('SQM_IMAP_NO_THREAD',$query, $response, $message);
385 $sThreadResponse = '';
386 if (isset($sRead[0])) {
387 for ($i=0,$iCnt=count($sRead);$i<$iCnt;++
$i) {
388 if (preg_match("/^\* THREAD (.+)$/", $sRead[$i], $aMatch)) {
389 $sThreadResponse = trim($aMatch[1]);
396 if ($response !== 'OK') {
401 * S: * THREAD (2)(3 6 (4 23)(44 7 96))
414 * Notes for future work:
415 * indent_array should contain: indent_level, parent and flags,
417 * To achieve that we need to define the following flags:
422 * a node has sibling nodes if it's not the last node
423 * a node has no sibling nodes if it's the last node
424 * By using binary comparations we can store the flag in one var
427 * -1 par = 0, level = 0, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
428 * \-2 par = 1, level = 1, flag = 0 + 2 = 2 (hasnochildren, isfirst)
429 * |-3 par = 1, level = 1, flag = 1 + 4 = 5 (haschildren, islast)
430 * \-4 par = 3, level = 2, flag = 1 + 2 + 4 = 7 (haschildren, isfirst, islast)
431 * \-5 par = 4, level = 3, flag = 0 + 2 + 4 = 6 (hasnochildren, isfirst, islast)
437 $aUidThread = array();
439 $aUidSubThread = array();
440 $aDepthStack = array();
443 if ($sThreadResponse) {
444 for ($i=0,$iCnt = strlen($sThreadResponse);$i<$iCnt;++
$i) {
445 $cChar = $sThreadResponse[$i];
447 case '(': // new sub thread
448 // correction for a subthread of a thread with no parents in thread
449 if (!count($aUidSubThread) && $j > 0) {
452 $aDepthStack[$j] = $l;
455 case ')': // close sub thread
457 $aUidSubThread[] = $sUid;
458 $aIndent[$sUid] = $j +
$l - 1;
464 // show message that starts the thread first.
465 $aUidSubThread = array_reverse($aUidSubThread);
466 // do not use array_merge because it's extremely slow and is causing timeouts
467 foreach ($aUidSubThread as $iUid) {
468 $aUidThread[] = $iUid;
470 $aUidSubThread = array();
472 $aDepthStack = array();
474 $l = $aDepthStack[$j];
477 case ' ': // new child
479 $aUidSubThread[] = $sUid;
480 $aIndent[$sUid] = $j +
$l - 1;
485 default: // part of UID
491 unset($sThreadResponse);
492 // show newest threads first
493 $aUidThread = array_reverse($aUidThread);
494 return array($aUidThread,$aIndent);
498 function elapsedTime($start) {
499 $stop = gettimeofday();
500 $timepassed = 1000000 * ($stop['sec'] - $start['sec']) +
$stop['usec'] - $start['usec'];
505 * Parses a string in an imap response. String starts with " or { which means it
506 * can handle double quoted strings and literal strings
508 * @param string $read imap response
509 * @param integer $i (reference) offset in string
510 * @return string $s parsed string without the double quotes or literal count
512 function parseString($read,&$i) {
518 $iPos = strpos($read,'"',$iPos);
520 if ($iPos && $read[$iPos -1] != '\\') {
521 $s = substr($read,$i,($iPos-$i));
526 if ($iPos > strlen($read)) {
530 } else if ($char == '{') {
533 $iPos = strpos($read,'}',$i);
535 $lit_cnt = substr($read, $i, $iPos - $i);
536 $i +
= strlen($lit_cnt) +
3; /* skip } + \r + \n */
537 /* Now read the literal */
538 $s = ($lit_cnt ?
substr($read,$i,$lit_cnt): '');
540 /* temp bugfix (SM 1.5 will have a working clean version)
541 too much work to implement that version right now */
543 } else { /* should never happen */
544 $i +
= 3; /* } + \r + \n */
556 * Parses a string containing an array from an imap response. String starts with ( and end with )
558 * @param string $read imap response
559 * @param integer $i (reference) offset in string
562 function parseArray($read,&$i) {
563 $i = strpos($read,'(',$i);
564 $i_pos = strpos($read,')',$i);
565 $s = substr($read,$i+
1,$i_pos - $i -1);
566 $a = explode(' ',$s);
577 * Retrieves a list with headers, flags, size or internaldate from the imap server
579 * WARNING: function is not portable between SquirrelMail 1.2.x, 1.4.x and 1.5.x.
580 * Output format, third argument and $msg_list array format requirements differ.
581 * @param stream $imap_stream imap connection
582 * @param array $msg_list array with id's to create a msgs set from
583 * @param array $aHeaderFields (since 1.5.0) requested header fields
584 * @param array $aFetchItems (since 1.5.0) requested other fetch items like FLAGS, RFC822.SIZE
585 * @return array $aMessages associative array with messages. Key is the UID, value is an associative array
588 function sqimap_get_small_header_list($imap_stream, $msg_list,
589 $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type'),
590 $aFetchItems = array('FLAGS', 'RFC822.SIZE', 'INTERNALDATE')) {
592 global $extra_small_header_fields;
593 if (!empty($extra_small_header_fields))
594 $aHeaderFields = array_merge($aHeaderFields, $extra_small_header_fields);
596 $aMessageList = array();
599 * Catch other priority headers as well
601 if (in_array('X-Priority',$aHeaderFields,true)) {
602 $aHeaderFields[] = 'Importance';
603 $aHeaderFields[] = 'Priority';
606 $bUidFetch = ! in_array('UID', $aFetchItems, true);
608 /* Get the small headers for each message in $msg_list */
609 if ($msg_list !== NULL) {
610 $msgs_str = sqimap_message_list_squisher($msg_list);
612 * We need to return the data in the same order as the caller supplied
613 * in $msg_list, but IMAP servers are free to return responses in
614 * whatever order they wish... So we need to re-sort manually
617 for ($i = 0; $i < sizeof($msg_list); $i++
) {
618 $aMessageList[$msg_list[$i]] = array();
630 $query = "FETCH $msgs_str (";
631 if (count($aFetchItems)) {
632 $sFetchItems = implode(' ',$aFetchItems);
634 if (count($aHeaderFields)) {
635 $sHeaderFields = implode(' ',$aHeaderFields);
636 $sFetchItems .= ' BODY.PEEK[HEADER.FIELDS ('.$sHeaderFields.')]';
638 $query .= trim($sFetchItems) . ')';
639 $aResponse = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, $bUidFetch);
640 $aMessages = parseFetch($aResponse,$aMessageList);
641 array_reverse($aMessages);
647 * Parses a fetch response, currently it can hande FLAGS, HEADERS, RFC822.SIZE, INTERNALDATE and UID
648 * @param array $aResponse Imap response
649 * @param array $aMessageList Placeholder array for results. The keys of this
650 * placeholder array should be the UID so we can
651 * reconstruct the order (OPTIONAL; this array will
652 * be built for the return value fresh if not given)
653 * @return array $aMessageList associative array with messages. Key is the UID, value is an associative array
654 * @author Marc Groot Koerkamp
656 function parseFetch(&$aResponse,$aMessageList = array()) {
657 for ($j=0,$iCnt=count($aResponse);$j<$iCnt;++
$j) {
660 $read = implode('',$aResponse[$j]);
662 unset($aResponse[$j]); /* unset does not reindex the array. the for loop is safe */
664 * #id<space>FETCH<space>(
667 /* extract the message id */
668 $i_space = strpos($read,' ',2);/* position 2ed <space> */
669 $id = substr($read,2/* skip "*<space>" */,$i_space -2);
671 $fetch = substr($read,$i_space+
1,5);
672 if (!is_numeric($id) && $fetch !== 'FETCH') {
673 $aMsg['ERROR'] = $read; // sm_encode_html_special_chars should be done just before display. this is backend code
676 $i = strpos($read,'(',$i_space+
5);
677 $read = substr($read,$i+
1);
678 $i_len = strlen($read);
680 while ($i < $i_len && $i !== false) {
682 $read = trim(substr($read,$i));
683 $i_len = strlen($read);
684 $i = strpos($read,' ');
685 $arg = substr($read,0,$i);
688 * use allcaps for imap items and lowcaps for headers as key for the $aMsg array
693 $i_pos = strpos($read,' ',$i);
695 $i_pos = strpos($read,')',$i);
698 $unique_id = substr($read,$i,$i_pos-$i);
705 $flags = parseArray($read,$i);
706 if (!$flags) break 3;
708 foreach ($flags as $flag) {
709 $flag = strtolower($flag);
710 $aFlags[$flag] = true;
712 $aMsg['FLAGS'] = $aFlags;
715 $i_pos = strpos($read,' ',$i);
717 $i_pos = strpos($read,')',$i);
720 $aMsg['SIZE'] = substr($read,$i,$i_pos-$i);
727 // sqimap_parse_address($read,$i,$aMsg);
728 break; // to be implemented, moving imap code out of the Message class
729 case 'BODYSTRUCTURE':
730 break; // to be implemented, moving imap code out of the Message class
732 $aMsg['INTERNALDATE'] = trim(preg_replace('/\s+/', ' ',parseString($read,$i)));
734 case 'BODY.PEEK[HEADER.FIELDS':
735 case 'BODY[HEADER.FIELDS':
736 $i = strpos($read,'{',$i); // header is always returned as literal because it contain \n characters
737 $header = parseString($read,$i);
738 if ($header === false) break 2;
739 /* First we replace all \r\n by \n, and unfold the header */
740 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
741 /* Now we can make a new header array with
742 each element representing a headerline */
743 $aHdr = explode("\n" , $hdr);
744 $aReceived = array();
745 foreach ($aHdr as $line) {
746 $pos = strpos($line, ':');
748 $field = strtolower(substr($line, 0, $pos));
749 if (!strstr($field,' ')) { /* valid field */
750 $value = trim(substr($line, $pos+
1));
753 $aMsg['date'] = trim(preg_replace('/\s+/', ' ', $value));
755 case 'x-priority': $aMsg['x-priority'] = ($value) ?
(int) $value[0] : 3; break;
758 // duplicate code with Rfc822Header.cls:parsePriority()
759 if (!isset($aMsg['x-priority'])) {
760 $aPrio = preg_split('/\s/',trim($value));
761 $sPrio = strtolower(array_shift($aPrio));
762 if (is_numeric($sPrio)) {
763 $iPrio = (int) $sPrio;
764 } elseif ( $sPrio == 'non-urgent' ||
$sPrio == 'low' ) {
766 } elseif ( $sPrio == 'urgent' ||
$sPrio == 'high' ) {
769 // default is normal priority
772 $aMsg['x-priority'] = $iPrio;
777 if ($pos = strpos($type, ";")) {
778 $type = substr($type, 0, $pos);
780 $type = explode("/", $type);
781 if(!is_array($type) ||
count($type) < 2) {
782 $aMsg['content-type'] = array('text','plain');
784 $aMsg['content-type'] = array(strtolower($type[0]),strtolower($type[1]));
788 $aMsg['received'][] = $value;
791 $aMsg[$field] = $value;
803 if (!empty($unique_id)) {
804 $msgi = "$unique_id";
805 $aMsg['UID'] = $unique_id;
807 //FIXME: under what circumstances does this happen? We can't use an empty string as an array index in the line just below, so we need to use something else here
810 $aMessageList[$msgi] = $aMsg;
811 $aResponse[$j] = NULL;
813 return $aMessageList;
819 * @author Marc Groot Koerkamp
821 function sqimap_parse_envelope($read, &$i, &$msg) {
825 for ($cnt = strlen($read); ($i < $cnt) && ($read[$i] != ')'); ++
$i) {
826 $char = strtoupper($read[$i]);
830 $arg_a[] = parseString($read,$i);
834 /* probably NIL argument */
835 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
842 /* Address structure (with group support)
843 * Note: Group support is useless on SMTP connections
844 * because the protocol doesn't support it
849 for (; $i < $cnt && $read[$i] != ')'; ++
$i) {
850 if ($read[$i] == '(') {
851 $addr = sqimap_parse_address($read, $i);
852 if (($addr[3] == '') && ($addr[2] != '')) {
857 } else if ($group && ($addr[3] == '') && ($addr[2] == '')) {
859 if ($a == ($j+
1)) { /* no group members */
860 $group_addr[4] = $group;
862 $group_addr[0] = "$group: Undisclosed recipients;";
863 $addr_a[] = $group_addr;
879 if (count($arg_a) > 9) {
880 $d = strtr($arg_a[0], array(' ' => ' '));
881 $d = explode(' ', $d);
882 if (!$arg_a[1]) $arg_a[1] = '';
883 $msg['DATE'] = $d; /* argument 1: date */
884 $msg['SUBJECT'] = $arg_a[1]; /* argument 2: subject */
885 $msg['FROM'] = is_array($arg_a[2]) ?
$arg_a[2][0] : ''; /* argument 3: from */
886 $msg['SENDER'] = is_array($arg_a[3]) ?
$arg_a[3][0] : ''; /* argument 4: sender */
887 $msg['REPLY-TO'] = is_array($arg_a[4]) ?
$arg_a[4][0] : ''; /* argument 5: reply-to */
888 $msg['TO'] = $arg_a[5]; /* argument 6: to */
889 $msg['CC'] = $arg_a[6]; /* argument 7: cc */
890 $msg['BCC'] = $arg_a[7]; /* argument 8: bcc */
891 $msg['IN-REPLY-TO'] = $arg_a[8]; /* argument 9: in-reply-to */
892 $msg['MESSAGE-ID'] = $arg_a[9]; /* argument 10: message-id */
900 * @author Marc Groot Koerkamp
902 function sqimap_parse_address($read, &$i) {
904 for (; $read[$i] != ')'; ++
$i) {
905 $char = strtoupper($read[$i]);
908 case '"': $arg_a[] = parseString($read,$i); break;
911 if (strtoupper(substr($read, $i, 3)) == 'NIL') {
920 if (count($arg_a) == 4) {
923 // $adr = new AddressStructure();
924 // $adr->personal = $arg_a[0];
925 // $adr->adl = $arg_a[1];
926 // $adr->mailbox = $arg_a[2];
927 // $adr->host = $arg_a[3];
936 * Returns a message array with all the information about a message.
937 * See the documentation folder for more information about this array.
939 * @param resource $imap_stream imap connection
940 * @param integer $id uid of the message
941 * @param string $mailbox used for error handling, can be removed because we should return an error code and generate the message elsewhere
942 * @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)
943 * @return mixed Message object or FALSE/error string if error occurred and $hide is set to 2/3
945 function sqimap_get_message($imap_stream, $id, $mailbox, $hide=0) {
946 // typecast to int to prohibit 1:* msgs sets
947 // Update: $id should always be sanitized into a BIGINT so this
948 // is being removed; leaving this code here in case something goes
952 $read = sqimap_run_command($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
954 if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
955 if (trim($regs[1])) {
956 $flags = preg_split('/ /', $regs[1],-1,PREG_SPLIT_NO_EMPTY
);
961 if ($hide == 1) exit;
962 if ($hide == 2) return FALSE;
964 /* the message was not found, maybe the mailbox was modified? */
965 global $sort, $startMessage;
967 $errmessage = _("The server couldn't find the message you requested.");
969 if ($hide == 3) return $errmessage;
971 $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).");
973 /* this will include a link back to the message list */
974 error_message($errmessage, $mailbox, $sort, (int) $startMessage);
977 $bodystructure = implode('',$read);
978 $msg = mime_structure($bodystructure,$flags);
979 $read = sqimap_run_command($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
980 $rfc822_header = new Rfc822Header();
981 $rfc822_header->parseHeader($read);
982 $msg->rfc822_header
= $rfc822_header;
984 parse_message_entities($msg, $id, $imap_stream);
990 * Recursively parse embedded messages (if any) in the given
991 * message, building correct rfc822 headers for each one
993 * @param object $msg The message object to scan for attached messages
994 * NOTE: this is passed by reference! Changes made
995 * within will affect the caller's copy of $msg!
996 * @param int $id The top-level message UID on the IMAP server, even
997 * if the $msg being passed in is only an attached entity
999 * @param resource $imap_stream A live connection to the IMAP server.
1006 function parse_message_entities(&$msg, $id, $imap_stream) {
1007 if (!empty($msg->entities
)) foreach ($msg->entities
as $i => $entity) {
1008 if (is_object($entity) && strtolower(get_class($entity)) == 'message') {
1009 if (!empty($entity->rfc822_header
)) {
1010 $read = sqimap_run_command($imap_stream, "FETCH $id BODY[". $entity->entity_id
.".HEADER]", true, $response, $message, TRUE);
1011 $rfc822_header = new Rfc822Header();
1012 $rfc822_header->parseHeader($read);
1013 $msg->entities
[$i]->rfc822_header
= $rfc822_header;
1015 parse_message_entities($msg->entities
[$i], $id, $imap_stream);