Better error reporting
[squirrelmail.git] / functions / imap_messages.php
index 740a6b1dd906f76c2c07516a407c796f0839d4ad..05fc99d74f3e0278c1d24ba526569d6649cafd89 100755 (executable)
@@ -3,12 +3,11 @@
 /**
  * imap_messages.php
  *
- * Copyright (c) 1999-2005 The SquirrelMail Project Team
- * Licensed under the GNU GPL. For full terms see the file COPYING.
- *
  * This implements functions that manipulate messages
  * NOTE: Quite a few functions in this file are obsolete
  *
+ * @copyright © 1999-2006 The SquirrelMail Project Team
+ * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  * @version $Id$
  * @package squirrelmail
  * @subpackage imap
@@ -21,7 +20,7 @@
  * @param string $id The list of messages to copy
  * @param string $mailbox The destination to copy to
  * @param bool $handle_errors Show error messages in case of a NO, BAD or BYE response
- * @return bool If the copy completed without errors  
+ * @return bool If the copy completed without errors
  */
 function sqimap_msgs_list_copy($imap_stream, $id, $mailbox, $handle_errors = true) {
     $msgs_id = sqimap_message_list_squisher($id);
@@ -40,9 +39,14 @@ function sqimap_msgs_list_copy($imap_stream, $id, $mailbox, $handle_errors = tru
  * @param string $id The list of messages to move
  * @param string $mailbox The destination to move to
  * @param bool $handle_errors Show error messages in case of a NO, BAD or BYE response
+ * @param string $source_mailbox (since 1.5.1) name of source mailbox. It is used to
+ *  validate that target mailbox != source mailbox.
  * @return bool If the move completed without errors
  */
-function sqimap_msgs_list_move($imap_stream, $id, $mailbox, $handle_errors = true) {
+function sqimap_msgs_list_move($imap_stream, $id, $mailbox, $handle_errors = true, $source_mailbox = false) {
+    if ($source_mailbox!==false && $source_mailbox==$mailbox) {
+        return false;
+    }
     $msgs_id = sqimap_message_list_squisher($id);
     if (sqimap_msgs_list_copy ($imap_stream, $id, $mailbox, $handle_errors)) {
         return sqimap_toggle_flag($imap_stream, $id, '\\Deleted', true, true);
@@ -90,9 +94,25 @@ function sqimap_msgs_list_delete($imap_stream, $mailbox, $id, $bypass_trash=fals
 function sqimap_toggle_flag($imap_stream, $id, $flag, $set, $handle_errors) {
     $msgs_id = sqimap_message_list_squisher($id);
     $set_string = ($set ? '+' : '-');
+
+    for ($i=0; $i<sizeof($id); $i++) {
+        $aMessageList["$id[$i]"] = array();
+    }
+
     $aResponse = sqimap_run_command_list($imap_stream, "STORE $msgs_id ".$set_string."FLAGS ($flag)", $handle_errors, $response, $message, TRUE);
+
     // parse the fetch response
-    return parseFetch($aResponse);
+    $parseFetchResults=parseFetch($aResponse,$aMessageList);
+
+    // some broken IMAP servers do not return UID elements on UID STORE
+    // if this is the case, then we need to do a UID FETCH
+    $testkey=$id[0];
+    if (!isset($parseFetchResults[$testkey]['UID'])) {
+        $aResponse = sqimap_run_command_list($imap_stream, "FETCH $msgs_id (FLAGS)", $handle_errors, $response, $message, TRUE);
+        $parseFetchResults = parseFetch($aResponse,$aMessageList);
+    }
+
+    return ($parseFetchResults);
 }
 
 
@@ -142,11 +162,20 @@ function sqimap_get_sort_order($imap_stream, $sSortField, $reverse, $search='ALL
         }
         $query = "SORT ($sSortField) ".strtoupper($default_charset)." $search";
         // FIX ME sqimap_run_command should return the parsed data accessible by $aDATA['SORT']
-        $aData = sqimap_run_command ($imap_stream, $query, false, $response, $message, TRUE);
+        // use sqimap_run_command_list in case of unsollicited responses. If we don't we could loose the SORT response
+        $aData = sqimap_run_command_list ($imap_stream, $query, false, $response, $message, TRUE);
         /* fallback to default charset */
-        if ($response == 'NO' && strpos($message,'[BADCHARSET]') !== false) {
-            $query = "SORT ($sSortField) US-ASCII $search";
-            $aData = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
+        if ($response == 'NO') {
+            if (strpos($message,'[BADCHARSET]') !== false ||
+                strpos($message,'Unrecognized character set') !== false) {
+                sqm_trigger_imap_error('SQM_IMAP_BADCHARSET',$query, $response, $message);
+                $query = "SORT ($sSortField) US-ASCII $search";
+                $aData = sqimap_run_command_list ($imap_stream, $query, true, $response, $message, TRUE);
+            } else {
+                sqm_trigger_imap_error('SQM_IMAP_ERROR',$query, $response, $message);
+            }
+        } else if ($response == 'BAD') {
+            sqm_trigger_imap_error('SQM_IMAP_NO_SORT',$query, $response, $message);
         }
     }
 
@@ -160,7 +189,7 @@ function sqimap_get_sort_order($imap_stream, $sSortField, $reverse, $search='ALL
 
 /**
  * Parses a UID list returned on a SORT or SEARCH request
- * @param array $aData imap response
+ * @param array $aData imap response (retrieved from sqimap_run_command_list)
  * @param string $sCommand issued imap command (SEARCH or SORT)
  * @return array $aUid uid list
  */
@@ -168,8 +197,10 @@ function parseUidList($aData,$sCommand) {
     $aUid = array();
     if (isset($aData) && count($aData)) {
         for ($i=0,$iCnt=count($aData);$i<$iCnt;++$i) {
-            if (preg_match("/^\* $sCommand (.+)$/", $aData[$i], $aMatch)) {
-                $aUid += preg_split("/ /", trim($aMatch[1]));
+            for ($j=0,$jCnt=count($aData[$i]);$j<$jCnt;++$j) {
+                if (preg_match("/^\* $sCommand (.+)$/", $aData[$i][$j], $aMatch)) {
+                    $aUid += preg_split("/ /", trim($aMatch[1]));
+                }
             }
         }
     }
@@ -404,11 +435,21 @@ function get_thread_sort($imap_stream, $search='ALL') {
     }
     $query = "THREAD $sort_type ".strtoupper($default_charset)." $search";
 
+    // TODO use sqimap_run_command_list as we do in get_server_sort()
     $thread_test = sqimap_run_command ($imap_stream, $query, false, $response, $message, TRUE);
     /* fallback to default charset */
-    if ($response == 'NO' && strpos($message,'[BADCHARSET]') !== false) {
-        $query = "THREAD $sort_type US-ASCII $search";
-        $thread_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
+
+    if ($response == 'NO') {
+        if (strpos($message,'[BADCHARSET]') !== false ||
+            strpos($message,'Unrecognized character set') !== false) {
+            sqm_trigger_imap_error('SQM_IMAP_BADCHARSET',$query, $response, $message);
+            $query = "THREAD $sort_type US-ASCII $search";
+            $thread_test = sqimap_run_command ($imap_stream, $query, true, $response, $message, TRUE);
+        } else {
+            sqm_trigger_imap_error('SQM_IMAP_ERROR',$query, $response, $message);
+        }
+    } elseif ($response == 'BAD') {
+        sqm_trigger_imap_error('SQM_IMAP_NO_THREAD',$query, $response, $message);
     }
     if (isset($thread_test[0])) {
         for ($i=0,$iCnt=count($thread_test);$i<$iCnt;++$i) {
@@ -421,7 +462,7 @@ function get_thread_sort($imap_stream, $search='ALL') {
         $thread_list = "";
     }
     if (!preg_match("/OK/", $response)) {
-        $server_sort_array = 'no';
+        $server_sort_array = false;
         return $server_sort_array;
     }
     if (isset($thread_list)) {
@@ -489,12 +530,14 @@ function elapsedTime($start) {
  * X-MS-Mail-Priority is not parsed because it always coincides
  * with one of the other headers.
  *
- * DUPLICATE CODE ALERT:
+ * FIXME: DUPLICATE CODE ALERT:
  * NOTE: this is actually a duplicate from the function in
  * class/mime/Rfc822Header.php.
+ * @todo obsolate function or use it instead of code block in parseFetch()
  */
-function parsePriority($value) {
-    $value = strtolower(array_shift(split('/\w/',trim($value))));
+function parsePriority($sValue) {
+    $aValue = split('/\w/',trim($sValue));
+    $value = strtolower(array_shift($aValue));
     if ( is_numeric($value) ) {
         return $value;
     }
@@ -581,7 +624,7 @@ function parseArray($read,&$i) {
 /**
  * Retrieves a list with headers, flags, size or internaldate from the imap server
  *
- * WARNING: function is not portable between SquirrelMail 1.2.x, 1.4.x and 1.5.x. 
+ * WARNING: function is not portable between SquirrelMail 1.2.x, 1.4.x and 1.5.x.
  * Output format, third argument and $msg_list array format requirements differ.
  * @param stream $imap_stream imap connection
  * @param array  $msg_list array with id's to create a msgs set from
@@ -591,11 +634,19 @@ function parseArray($read,&$i) {
  * @since 1.1.3
  */
 function sqimap_get_small_header_list($imap_stream, $msg_list,
-    $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Importance', 'Priority', 'Content-Type'),
+    $aHeaderFields = array('Date', 'To', 'Cc', 'From', 'Subject', 'X-Priority', 'Content-Type'),
     $aFetchItems = array('FLAGS', 'RFC822.SIZE', 'INTERNALDATE')) {
 
     $aMessageList = array();
 
+    /**
+     * Catch other priority headers as well
+     */
+    if (in_array('X-Priority',$aHeaderFields,true)) {
+        $aHeaderFields[] = 'Importance';
+        $aHeaderFields[] = 'Priority';
+    }
+
     $bUidFetch = ! in_array('UID', $aFetchItems, true);
 
     /* Get the small headers for each message in $msg_list */
@@ -645,22 +696,23 @@ function sqimap_get_small_header_list($imap_stream, $msg_list,
  * @author Marc Groot Koerkamp
  */
 function parseFetch($aResponse,$aMessageList = array()) {
-    foreach ($aResponse as $r) {
-        $msg = array();
-        // use unset because we do isset below
-        $read = implode('',$r);
+    for ($j=0,$iCnt=count($aResponse);$j<$iCnt;++$j) {
+        $aMsg = array();
 
+        $read = implode('',$aResponse[$j]);
+        // free up memmory
+        unset($aResponse[$j]); /* unset does not reindex the array. the for loop is safe */
         /*
-         * #id<space>FETCH<space>(
-         */
+            * #id<space>FETCH<space>(
+        */
 
         /* extract the message id */
-        $i_space = strpos($read,' ',2);
-        $id = substr($read,2,$i_space-2);
-        $msg['ID'] = $id;
+        $i_space = strpos($read,' ',2);/* position 2ed <space> */
+        $id = substr($read,2/* skip "*<space>" */,$i_space -2);
+        $aMsg['ID'] = $id;
         $fetch = substr($read,$i_space+1,5);
         if (!is_numeric($id) && $fetch !== 'FETCH') {
-            $msg['ERROR'] = $read; // htmlspecialchars should be done just before display. this is backend code
+            $aMsg['ERROR'] = $read; // htmlspecialchars should be done just before display. this is backend code
             break;
         }
         $i = strpos($read,'(',$i_space+5);
@@ -674,6 +726,9 @@ function parseFetch($aResponse,$aMessageList = array()) {
             $i = strpos($read,' ');
             $arg = substr($read,0,$i);
             ++$i;
+            /*
+             * use allcaps for imap items and lowcaps for headers as key for the $aMsg array
+             */
             switch ($arg)
             {
             case 'UID':
@@ -696,7 +751,7 @@ function parseFetch($aResponse,$aMessageList = array()) {
                     $flag = strtolower($flag);
                     $aFlags[$flag] = true;
                 }
-                $msg['FLAGS'] = $aFlags;
+                $aMsg['FLAGS'] = $aFlags;
                 break;
             case 'RFC822.SIZE':
                 $i_pos = strpos($read,' ',$i);
@@ -704,93 +759,99 @@ function parseFetch($aResponse,$aMessageList = array()) {
                     $i_pos = strpos($read,')',$i);
                 }
                 if ($i_pos) {
-                    $msg['SIZE'] = substr($read,$i,$i_pos-$i);
+                    $aMsg['SIZE'] = substr($read,$i,$i_pos-$i);
                     $i = $i_pos+1;
                 } else {
                     break 3;
                 }
-
                 break;
             case 'ENVELOPE':
-                break; // to be implemented, moving imap code out of the nessages class
-                sqimap_parse_address($read,$i,$msg);
-                break; // to be implemented, moving imap code out of the nessages class
+                // sqimap_parse_address($read,$i,$aMsg);
+                break; // to be implemented, moving imap code out of the Message class
             case 'BODYSTRUCTURE':
-                break;
+                break; // to be implemented, moving imap code out of the Message class
             case 'INTERNALDATE':
-                $msg['INTERNALDATE'] = trim(str_replace('  ', ' ',parseString($read,$i)));
+                $aMsg['INTERNALDATE'] = trim(str_replace('  ', ' ',parseString($read,$i)));
                 break;
             case 'BODY.PEEK[HEADER.FIELDS':
             case 'BODY[HEADER.FIELDS':
-                $i = strpos($read,'{',$i);
+                $i = strpos($read,'{',$i); // header is always returned as literal because it contain \n characters
                 $header = parseString($read,$i);
                 if ($header === false) break 2;
                 /* First we replace all \r\n by \n, and unfold the header */
                 $hdr = trim(str_replace(array("\r\n", "\n\t", "\n "),array("\n", ' ', ' '), $header));
-                /* Now we can make a new header array with */
-                /* each element representing a headerline  */
-                $hdr = explode("\n" , $hdr);
+                /* Now we can make a new header array with
+                   each element representing a headerline  */
+                $aHdr = explode("\n" , $hdr);
                 $aReceived = array();
-                foreach ($hdr as $line) {
+                foreach ($aHdr as $line) {
                     $pos = strpos($line, ':');
                     if ($pos > 0) {
                         $field = strtolower(substr($line, 0, $pos));
                         if (!strstr($field,' ')) { /* valid field */
                             $value = trim(substr($line, $pos+1));
-                            switch($field)
-                            {
-                            case 'to': $msg['TO'] = $value; break;
-                            case 'cc': $msg['CC'] = $value; break;
-                            case 'from': $msg['FROM'] = $value; break;
-                            case 'date':
-                                $msg['DATE'] = str_replace('  ', ' ', $value);
-                                break;
-                            case 'x-priority':
-                            case 'importance':
-                            case 'priority':
-                                $msg['PRIORITY'] = parsePriority($value); break;
-                            case 'subject': $msg['SUBJECT'] = $value; break;
-                            case 'content-type':
-                                $type = $value;
-                                if ($pos = strpos($type, ";")) {
-                                    $type = substr($type, 0, $pos);
-                                }
-                                $type = explode("/", $type);
-                                if(!is_array($type) || count($type) < 2) {
-                                    $msg['TYPE0'] = 'text';
-                                    $msg['TYPE1'] = 'plain';
-                                } else {
-                                    $msg['TYPE0'] = strtolower($type[0]);
-                                    $msg['TYPE1'] = strtolower($type[1]);
-                                }
-                                break;
-                            case 'received':
-                                $aReceived[] = $value;
-                                break;
-                            default: break;
+                            switch($field) {
+                                case 'date':
+                                    $aMsg['date'] = trim(str_replace('  ', ' ', $value));
+                                    break;
+                                case 'x-priority': $aMsg['x-priority'] = ($value) ? (int) $value{0} : 3; break;
+                                case 'priority':
+                                case 'importance':
+                                    if (!isset($aMsg['x-priority'])) {
+                                        $aPrio = split('/\w/',trim($value));
+                                        $sPrio = strtolower(array_shift($aPrio));
+                                        if  (is_numeric($sPrio)) {
+                                            $iPrio = (int) $sPrio;
+                                        } elseif ( $sPrio == 'non-urgent' || $sPrio == 'low' ) {
+                                            $iPrio = 3;
+                                        } elseif ( $sPrio == 'urgent' || $sPrio == 'high' ) {
+                                            $iPrio = 1;
+                                        } else {
+                                            // default is normal priority
+                                            $iPrio = 3;
+                                        }
+                                        $aMsg['x-priority'] = $iPrio;
+                                    }
+                                    break;
+                                case 'content-type':
+                                    $type = $value;
+                                    if ($pos = strpos($type, ";")) {
+                                        $type = substr($type, 0, $pos);
+                                    }
+                                    $type = explode("/", $type);
+                                    if(!is_array($type) || count($type) < 2) {
+                                        $aMsg['content-type'] = array('text','plain');
+                                    } else {
+                                        $aMsg['content-type'] = array(strtolower($type[0]),strtolower($type[1]));
+                                    }
+                                    break;
+                                case 'received':
+                                    $aMsg['received'][] = $value;
+                                    break;
+                                default:
+                                    $aMsg[$field] = $value;
+                                    break;
                             }
                         }
                     }
                 }
-                if (count($aReceived)) {
-                    $msg['RECEIVED'] = $aReceived;
-                }
                 break;
             default:
                 ++$i;
                 break;
             }
         }
-        $msgi ="$unique_id";
-        $msg['UID'] = $unique_id;
-
-        $aMessageList[$msgi] = $msg;
-        ++$msgi;
+        if (!empty($unique_id)) {
+            $msgi = "$unique_id";
+            $aMsg['UID'] = $unique_id;
+       } else {
+            $msgi = '';
+       }
+       $aMessageList[$msgi] = $aMsg;
     }
     return $aMessageList;
 }
 
-
 /**
  * Work in process
  * @private
@@ -949,45 +1010,4 @@ function sqimap_get_message($imap_stream, $id, $mailbox) {
     return $msg;
 }
 
-
-/**
- * Deprecated !!!!!!! DO NOT USE THIS, use sqimap_msgs_list_copy instead
- */
-function sqimap_messages_copy($imap_stream, $start, $end, $mailbox) {
-    $read = sqimap_run_command ($imap_stream, "COPY $start:$end " . sqimap_encode_mailbox_name($mailbox), true, $response, $message, TRUE);
-}
-
-
-/**
- * Deprecated !!!!!!! DO NOT USE THIS, use sqimap_msgs_list_delete instead
- */
-function sqimap_messages_delete($imap_stream, $start, $end, $mailbox, $bypass_trash=false) {
-    global $move_to_trash, $trash_folder;
-
-    if (($move_to_trash == true) && ($bypass_trash != true) &&
-        (sqimap_mailbox_exists($imap_stream, $trash_folder) && ($mailbox != $trash_folder))) {
-        sqimap_messages_copy ($imap_stream, $start, $end, $trash_folder);
-    }
-    sqimap_messages_flag ($imap_stream, $start, $end, "Deleted", true);
-}
-
-
-/**
- * Deprecated !!!!!!! DO NOT USE THIS, use sqimap_toggle_flag instead
- * Set a flag on the provided uid list
- * @param  resource imap connection
- */
-function sqimap_messages_flag($imap_stream, $start, $end, $flag, $handle_errors) {
-    $read = sqimap_run_command ($imap_stream, "STORE $start:$end +FLAGS (\\$flag)", $handle_errors, $response, $message, TRUE);
-}
-
-
-/**
- * @deprecated
- */
-function sqimap_get_small_header($imap_stream, $id, $sent) {
-    $res = sqimap_get_small_header_list($imap_stream, $id, $sent);
-    return $res[0];
-}
-
 ?>