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
18 * Copies specified messages to specified folder
19 * @param int $imap_stream The resource ID for the IMAP connection
20 * @param string $start Beginning of range to copy
21 * @param string $end End of the range to copy
22 * @param string $mailbox Which box to copy to
23 * @deprecated This function is obsolete and should not be used
25 function sqimap_messages_copy ($imap_stream, $start, $end, $mailbox) {
26 $read = sqimap_run_command ($imap_stream, "COPY $start:$end " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
30 * copy a range of messages ($id) to another mailbox ($mailbox)
31 * @param int $imap_stream The resource ID for the IMAP socket
32 * @param string $id The list of messages to copy
33 * @param string $mailbox The destination to copy to
36 function sqimap_msgs_list_copy ($imap_stream, $id, $mailbox) {
37 $msgs_id = sqimap_message_list_squisher($id);
38 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
42 * move a range of messages ($id) to another mailbox. Deletes the originals.
43 * @param int $imap_stream The resource ID for the IMAP socket
44 * @param string $id The list of messages to move
45 * @param string $mailbox The destination to move to
48 function sqimap_msgs_list_move ($imap_stream, $id, $mailbox) {
49 $msgs_id = sqimap_message_list_squisher($id);
50 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
51 $read = sqimap_run_command ($imap_stream, "STORE $msgs_id +FLAGS (\\Deleted)", true, $response,$message, TRUE);
56 * Deletes specified messages and moves them to trash if possible
57 * @deprecated This function is obsolete and should no longer be used
58 * @param int $imap_steam The resource ID for the IMAP connection
59 * @param string $start Start of range
60 * @param string $end End of range
61 * @param string $mailbox Mailbox messages are being deleted from
64 function sqimap_messages_delete ($imap_stream, $start, $end, $mailbox, $bypass_trash=false) {
65 global $move_to_trash, $trash_folder, $auto_expunge;
67 if (($move_to_trash == true) && ($bypass_trash != true) &&
68 (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder))) {
69 sqimap_messages_copy ($imap_stream, $start, $end, $trash_folder);
71 sqimap_messages_flag ($imap_stream, $start, $end, "Deleted", true);
74 function sqimap_msgs_list_delete ($imap_stream, $mailbox, $id, $bypass_trash=false) {
75 global $move_to_trash, $trash_folder;
76 $msgs_id = sqimap_message_list_squisher($id);
77 if (($move_to_trash == true) && ($bypass_trash != true) &&
78 (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder)) ) {
79 $read = sqimap_run_command ($imap_stream, "COPY $msgs_id " . sqimap_encode_mailbox_name($trash_folder), true, $response, $message, TRUE);
81 $read = sqimap_run_command ($imap_stream, "STORE $msgs_id +FLAGS (\\Deleted)", true, $response, $message, TRUE);
86 * Sets the specified messages with specified flag
88 function sqimap_messages_flag ($imap_stream, $start, $end, $flag, $handle_errors) {
89 $read = sqimap_run_command ($imap_stream, "STORE $start:$end +FLAGS (\\$flag)", $handle_errors, $response, $message, TRUE);
92 function sqimap_toggle_flag($imap_stream, $id, $flag, $set, $handle_errors) {
93 $msgs_id = sqimap_message_list_squisher($id);
94 $set_string = ($set ?
'+' : '-');
95 $read = sqimap_run_command ($imap_stream, "STORE $msgs_id ".$set_string."FLAGS ($flag)", $handle_errors, $response, $message, TRUE);
99 function sqimap_get_small_header ($imap_stream, $id, $sent) {
100 $res = sqimap_get_small_header_list($imap_stream, $id, $sent);
105 * Sort the message list and crunch to be as small as possible
106 * (overflow could happen, so make it small if possible)
108 function sqimap_message_list_squisher($messages_array) {
109 if( !is_array( $messages_array ) ) {
110 return $messages_array;
113 sort($messages_array, SORT_NUMERIC
);
115 while ($messages_array) {
116 $start = array_shift($messages_array);
118 while (isset($messages_array[0]) && $messages_array[0] == $end +
1) {
119 $end = array_shift($messages_array);
121 if ($msgs_str != '') {
125 if ($start != $end) {
126 $msgs_str .= ':' . $end;
133 * Get sort order from server and return it as the $id array for mailbox_display.
135 function sqimap_get_sort_order ($imap_stream, $sort, $mbxresponse) {
136 global $default_charset, $thread_sort_messages,
137 $internal_date_sort, $server_sort_array,
138 $sent_folder, $mailbox;
140 if (sqsession_is_registered('server_sort_array')) {
141 sqsession_unregister('server_sort_array');
146 $server_sort_array = array();
147 $sort_test = array();
151 if (isset($mbxresponse['UIDNEXT']) && $mbxresponse['UIDNEXT']) {
152 $uidnext = $mbxresponse['UIDNEXT']-1;
156 $query = "SEARCH UID 1:$uidnext";
157 $uids = sqimap_run_command ($imap_stream, $query, true, $response, $message, true);
158 if (isset($uids[0])) {
159 if (preg_match("/^\* SEARCH (.+)$/", $uids[0], $regs)) {
160 $server_sort_array = preg_split("/ /", trim($regs[1]));
163 if (!preg_match("/OK/", $response)) {
164 $server_sort_array = 'no';
166 $server_sort_array = array_reverse($server_sort_array);
167 sqsession_register($server_sort_array, 'server_sort_array');
168 return $server_sort_array;
171 $sort_on = array (0=> 'DATE',
177 if ($internal_date_sort == true) {
178 $sort_on[0] = 'ARRIVAL';
179 $sort_on[1] = 'ARRIVAL';
181 if ($sent_folder == $mailbox) {
185 if (!empty($sort_on[$sort])) {
186 $query = "SORT ($sort_on[$sort]) ".strtoupper($default_charset).' ALL';
187 $sort_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
189 if (isset($sort_test[0])) {
190 for ($i=0,$iCnt=count($sort_test);$i<$iCnt;++
$i) {
191 if (preg_match("/^\* SORT (.+)$/", $sort_test[$i], $regs)) {
192 $server_sort_array = preg_split("/ /", trim($regs[1]));
197 if ($sort == 0 ||
$sort == 2 ||
$sort == 4) {
198 $server_sort_array = array_reverse($server_sort_array);
200 if (!preg_match("/OK/", $response)) {
201 $server_sort_array = 'no';
203 sqsession_register($server_sort_array, 'server_sort_array');
204 return $server_sort_array;
208 * Get sort order from server if server does not have the SORT extension
209 * and return it as array for mailbox_display.
211 * @param resource $imap_stream
212 * @param array $mbxresponse response from a sqimap_mailbox_select
213 * @return array $php_sort_array
215 function sqimap_get_php_sort_order ($imap_stream, $mbxresponse) {
217 if (sqsession_is_registered('php_sort_array')) {
218 sqsession_unregister('php_sort_array');
221 $php_sort_array = array();
223 if (isset($mbxresponse['UIDNEXT']) && $mbxresponse['UIDNEXT']) {
224 $uidnext = $mbxresponse['UIDNEXT']-1;
228 $query = "SEARCH UID 1:$uidnext";
229 $uids = sqimap_run_command ($imap_stream, $query, true, $response, $message, true);
230 if (isset($uids[0])) {
231 $php_sort_array = array();
232 // EIMS workaround. EIMS returns the result as multiple untagged SEARCH responses
233 foreach($uids as $line) {
234 if (preg_match("/^\* SEARCH (.+)$/", $line, $regs)) {
235 $php_sort_array +
= preg_split("/ /", trim($regs[1]));
239 if (!preg_match("/OK/", $response)) {
240 $php_sort_array = 'no';
242 sqsession_register($php_sort_array, 'php_sort_array');
243 return $php_sort_array;
248 * Returns an indent array for printMessageinfo()
249 * This represents the amount of indent needed (value),
250 * for this message number (key)
252 function get_parent_level ($imap_stream) {
253 global $sort_by_ref, $default_charset, $thread_new;
258 /* loop through the threads and take unwanted characters out
259 of the thread string then chop it up
261 for ($i=0;$i<count($thread_new);$i++
) {
262 $thread_new[$i] = preg_replace("/\s\(/", "(", $thread_new[$i]);
263 $thread_new[$i] = preg_replace("/(\d+)/", "$1|", $thread_new[$i]);
264 $thread_new[$i] = preg_split("/\|/", $thread_new[$i], -1, PREG_SPLIT_NO_EMPTY
);
266 $indent_array = array();
268 $thread_new = array();
270 /* looping through the parts of one message thread */
272 for ($i=0;$i<count($thread_new);$i++
) {
273 /* first grab the parent, it does not indent */
275 if (isset($thread_new[$i][0])) {
276 if (preg_match("/(\d+)/", $thread_new[$i][0], $regs)) {
280 $indent_array[$parent] = 0;
282 /* now the children, checking each thread portion for
283 ),(, and space, adjusting the level and space values
284 to get the indent level
291 for ($k=1;$k<(count($thread_new[$i]))-1;$k++
) {
292 $chars = count_chars($thread_new[$i][$k], 1);
293 if (isset($chars['40'])) { /* testing for ( */
294 $level = $level +
$chars['40'];
296 if (isset($chars['41'])) { /* testing for ) */
297 $level = $level - $chars['41'];
299 /* if we were faking lets stop, this portion
300 of the thread is over
302 if ($level == $cutoff) {
306 if (isset($chars['32'])) { /* testing for space */
307 if (!isset($spaces[$level])) {
310 $spaces[$level] = $spaces[$level] +
$chars['32'];
312 for ($x=0;$x<=$level;$x++
) {
313 if (isset($spaces[$x])) {
314 $spaces_total = $spaces_total +
$spaces[$x];
317 $indent = $level +
$spaces_total;
318 /* must have run into a message that broke the thread
319 so we are adjusting for that portion
322 $indent = $indent +
1;
324 if (preg_match("/(\d+)/", $thread_new[$i][$k], $regs)) {
327 /* the thread must be broken if $indent == 0
328 so indent the message once and start faking it
335 /* dont need abs but if indent was negative
338 $indent_array[$child] = abs($indent);
342 return $indent_array;
347 * Returns an array with each element as a string representing one
348 * message-thread as returned by the IMAP server.
350 function get_thread_sort ($imap_stream) {
351 global $thread_new, $sort_by_ref, $default_charset, $server_sort_array;
352 if (sqsession_is_registered('thread_new')) {
353 sqsession_unregister('thread_new');
355 if (sqsession_is_registered('server_sort_array')) {
356 sqsession_unregister('server_sort_array');
358 $thread_temp = array ();
359 if ($sort_by_ref == 1) {
360 $sort_type = 'REFERENCES';
363 $sort_type = 'ORDEREDSUBJECT';
365 $query = "THREAD $sort_type ".strtoupper($default_charset)." ALL";
366 $thread_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
367 if (isset($thread_test[0])) {
368 for ($i=0,$iCnt=count($thread_test);$i<$iCnt;++
$i) {
369 if (preg_match("/^\* THREAD (.+)$/", $thread_test[$i], $regs)) {
370 $thread_list = trim($regs[1]);
378 if (!preg_match("/OK/", $response)) {
379 $server_sort_array = 'no';
380 return $server_sort_array;
382 if (isset($thread_list)) {
383 $thread_temp = preg_split("//", $thread_list, -1, PREG_SPLIT_NO_EMPTY
);
385 $char_count = count($thread_temp);
387 $thread_new = array();
390 for ($i=0;$i<$char_count;$i++
) {
391 if ($thread_temp[$i] != ')' && $thread_temp[$i] != '(') {
392 $thread_new[$k] = $thread_new[$k] . $thread_temp[$i];
394 elseif ($thread_temp[$i] == '(') {
395 $thread_new[$k] .= $thread_temp[$i];
398 elseif ($thread_temp[$i] == ')') {
400 $thread_new[$k] .= $thread_temp[$i];
401 $counter = $counter - 1;
404 $thread_new[$k] .= $thread_temp[$i];
406 $thread_new[$k] = "";
407 $counter = $counter - 1;
411 sqsession_register($thread_new, 'thread_new');
412 $thread_new = array_reverse($thread_new);
413 $thread_list = implode(" ", $thread_new);
414 $thread_list = str_replace("(", " ", $thread_list);
415 $thread_list = str_replace(")", " ", $thread_list);
416 $thread_list = preg_split("/\s/", $thread_list, -1, PREG_SPLIT_NO_EMPTY
);
417 $server_sort_array = $thread_list;
418 sqsession_register($server_sort_array, 'server_sort_array');
423 function elapsedTime($start) {
424 $stop = gettimeofday();
425 $timepassed = 1000000 * ($stop['sec'] - $start['sec']) +
$stop['usec'] - $start['usec'];
429 // only used in sqimap_get_small_header_list
430 function parseString($read,&$i) {
436 $iPos = strpos($read,'"',$iPos);
438 if ($iPos && $read{$iPos -1} != '\\') {
439 $s = substr($read,$i,($iPos-$i));
444 if ($iPos > strlen($read)) {
448 } else if ($char == '{') {
451 $iPos = strpos($read,'}',$i);
453 $lit_cnt = substr($read, $i, $iPos - $i);
454 $i +
= strlen($lit_cnt) +
3; /* skip } + \r + \n */
455 /* Now read the literal */
456 $s = ($lit_cnt ?
substr($read,$i,$lit_cnt): '');
458 /* temp bugfix (SM 1.5 will have a working clean version)
459 too much work to implement that version right now */
461 } else { /* should never happen */
462 $i +
= 3; /* } + \r + \n */
472 // only used in sqimap_get_small_header_list
473 function parseArray($read,&$i) {
474 $i = strpos($read,'(',$i);
475 $i_pos = strpos($read,')',$i);
476 $s = substr($read,$i+
1,$i_pos - $i -1);
477 $a = explode(' ',$s);
486 function sqimap_get_small_header_list ($imap_stream, $msg_list, $show_num=false) {
487 global $squirrelmail_language, $color, $data_dir, $username, $imap_server_type;
488 global $allow_server_sort;
489 /* Get the small headers for each message in $msg_list */
490 $maxmsg = sizeof($msg_list);
491 if ($show_num != '999999') {
492 $msgs_str = sqimap_message_list_squisher($msg_list);
497 $read_list = array();
500 * We need to return the data in the same order as the caller supplied
501 * in $msg_list, but IMAP servers are free to return responses in
502 * whatever order they wish... So we need to re-sort manually
504 for ($i = 0; $i < sizeof($msg_list); $i++
) {
505 $messages["$msg_list[$i]"] = array();
508 $internaldate = getPref($data_dir, $username, 'internal_date_sort');
510 $query = "FETCH $msgs_str (FLAGS UID RFC822.SIZE INTERNALDATE BODY.PEEK[HEADER.FIELDS (Date To Cc From Subject X-Priority Content-Type)])";
512 $query = "FETCH $msgs_str (FLAGS UID RFC822.SIZE BODY.PEEK[HEADER.FIELDS (Date To Cc From Subject X-Priority Content-Type)])";
514 $read_list = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, TRUE);
517 foreach ($read_list as $r) {
518 /* initialize/reset vars */
519 $subject = _("(no subject)");
520 $from = _("Unknown sender");
523 $type = array('','');
524 $cc = $to = $inrepto = '';
525 // use unset because we do isset below
527 $flag_seen = $flag_answered = $flag_deleted = $flag_flagged = false;
529 $read = implode('',$r);
532 * #id<space>FETCH<space>(
535 /* extract the message id */
536 $i_space = strpos($read,' ',2);
537 $id = substr($read,2,$i_space-2);
538 $fetch = substr($read,$i_space+
1,5);
539 if (!is_numeric($id) && $fetch !== 'FETCH') {
540 set_up_language($squirrelmail_language);
541 echo '<br><b><font color=$color[2]>' .
542 _("ERROR : Could not complete request.") .
544 _("Unknown response from IMAP server: ") . ' 1.' .
545 htmlspecialchars($read) . "</font><br>\n";
548 $i = strpos($read,'(',$i_space+
5);
549 $read = substr($read,$i+
1);
550 $i_len = strlen($read);
552 while ($i < $i_len && $i !== false) {
554 $read = trim(substr($read,$i));
555 $i_len = strlen($read);
556 $i = strpos($read,' ');
557 $arg = substr($read,0,$i);
562 $i_pos = strpos($read,' ',$i);
564 $i_pos = strpos($read,')',$i);
567 $unique_id = substr($read,$i,$i_pos-$i);
574 $flags = parseArray($read,$i);
575 if (!$flags) break 3;
576 foreach ($flags as $flag) {
577 $flag = strtolower($flag);
580 case '\\seen': $flag_seen = true; break;
581 case '\\answered': $flag_answered = true; break;
582 case '\\deleted': $flag_deleted = true; break;
583 case '\\flagged': $flag_flagged = true; break;
589 $i_pos = strpos($read,' ',$i);
591 $i_pos = strpos($read,')',$i);
594 $size = substr($read,$i,$i_pos-$i);
602 $date = parseString($read,$i);
603 //if ($tmpdate === false) break 3;
604 //$tmpdate = str_replace(' ',' ',$tmpdate);
605 //$tmpdate = explode(' ',$tmpdate);
606 //$date = str_replace('-',' ',$tmpdate[0]) . " " .
607 // $tmpdate[1] . ' ' . $tmpdate[2];
609 case 'BODY.PEEK[HEADER.FIELDS':
610 case 'BODY[HEADER.FIELDS':
611 $i = strpos($read,'{',$i);
612 $header = parseString($read,$i);
613 if ($header === false) break 2;
614 /* First we replace all \r\n by \n, and unfold the header */
615 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
616 /* Now we can make a new header array with */
617 /* each element representing a headerline */
618 $hdr = explode("\n" , $hdr);
619 foreach ($hdr as $line) {
620 $pos = strpos($line, ':');
622 $field = strtolower(substr($line, 0, $pos));
623 if (!strstr($field,' ')) { /* valid field */
624 $value = trim(substr($line, $pos+
1));
627 case 'to': $to = $value; break;
628 case 'cc': $cc = $value; break;
629 case 'from': $from = $value; break;
630 case 'date': $date = $value; break;
631 case 'x-priority': $priority = $value; break;
634 if ($subject == "") {
635 $subject = _("(no subject)");
640 if ($pos = strpos($type, ";")) {
641 $type = substr($type, 0, $pos);
643 $type = explode("/", $type);
644 if(!is_array($type)) {
660 $date = str_replace(' ', ' ', $date);
661 $tmpdate = explode(' ', trim($date));
663 $tmpdate = $date = array();
666 $messages[$msgi]['ID'] = $unique_id;
667 $messages[$msgi]['TIME_STAMP'] = getTimeStamp($tmpdate);
668 $messages[$msgi]['DATE_STRING'] = getDateString($messages[$msgi]['TIME_STAMP']);
669 $messages[$msgi]['FROM'] = $from; //parseAddress($from);
670 $messages[$msgi]['SUBJECT'] = $subject;
671 // if (handleAsSent($mailbox)) {
672 $messages[$msgi]['TO'] = $to; //parseAddress($to);
674 $messages[$msgi]['PRIORITY'] = $priority;
675 $messages[$msgi]['CC'] = $cc; //parseAddress($cc);
676 $messages[$msgi]['SIZE'] = $size;
677 $messages[$msgi]['TYPE0'] = $type[0];
678 $messages[$msgi]['FLAG_DELETED'] = $flag_deleted;
679 $messages[$msgi]['FLAG_ANSWERED'] = $flag_answered;
680 $messages[$msgi]['FLAG_SEEN'] = $flag_seen;
681 $messages[$msgi]['FLAG_FLAGGED'] = $flag_flagged;
683 /* non server sort stuff */
684 if (!$allow_server_sort) {
685 $from = parseAddress($from);
687 $from = decodeHeader($from[0][1]);
691 $messages[$msgi]['FROM-SORT'] = $from;
692 $subject_sort = strtolower(decodeHeader($subject));
693 if (preg_match("/^(vedr|sv|re|aw):\s*(.*)$/si", $subject_sort, $matches)){
694 $messages[$msgi]['SUBJECT-SORT'] = $matches[2];
696 $messages[$msgi]['SUBJECT-SORT'] = $subject_sort;
701 array_reverse($messages);
702 $new_messages = array();
703 foreach ($messages as $i =>$message) {
704 $new_messages[] = $message;
706 return $new_messages;
710 * Returns a message array with all the information about a message.
711 * See the documentation folder for more information about this array.
713 function sqimap_get_message ($imap_stream, $id, $mailbox) {
716 $read = sqimap_run_command ($imap_stream, "FETCH $id (FLAGS BODYSTRUCTURE)", true, $response, $message, TRUE);
718 if (preg_match('/.+FLAGS\s\((.*)\)\s/AUi',$read[0],$regs)) {
719 if (trim($regs[1])) {
720 $flags = preg_split('/ /', $regs[1],-1,'PREG_SPLIT_NI_EMPTY');
724 /* the message was not found, maybe the mailbox was modified? */
725 global $sort, $startMessage, $color;
727 $errmessage = _("The server couldn't find the message you requested.") .
728 '<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).");
729 /* this will include a link back to the message list */
730 error_message($errmessage, $mailbox, $sort, $startMessage, $color);
733 $bodystructure = implode('',$read);
734 $msg = mime_structure($bodystructure,$flags);
735 $read = sqimap_run_command ($imap_stream, "FETCH $id BODY[HEADER]", true, $response, $message, TRUE);
736 $rfc822_header = new Rfc822Header();
737 $rfc822_header->parseHeader($read);
738 $msg->rfc822_header
= $rfc822_header;