6 * Copyright (c) 1999-2004 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This implements functions that manipulate messages
10 * NOTE: Quite a few functions in this file are obsolete
13 * @package squirrelmail
17 * Copies specified messages to specified folder
18 * @param int $imap_stream The resource ID for the IMAP connection
19 * @param string $start Beginning of range to copy
20 * @param string $end End of the range to copy
21 * @param string $mailbox Which box to copy to
22 * @deprecated This function is obsolete and should not be used
24 function sqimap_messages_copy ($imap_stream, $start, $end, $mailbox) {
25 $read = sqimap_run_command ($imap_stream, "COPY $start:$end " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
29 * copy a range of messages ($id) to another mailbox ($mailbox)
30 * @param int $imap_stream The resource ID for the IMAP socket
31 * @param string $id The list of messages to copy
32 * @param string $mailbox The destination to copy to
35 function sqimap_msgs_list_copy ($imap_stream, $id, $mailbox) {
36 $msgs_id = sqimap_message_list_squisher($id);
37 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
41 * move a range of messages ($id) to another mailbox. Deletes the originals.
42 * @param int $imap_stream The resource ID for the IMAP socket
43 * @param string $id The list of messages to move
44 * @param string $mailbox The destination to move to
47 function sqimap_msgs_list_move ($imap_stream, $id, $mailbox) {
48 $msgs_id = sqimap_message_list_squisher($id);
49 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
50 $read = sqimap_run_command ($imap_stream, "STORE $msgs_id +FLAGS (\\Deleted)", true, $response,$message, TRUE);
55 * Deletes specified messages and moves them to trash if possible
56 * @deprecated This function is obsolete and should no longer be used
57 * @param int $imap_steam The resource ID for the IMAP connection
58 * @param string $start Start of range
59 * @param string $end End of range
60 * @param string $mailbox Mailbox messages are being deleted from
63 function sqimap_messages_delete ($imap_stream, $start, $end, $mailbox, $bypass_trash=false) {
64 global $move_to_trash, $trash_folder, $auto_expunge;
66 if (($move_to_trash == true) && ($bypass_trash != true) &&
67 (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder))) {
68 sqimap_messages_copy ($imap_stream, $start, $end, $trash_folder);
70 sqimap_messages_flag ($imap_stream, $start, $end, "Deleted", true);
73 function sqimap_msgs_list_delete ($imap_stream, $mailbox, $id, $bypass_trash=false) {
74 global $move_to_trash, $trash_folder;
75 $msgs_id = sqimap_message_list_squisher($id);
76 if (($move_to_trash == true) && ($bypass_trash != true) &&
77 (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder)) ) {
78 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($trash_folder), true, $response, $message, TRUE);
80 $read = sqimap_run_command ($imap_stream, "STORE $msgs_id +FLAGS (\\Deleted)", true, $response, $message, TRUE);
85 * Sets the specified messages with specified flag
87 function sqimap_messages_flag ($imap_stream, $start, $end, $flag, $handle_errors) {
88 $read = sqimap_run_command ($imap_stream, "STORE $start:$end +FLAGS (\\$flag)", $handle_errors, $response, $message, TRUE);
91 function sqimap_toggle_flag($imap_stream, $id, $flag, $set, $handle_errors) {
92 $msgs_id = sqimap_message_list_squisher($id);
93 $set_string = ($set ?
'+' : '-');
94 $read = sqimap_run_command ($imap_stream, "STORE $msgs_id ".$set_string."FLAGS ($flag)", $handle_errors, $response, $message, TRUE);
98 function sqimap_get_small_header ($imap_stream, $id, $sent) {
99 $res = sqimap_get_small_header_list($imap_stream, $id, $sent);
104 * Sort the message list and crunch to be as small as possible
105 * (overflow could happen, so make it small if possible)
107 function sqimap_message_list_squisher($messages_array) {
108 if( !is_array( $messages_array ) ) {
109 return $messages_array;
112 sort($messages_array, SORT_NUMERIC
);
114 while ($messages_array) {
115 $start = array_shift($messages_array);
117 while (isset($messages_array[0]) && $messages_array[0] == $end +
1) {
118 $end = array_shift($messages_array);
120 if ($msgs_str != '') {
124 if ($start != $end) {
125 $msgs_str .= ':' . $end;
132 * Get sort order from server and return it as the $id array for mailbox_display.
134 function sqimap_get_sort_order ($imap_stream, $sort, $mbxresponse) {
135 global $default_charset, $thread_sort_messages,
136 $internal_date_sort, $server_sort_array,
137 $sent_folder, $mailbox;
139 if (sqsession_is_registered('server_sort_array')) {
140 sqsession_unregister('server_sort_array');
145 $server_sort_array = array();
146 $sort_test = array();
150 if (isset($mbxresponse['UIDNEXT']) && $mbxresponse['UIDNEXT']) {
151 $uidnext = $mbxresponse['UIDNEXT']-1;
155 $query = "SEARCH UID 1:$uidnext";
156 $uids = sqimap_run_command ($imap_stream, $query, true, $response, $message, true);
157 if (isset($uids[0])) {
158 if (preg_match("/^\* SEARCH (.+)$/", $uids[0], $regs)) {
159 $server_sort_array = preg_split("/ /", trim($regs[1]));
162 if (!preg_match("/OK/", $response)) {
163 $server_sort_array = 'no';
165 $server_sort_array = array_reverse($server_sort_array);
166 sqsession_register($server_sort_array, 'server_sort_array');
167 return $server_sort_array;
170 $sort_on = array (0=> 'DATE',
176 if ($internal_date_sort == true) {
177 $sort_on[0] = 'ARRIVAL';
178 $sort_on[1] = 'ARRIVAL';
180 if ($sent_folder == $mailbox) {
184 if (!empty($sort_on[$sort])) {
185 $query = "SORT ($sort_on[$sort]) ".strtoupper($default_charset).' ALL';
186 $sort_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
188 if (isset($sort_test[0])) {
189 for ($i=0,$iCnt=count($sort_test);$i<$iCnt;++
$i) {
190 if (preg_match("/^\* SORT (.+)$/", $sort_test[$i], $regs)) {
191 $server_sort_array = preg_split("/ /", trim($regs[1]));
196 if ($sort == 0 ||
$sort == 2 ||
$sort == 4) {
197 $server_sort_array = array_reverse($server_sort_array);
199 if (!preg_match("/OK/", $response)) {
200 $server_sort_array = 'no';
202 sqsession_register($server_sort_array, 'server_sort_array');
203 return $server_sort_array;
207 * Get sort order from server if server does not have the SORT extension
208 * and return it as array for mailbox_display.
210 * @param resource $imap_stream
211 * @param array $mbxresponse response from a sqimap_mailbox_select
212 * @return array $php_sort_array
214 function sqimap_get_php_sort_order ($imap_stream, $mbxresponse) {
216 if (sqsession_is_registered('php_sort_array')) {
217 sqsession_unregister('php_sort_array');
220 $php_sort_array = array();
222 if (isset($mbxresponse['UIDNEXT']) && $mbxresponse['UIDNEXT']) {
223 $uidnext = $mbxresponse['UIDNEXT']-1;
227 $query = "SEARCH UID 1:$uidnext";
228 $uids = sqimap_run_command ($imap_stream, $query, true, $response, $message, true);
229 if (isset($uids[0])) {
230 $php_sort_array = array();
231 // EIMS workaround. EIMS returns the result as multiple untagged SEARCH responses
232 foreach($uids as $line) {
233 if (preg_match("/^\* SEARCH (.+)$/", $line, $regs)) {
234 $php_sort_array +
= preg_split("/ /", trim($regs[1]));
238 if (!preg_match("/OK/", $response)) {
239 $php_sort_array = 'no';
241 sqsession_register($php_sort_array, 'php_sort_array');
242 return $php_sort_array;
247 * Returns an indent array for printMessageinfo()
248 * This represents the amount of indent needed (value),
249 * for this message number (key)
251 function get_parent_level ($imap_stream) {
252 global $sort_by_ref, $default_charset, $thread_new;
257 /* loop through the threads and take unwanted characters out
258 of the thread string then chop it up
260 for ($i=0;$i<count($thread_new);$i++
) {
261 $thread_new[$i] = preg_replace("/\s\(/", "(", $thread_new[$i]);
262 $thread_new[$i] = preg_replace("/(\d+)/", "$1|", $thread_new[$i]);
263 $thread_new[$i] = preg_split("/\|/", $thread_new[$i], -1, PREG_SPLIT_NO_EMPTY
);
265 $indent_array = array();
267 $thread_new = array();
269 /* looping through the parts of one message thread */
271 for ($i=0;$i<count($thread_new);$i++
) {
272 /* first grab the parent, it does not indent */
274 if (isset($thread_new[$i][0])) {
275 if (preg_match("/(\d+)/", $thread_new[$i][0], $regs)) {
279 $indent_array[$parent] = 0;
281 /* now the children, checking each thread portion for
282 ),(, and space, adjusting the level and space values
283 to get the indent level
290 for ($k=1;$k<(count($thread_new[$i]))-1;$k++
) {
291 $chars = count_chars($thread_new[$i][$k], 1);
292 if (isset($chars['40'])) { /* testing for ( */
293 $level = $level +
$chars['40'];
295 if (isset($chars['41'])) { /* testing for ) */
296 $level = $level - $chars['41'];
298 /* if we were faking lets stop, this portion
299 of the thread is over
301 if ($level == $cutoff) {
305 if (isset($chars['32'])) { /* testing for space */
306 if (!isset($spaces[$level])) {
309 $spaces[$level] = $spaces[$level] +
$chars['32'];
311 for ($x=0;$x<=$level;$x++
) {
312 if (isset($spaces[$x])) {
313 $spaces_total = $spaces_total +
$spaces[$x];
316 $indent = $level +
$spaces_total;
317 /* must have run into a message that broke the thread
318 so we are adjusting for that portion
321 $indent = $indent +
1;
323 if (preg_match("/(\d+)/", $thread_new[$i][$k], $regs)) {
326 /* the thread must be broken if $indent == 0
327 so indent the message once and start faking it
334 /* dont need abs but if indent was negative
337 $indent_array[$child] = abs($indent);
341 return $indent_array;
346 * Returns an array with each element as a string representing one
347 * message-thread as returned by the IMAP server.
349 function get_thread_sort ($imap_stream) {
350 global $thread_new, $sort_by_ref, $default_charset, $server_sort_array;
351 if (sqsession_is_registered('thread_new')) {
352 sqsession_unregister('thread_new');
354 if (sqsession_is_registered('server_sort_array')) {
355 sqsession_unregister('server_sort_array');
357 $thread_temp = array ();
358 if ($sort_by_ref == 1) {
359 $sort_type = 'REFERENCES';
362 $sort_type = 'ORDEREDSUBJECT';
364 $query = "THREAD $sort_type ".strtoupper($default_charset)." ALL";
365 $thread_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
366 if (isset($thread_test[0])) {
367 for ($i=0,$iCnt=count($thread_test);$i<$iCnt;++
$i) {
368 if (preg_match("/^\* THREAD (.+)$/", $thread_test[$i], $regs)) {
369 $thread_list = trim($regs[1]);
377 if (!preg_match("/OK/", $response)) {
378 $server_sort_array = 'no';
379 return $server_sort_array;
381 if (isset($thread_list)) {
382 $thread_temp = preg_split("//", $thread_list, -1, PREG_SPLIT_NO_EMPTY
);
384 $char_count = count($thread_temp);
386 $thread_new = array();
389 for ($i=0;$i<$char_count;$i++
) {
390 if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
391 $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
393 elseif ($thread_temp[$i] == '(') {
394 $thread_new[$k] .= $thread_temp[$i];
397 elseif ($thread_temp[$i] == ')') {
399 $thread_new[$k] .= $thread_temp[$i];
400 $counter = $counter - 1;
403 $thread_new[$k] .= $thread_temp[$i];
405 $thread_new[$k] = "";
406 $counter = $counter - 1;
410 sqsession_register($thread_new, 'thread_new');
411 $thread_new = array_reverse($thread_new);
412 $thread_list = implode(" ", $thread_new);
413 $thread_list = str_replace("(", " ", $thread_list);
414 $thread_list = str_replace(")", " ", $thread_list);
415 $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY
);
416 $server_sort_array = $thread_list;
417 sqsession_register($server_sort_array, 'server_sort_array');
422 function elapsedTime($start) {
423 $stop = gettimeofday();
424 $timepassed = 1000000 * ($stop['sec'] - $start['sec']) +
$stop['usec'] - $start['usec'];
428 // only used in sqimap_get_small_header_list
429 function parseString($read,&$i) {
435 $iPos = strpos($read,'"',$iPos);
437 if ($iPos && $read{$iPos -1} != '\\') {
438 $s = substr($read,$i,($iPos-$i));
443 if ($iPos > strlen($read)) {
447 } else if ($char == '{') {
450 $iPos = strpos($read,'}',$i);
452 $lit_cnt = substr($read, $i, $iPos - $i);
453 $i +
= strlen($lit_cnt) +
3; /* skip } + \r + \n */
454 /* Now read the literal */
455 $s = ($lit_cnt ?
substr($read,$i,$lit_cnt): '');
457 /* temp bugfix (SM 1.5 will have a working clean version)
458 too much work to implement that version right now */
460 } else { /* should never happen */
461 $i +
= 3; /* } + \r + \n */
471 // only used in sqimap_get_small_header_list
472 function parseArray($read,&$i) {
473 $i = strpos($read,'(',$i);
474 $i_pos = strpos($read,')',$i);
475 $s = substr($read,$i+
1,$i_pos - $i -1);
476 $a = explode(' ',$s);
485 function sqimap_get_small_header_list ($imap_stream, $msg_list, $show_num=false) {
486 global $squirrelmail_language, $color, $data_dir, $username, $imap_server_type;
487 global $allow_server_sort;
488 /* Get the small headers for each message in $msg_list */
489 $maxmsg = sizeof($msg_list);
490 if ($show_num != '999999') {
491 $msgs_str = sqimap_message_list_squisher($msg_list);
496 $read_list = array();
499 * We need to return the data in the same order as the caller supplied
500 * in $msg_list, but IMAP servers are free to return responses in
501 * whatever order they wish... So we need to re-sort manually
503 for ($i = 0; $i < sizeof($msg_list); $i++
) {
504 $messages["$msg_list[$i]"] = array();
507 $internaldate = getPref($data_dir, $username, 'internal_date_sort');
509 $query = "FETCH $msgs_str (FLAGS UID RFC822.SIZE INTERNALDATE BODY.PEEK[HEADER.FIELDS (Date To Cc From Subject X-Priority Content-Type)])";
511 $query = "FETCH $msgs_str (FLAGS UID RFC822.SIZE BODY.PEEK[HEADER.FIELDS (Date To Cc From Subject X-Priority Content-Type)])";
513 $read_list = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, TRUE);
516 foreach ($read_list as $r) {
517 /* initialize/reset vars */
518 $subject = _("(no subject)");
519 $from = _("Unknown sender");
522 $type = array('','');
523 $cc = $to = $inrepto = '';
524 // use unset because we do isset below
526 $flag_seen = $flag_answered = $flag_deleted = $flag_flagged = false;
528 $read = implode('',$r);
531 * #id<space>FETCH<space>(
534 /* extract the message id */
535 $i_space = strpos($read,' ',2);
536 $id = substr($read,2,$i_space-2);
537 $fetch = substr($read,$i_space+
1,5);
538 if (!is_numeric($id) && $fetch !== 'FETCH') {
539 set_up_language($squirrelmail_language);
540 echo '<br><b><font color=$color[2]>' .
541 _("ERROR : Could not complete request.") .
543 _("Unknown response from IMAP server: ") . ' 1.' .
544 htmlspecialchars($read) . "</font><br>\n";
547 $i = strpos($read,'(',$i_space+
5);
548 $read = substr($read,$i+
1);
549 $i_len = strlen($read);
551 while ($i < $i_len && $i !== false) {
553 $read = trim(substr($read,$i));
554 $i_len = strlen($read);
555 $i = strpos($read,' ');
556 $arg = substr($read,0,$i);
561 $i_pos = strpos($read,' ',$i);
563 $i_pos = strpos($read,')',$i);
566 $unique_id = substr($read,$i,$i_pos-$i);
573 $flags = parseArray($read,$i);
574 if (!$flags) break 3;
575 foreach ($flags as $flag) {
576 $flag = strtolower($flag);
579 case '\\seen': $flag_seen = true; break;
580 case '\\answered': $flag_answered = true; break;
581 case '\\deleted': $flag_deleted = true; break;
582 case '\\flagged': $flag_flagged = true; break;
588 $i_pos = strpos($read,' ',$i);
590 $i_pos = strpos($read,')',$i);
593 $size = substr($read,$i,$i_pos-$i);
601 $date = parseString($read,$i);
602 //if ($tmpdate === false) break 3;
603 //$tmpdate = str_replace(' ',' ',$tmpdate);
604 //$tmpdate = explode(' ',$tmpdate);
605 //$date = str_replace('-',' ',$tmpdate[0]) . " " .
606 // $tmpdate[1] . ' ' . $tmpdate[2];
608 case 'BODY.PEEK[HEADER.FIELDS':
609 case 'BODY[HEADER.FIELDS':
610 $i = strpos($read,'{',$i);
611 $header = parseString($read,$i);
612 if ($header === false) break 2;
613 /* First we replace all \r\n by \n, and unfold the header */
614 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
615 /* Now we can make a new header array with */
616 /* each element representing a headerline */
617 $hdr = explode("\n" , $hdr);
618 foreach ($hdr as $line) {
619 $pos = strpos($line, ':');
621 $field = strtolower(substr($line, 0, $pos));
622 if (!strstr($field,' ')) { /* valid field */
623 $value = trim(substr($line, $pos+
1));
626 case 'to': $to = $value; break;
627 case 'cc': $cc = $value; break;
628 case 'from': $from = $value; break;
629 case 'date': $date = $value; break;
630 case 'x-priority': $priority = $value; break;
633 if ($subject == "") {
634 $subject = _("(no subject)");
639 if ($pos = strpos($type, ";")) {
640 $type = substr($type, 0, $pos);
642 $type = explode("/", $type);
643 if(!is_array($type)) {
659 $date = str_replace(' ', ' ', $date);
660 $tmpdate = explode(' ', trim($date));
662 $tmpdate = $date = array();
665 $messages[$msgi]['ID'] = $unique_id;
666 $messages[$msgi]['TIME_STAMP'] = getTimeStamp($tmpdate);
667 $messages[$msgi]['DATE_STRING'] = getDateString($messages[$msgi]['TIME_STAMP']);
668 $messages[$msgi]['FROM'] = $from; //parseAddress($from);
669 $messages[$msgi]['SUBJECT'] = $subject;
670 // if (handleAsSent($mailbox)) {
671 $messages[$msgi]['TO'] = $to; //parseAddress($to);
673 $messages[$msgi]['PRIORITY'] = $priority;
674 $messages[$msgi]['CC'] = $cc; //parseAddress($cc);
675 $messages[$msgi]['SIZE'] = $size;
676 $messages[$msgi]['TYPE0'] = $type[0];
677 $messages[$msgi]['FLAG_DELETED'] = $flag_deleted;
678 $messages[$msgi]['FLAG_ANSWERED'] = $flag_answered;
679 $messages[$msgi]['FLAG_SEEN'] = $flag_seen;
680 $messages[$msgi]['FLAG_FLAGGED'] = $flag_flagged;
682 /* non server sort stuff */
683 if (!$allow_server_sort) {
684 $from = parseAddress($from);
686 $from = decodeHeader($from[0][1]);
690 $messages[$msgi]['FROM-SORT'] = $from;
691 $subject_sort = strtolower(decodeHeader($subject));
692 if (preg_match("/^(vedr|sv|re|aw):\s*(.*)$/si", $subject_sort, $matches)){
693 $messages[$msgi]['SUBJECT-SORT'] = $matches[2];
695 $messages[$msgi]['SUBJECT-SORT'] = $subject_sort;
700 array_reverse($messages);
701 $new_messages = array();
702 foreach ($messages as $i =>$message) {
703 $new_messages[] = $message;
705 return $new_messages;
709 * Returns a message array with all the information about a message.
710 * See the documentation folder for more information about this array.
712 function sqimap_get_message ($imap_stream, $id, $mailbox) {
715 $read = sqimap_run_command ($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
717 if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
718 if (trim($regs[1])) {
719 $flags = preg_split('/ /', $regs[1],-1,'PREG_SPLIT_NI_EMPTY');
723 /* the message was not found, maybe the mailbox was modified? */
724 global $sort, $startMessage, $color;
726 $errmessage = _("The server couldn't find the message you requested.") .
727 '<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).");
728 /* this will include a link back to the message list */
729 error_message($errmessage, $mailbox, $sort, $startMessage, $color);
732 $bodystructure = implode('',$read);
733 $msg = mime_structure($bodystructure,$flags);
734 $read = sqimap_run_command ($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
735 $rfc822_header = new Rfc822Header();
736 $rfc822_header->parseHeader($read);
737 $msg->rfc822_header
= $rfc822_header;