Fix bug while modifying addresses, if you get an error, you can't resubmit the form...
[squirrelmail.git] / functions / imap_general.php
index eb044690e2484a1fd894a90ea6b923e61b2bd7b5..ea8ba293981c0869383cea691e2178ba398ecfdb 100755 (executable)
@@ -36,8 +36,13 @@ function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$respon
     if ($imap_stream) {
         $sid = sqimap_session_id($unique_id);
         fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
-        $read = sqimap_read_data_list ($imap_stream, $sid, $handle_errors, $response, $message, $query );
-        return $read;
+        $tag_uid_a = explode(' ',trim($sid));
+        $tag = $tag_uid_a[0];
+        $read = sqimap_read_data_list ($imap_stream, $tag, $handle_errors, $response, $message, $query );
+        /* get the response and the message */
+        $message = $message[$tag];
+        $response = $response[$tag]; 
+        return $read[$tag];
     } else {
         global $squirrelmail_language, $color;
         set_up_language($squirrelmail_language);
@@ -48,15 +53,27 @@ function sqimap_run_command_list ($imap_stream, $query, $handle_errors, &$respon
         error_box($string,$color);
         return false;
     }
-    
 }
 
-function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id = false) {
+function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response, 
+                            &$message, $unique_id = false,$filter=false,
+                             $outputstream=false,$no_return=false) {
     if ($imap_stream) {
         $sid = sqimap_session_id($unique_id);
-        fputs ($imap_stream, $sid . ' ' . $query . "\r\n");
-        $read = sqimap_read_data ($imap_stream, $sid, $handle_errors, $response, $message, $query);
-        return $read;
+        fputs ($imap_stream, $sid . ' ' . $query . "\r\n"); 
+        $tag_uid_a = explode(' ',trim($sid));
+        $tag = $tag_uid_a[0];
+   
+        $read = sqimap_read_data ($imap_stream, $tag, $handle_errors, $response,
+                                  $message, $query,$filter,$outputstream,$no_return);
+        /* retrieve the response and the message */
+        $response = $response[$tag];
+        $message  = $message[$tag];
+        if (!empty($read[$tag])) {
+            return $read[$tag][0];
+        } else {
+            return $read[$tag];
+        }
     } else {
         global $squirrelmail_language, $color;
         set_up_language($squirrelmail_language);
@@ -66,10 +83,38 @@ function sqimap_run_command ($imap_stream, $query, $handle_errors, &$response, &
                 "</b></font>\n";
         error_box($string,$color);
         return false;
-    }
-    
+    }    
+}
+function sqimap_prepare_pipelined_query($new_query,&$tag,&$aQuery,$unique_id) {
+    $sid = sqimap_session_id($unique_id);
+    $tag_uid_a = explode(' ',trim($sid));
+    $tag = $tag_uid_a[0];
+    $query = $sid . ' '.$new_query."\n";
+    $aQuery[$tag] = $query;
 }
 
+function sqimap_run_pipelined_command ($imap_stream, $aQuery, $handle_errors, 
+                       &$aServerResponse, &$aServerMessage, $unique_id = false,
+                       $filter=false,$outputstream=false,$no_return=false) {
+    $aResponse = false;
+    foreach($aQuery as $tag => $query) {
+        fputs($imap_stream,$query);
+        $aResults[$tag] = false;
+    }
+   
+    foreach($aQuery as $tag => $query) {
+        if (!$aResults[$tag]) {
+            $aReturnedResponse = sqimap_read_data_list ($imap_stream, $tag, 
+                                    $handle_errors, $response, $message, $query,
+                                    $filter,$outputstream,$no_return);
+            foreach ($aReturnedResponse as $returned_tag => $aResponse) {
+                $aResults[$returned_tag] = $aResponse;
+                $aServerResponse[$returned_tag] = $response[$returned_tag];
+                $aServerMessage[$returned_tag] = $message[$returned_tag];
+            }
+        }
+    }
+}
 
 /* 
  * custom fgets function. gets a line from IMAP
@@ -81,9 +126,11 @@ function sqimap_fgets($imap_stream) {
     $buffer = 4096;
     $results = '';
     $offset = 0;
-    $i=0;
     while (strpos($results, "\r\n", $offset) === false) {
         if (!($read = fgets($imap_stream, $buffer))) {
+        /* this happens in case of an error */
+        /* reset $results because it's useless */
+        $results = false;
             break;
         }
         if ( $results != '' ) {
@@ -94,17 +141,113 @@ function sqimap_fgets($imap_stream) {
     return $results;
 }
 
+function sqimap_fread($imap_stream,$iSize,$filter=false,
+                      $outputstream=false, $no_return=false) {
+    if (!$filter || !$outputstream) {
+        $iBufferSize = $iSize;
+    } else {
+        $iBufferSize = 62400; // multiple of 78 in case of base64 decoding.
+    }
+    $iRet = $iSize - $iBufferSize;
+    $iRetrieved = 0;
+    $i = 0;
+    $results = $sReadRem = '';
+    $bFinished = $bBufferSizeAdapted =  $bBufferIsOk = false;
+    while (($iRetrieved < ($iSize - $iBufferSize))) {
+        $sRead = fread($imap_stream,$iBufferSize);
+        if (!$sRead) {
+            $results = false;
+            break;
+        }
+        $iRetrieved += $iBufferSize;
+        if ($filter) {
+           // in case line-endings do not appear at position 78 we adapt the buffersize so we can base64 decode on the fly
+           if (!$bBufferSizeAdapted) {
+               $i = strpos($sRead,"\n");
+               if ($i) {
+                   ++$i;
+                   $iFragments = floor($iBufferSize / $i);
+                   $iNewBufferSize = $iFragments * $i;
+                   $iRemainder = $iNewBufferSize + $i - $iBufferSize;
+                   if ($iNewBufferSize == $iBufferSize) {
+                       $bBufferIsOk = true;
+                       $iRemainder = 0;
+                       $iNewBufferSize = $iBufferSize;
+                       $bBufferSizeAdapted = true;
+                   }
+                   if (!$bBufferIsOk && ($iRemainder + $iBufferSize)  < $iSize) {
+                       $sReadRem = fread($imap_stream,$iRemainder);
+                   } else if (!$bBufferIsOk) {
+                       $sReadRem = fread($imap_stream,$iSize - $iBufferSize);
+                       $bFinished = true;
+                   }
+                   if (!$sReadRem && $sReadRem !== '') {
+                        $results = false;
+                        break;
+                   }
+                   $iBufferSize = $iNewBufferSize;
+                   $bBufferSizeAdapted = true;
+               } else {
+                   $sReadRem = fread($imap_stream,$iSize - $iBufferSize);
+                   $bFinished = true;
+                   if (!$sReadRem) {
+                       $results = false;
+                       break;
+                   }
+               }
+               $sRead .= $sReadRem;
+               $iRetrieved += $iRemainder;
+               unset($sReadRem);
+           }
+           $filter($sRead);
+        }
+        if ($outputstream) {
+           if (is_resource($outputstream)) {
+               fwrite($outputstream,$sRead);
+           } else if ($outputstream == 'php://stdout') {
+               echo $sRead;
+           }
+        }
+        if ($no_return) {
+            $sRead = '';
+        }    
+        $results .= $sRead;
+    }
+    if (!$results && !$bFinished) {
+        $sRead = fread($imap_stream,($iSize - ($iRetrieved)));  
+        if ($filter) {
+           $filter($sRead);
+        }
+        if ($outputstream) {
+           if (is_resource($outputstream)) {      
+               fwrite($outputstream,$sRead);
+           } else if ($outputstream == 'php://stdout') { // FIXME
+               echo $sRead;
+           }
+        }
+        if ($no_return) {
+            $sRead = '';
+        }    
+        $results .= $sRead;
+    }
+    return $results;       
+}        
+
+
+
 /*
  * Reads the output from the IMAP stream.  If handle_errors is set to true,
  * this will also handle all errors that are received.  If it is not set,
  * the errors will be sent back through $response and $message
  */
 
-function sqimap_read_data_list ($imap_stream, $tag_uid, $handle_errors, &$response, &$message, $query = '') {
+function sqimap_read_data_list ($imap_stream, $tag, $handle_errors, 
+          &$response, &$message, $query = '',
+           $filter = false, $outputstream = false, $no_return = false) {
     global $color, $squirrelmail_language;
     $read = '';
-    $tag_uid_a = explode(' ',trim($tag_uid));
-    $tag = $tag_uid_a[0];
+    if (!is_array($message)) $message = array();
+    if (!is_array($response)) $response = array();
     $resultlist = array();
     $data = array();
     $read = sqimap_fgets($imap_stream);
@@ -113,7 +256,13 @@ function sqimap_read_data_list ($imap_stream, $tag_uid, $handle_errors, &$respon
         $char = $read{0};
         switch ($char)
         {
-        case $tag{0}:
+          case '+':
+          default:
+            $read = sqimap_fgets($imap_stream);
+            break;
+
+          case $tag{0}:
+          {
             /* get the command */
             $arg = '';
             $i = strlen($tag)+1;
@@ -125,27 +274,45 @@ function sqimap_read_data_list ($imap_stream, $tag_uid, $handle_errors, &$respon
             if ($arg && $found_tag==$tag) {
                 switch ($arg)
                 {
-                case 'OK':
-                case 'BAD':
-                case 'NO':
-                case 'BYE':
-                case 'PREAUTH':
-                    $response = $arg;
-                    $message = trim(substr($read,$i+strlen($arg)));
-                    break 3;
-                default: 
+                  case 'OK':
+                  case 'BAD':
+                  case 'NO':
+                  case 'BYE':
+                  case 'PREAUTH':
+                    $response[$found_tag] = $arg;
+                    $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
+                    if (!empty($data)) {
+                        $resultlist[] = $data;
+                    }
+                    $aResponse[$tag] = $resultlist;
+                    break 3; /* switch switch while */
+                  default: 
                     /* this shouldn't happen */
-                    $response = $arg;
-                    $message = trim(substr($read,$i+strlen($arg)));
-                    break 3;
+                    $response[$found_tag] = $arg;
+                    $message[$found_tag] = trim(substr($read,$i+strlen($arg)));
+                    if (!empty($data)) {
+                        $resultlist[] = $data;
+                    }
+                    $aResponse[$found_tag] = $resultlist;
+                    break 3; /* switch switch while */
                 }
             } elseif($found_tag !== $tag) {
-                /* reset data array because we do not need this reponse */
-                $data = array();
+                /* not the tag we are looking for, continue */
+                if (!empty($data)) {
+                    $resultlist[] = $data;
+                }
+                $aResponse[$found_tag] = $resultlist;
+                $resultlist = $data = array();
                 $read = sqimap_fgets($imap_stream);
+                if ($read === false) { /* error */
+                     break 3; /* switch switch while */
+                }
                 break;
             }
-            case '*':
+          } // end case $tag{0}
+
+          case '*':
+          {
             if (preg_match('/^\*\s\d+\sFETCH/',$read)) {
                 /* check for literal */
                 $s = substr($read,-3);
@@ -160,7 +327,10 @@ function sqimap_read_data_list ($imap_stream, $tag_uid, $handle_errors, &$respon
                             $j = strrpos($read,'{');
                             $iLit = substr($read,$j+1,-3);
                             $fetch_data[] = $read;
-                            $sLiteral = fread($imap_stream,$iLit);
+                            $sLiteral = sqimap_fread($imap_stream,$iLit,$filter,$outputstream,$no_return);
+                            if ($sLiteral === false) { /* error */
+                                break 4; /* while while switch while */
+                            }
                             /* backwards compattibility */
                             $aLiteral = explode("\n", $sLiteral);
                             /* release not neaded data */
@@ -173,20 +343,27 @@ function sqimap_read_data_list ($imap_stream, $tag_uid, $handle_errors, &$respon
                             /* next fgets belongs to this fetch because
                                we just got the exact literalsize and there
                                must follow data to complete the response */
-                            $fetch_data[] = sqimap_fgets($imap_stream);
+                            $read = sqimap_fgets($imap_stream);
+                            if ($read === false) { /* error */
+                                break 4; /* while while switch while */
+                            }
+                            $fetch_data[] = $read;
                         } else {
-                           $fetch_data[] = $read;
+                            $fetch_data[] = $read;
                         }
                         /* retrieve next line and check in the while
                            statements if it belongs to this fetch response */
                         $read = sqimap_fgets($imap_stream);
+                        if ($read === false) { /* error */
+                            break 4; /* while while switch while */
+                        }
                         /* check for next untagged reponse and break */
                         if ($read{0} == '*') break 2;
                         $s = substr($read,-3);
                     } while ($s === "}\r\n");
                     $s = substr($read,-3);
                 } while ($read{0} !== '*' &&
-                substr($read,0,strlen($tag)) !== $tag);
+                         substr($read,0,strlen($tag)) !== $tag);
                 $resultlist[] = $fetch_data;
                 /* release not neaded data */
                 unset ($fetch_data);
@@ -197,37 +374,65 @@ function sqimap_read_data_list ($imap_stream, $tag_uid, $handle_errors, &$respon
                         $j = strrpos($read,'{');
                         $iLit = substr($read,$j+1,-3);
                         $data[] = $read;
-                        $data[] = fread($imap_stream,$iLit);
+                        $sLiteral = fread($imap_stream,$iLit);
+                        if ($sLiteral === false) { /* error */
+                            $read = false;
+                            break 3; /* while switch while */
+                        }
+                        $data[] = $sLiteral;
                         $fetch_data[] = sqimap_fgets($imap_stream);
                     } else {
-                        $data[] = $read;
+                         $data[] = $read;
                     }
                     $read = sqimap_fgets($imap_stream);
-                    if ($read{0} == '*') break;
+                    if ($read === false) {
+                        break 3; /* while switch while */
+                    } else if ($read{0} == '*') {
+                        break;
+                    }
                     $s = substr($read,-3);
                 } while ($s === "}\r\n");
                 break 1;
             }
             break;
-        case '+':
-            $read = sqimap_fgets($imap_stream);
-            break;
-        default:
-            $read = sqimap_fgets($imap_stream);
-            break;
-        }
+          } // end case '*'
+        }   // end switch
+    } // end while
+    
+    /* error processing in case $read is false */
+    if ($read === false) {
+        unset($data);
+        set_up_language($squirrelmail_language);
+        require_once(SM_PATH . 'functions/display_messages.php');
+        $string = "<b><font color=$color[2]>\n" .
+                  _("ERROR : Connection dropped by imap-server.") .
+                  "</b><br>\n" .
+                  _("Query:") . ' '.
+                  htmlspecialchars($query) . '<br>' . "</font><br>\n";
+        error_box($string,$color);    
+        exit;
     }
+    
+    /* Set $resultlist array */
     if (!empty($data)) {
-        $resultlist[] = $data;
+        //$resultlist[] = $data;
     }
     elseif (empty($resultlist)) {
         $resultlist[] = array(); 
     }
+
+    /* Return result or handle errors */
     if ($handle_errors == false) {
+        return $aResponse;
         return( $resultlist );
-    } 
-    elseif ($response == 'NO') {
-    /* ignore this error from M$ exchange, it is not fatal (aka bug) */
+    }
+    switch ($response[$tag])
+    {
+    case 'OK':
+        return $aResponse;
+        break;
+    case 'NO': 
+        /* ignore this error from M$ exchange, it is not fatal (aka bug) */
         if (strstr($message, 'command resulted in') === false) {
             set_up_language($squirrelmail_language);
             require_once(SM_PATH . 'functions/display_messages.php');
@@ -237,12 +442,13 @@ function sqimap_read_data_list ($imap_stream, $tag_uid, $handle_errors, &$respon
                 _("Query:") . ' ' .
                 htmlspecialchars($query) . '<br>' .
                 _("Reason Given: ") .
-                htmlspecialchars($message) . "</font><br>\n";
+                htmlspecialchars($message[$tag]) . "</font><br>\n";
             error_box($string,$color);
+            echo '</body></html>';
             exit;
         }
-    } 
-    elseif ($response == 'BAD') {
+        break;
+    case 'BAD': 
         set_up_language($squirrelmail_language);
         require_once(SM_PATH . 'functions/display_messages.php');
         $string = "<b><font color=$color[2]>\n" .
@@ -251,18 +457,50 @@ function sqimap_read_data_list ($imap_stream, $tag_uid, $handle_errors, &$respon
             _("Query:") . ' '.
             htmlspecialchars($query) . '<br>' .
             _("Server responded: ") .
-            htmlspecialchars($message) . "</font><br>\n";
-        error_box($string,$color);    
+            htmlspecialchars($message[$tag]) . "</font><br>\n";
+        error_box($string,$color);
+        echo '</body></html>';        
+        exit; 
+    case 'BYE': 
+        set_up_language($squirrelmail_language);
+        require_once(SM_PATH . 'functions/display_messages.php');
+        $string = "<b><font color=$color[2]>\n" .
+            _("ERROR : Imap server closed the connection.") .
+            "</b><br>\n" .
+            _("Query:") . ' '.
+            htmlspecialchars($query) . '<br>' .
+            _("Server responded: ") .
+            htmlspecialchars($message[$tag]) . "</font><br>\n";
+        error_box($string,$color);
+        echo '</body></html>';        
         exit;
-    } 
-    else {
-        return $resultlist;
+    default: 
+        set_up_language($squirrelmail_language);
+        require_once(SM_PATH . 'functions/display_messages.php');
+        $string = "<b><font color=$color[2]>\n" .
+            _("ERROR : Unknown imap response.") .
+            "</b><br>\n" .
+            _("Query:") . ' '.
+            htmlspecialchars($query) . '<br>' .
+            _("Server responded: ") .
+            htmlspecialchars($message[$tag]) . "</font><br>\n";
+        error_box($string,$color);
+       /* the error is displayed but because we don't know the reponse we
+          return the result anyway */
+       return $aResponse;    
+       break;
     }
 }
 
-function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors, &$response, &$message, $query = '') {
-    $res = sqimap_read_data_list($imap_stream, $tag_uid, $handle_errors, $response, $message, $query);
-  
+function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors, 
+                           &$response, &$message, $query = '',
+                           $filter=false,$outputstream=false,$no_return=false) {
+
+    $tag_uid_a = explode(' ',trim($tag_uid));
+    $tag = $tag_uid_a[0];
+
+    $res = sqimap_read_data_list($imap_stream, $tag, $handle_errors, 
+              $response, $message, $query,$filter,$outputstream,$no_return); 
     /* sqimap_read_data should be called for one response
        but since it just calls sqimap_read_data_list which 
        handles multiple responses we need to check for that
@@ -277,12 +515,11 @@ function sqimap_read_data ($imap_stream, $tag_uid, $handle_errors, &$response, &
 //        }
 //    }
     if (isset($result)) {
-        return $result;
+        return $result[$tag];
     }
     else {
-        return $res[0];
+        return $res;
     }
-
 }
 
 /*
@@ -511,138 +748,164 @@ function sqimap_get_num_messages ($imap_stream, $mailbox) {
 }
 
 
-function parseAddress($address, $max=0, $addr_ar = array(), $group = '', $host='', $limit=0) {
-    $pos = 0;
-    $j = strlen($address);
-    $personal = '';
-    $addr = '';
-    $comment = '';
-    if ($max && $max == count($addr_ar)) {
-        return $addr_ar;
-    }
-    while ($pos < $j) {
-        if ($max && $max == count($addr_ar)) {
-            return $addr_ar;
-        }
-        $char = $address{$pos};
-        switch ($char) {
-            case '=':
-            /* check if it is an encoded string */
-                if (preg_match('/^(=\?([^?]*)\?(Q|B)\?([^?]*)\?=)(.*)/Ui',substr($address,$pos),$reg)) {
-            /* add stringpart before the encoded string to the personal var */
-            if (!$personal) {
-            $personal = substr($address,0,$pos);
+function parseAddress($address, $max=0) {
+    $aTokens = array();
+    $aAddress = array();
+    $iCnt = strlen($address);
+    $aSpecials = array('(' ,'<' ,',' ,';' ,':');
+    $aReplace =  array(' (',' <',' ,',' ;',' :');
+    $address = str_replace($aSpecials,$aReplace,$address);
+    $i = $iAddrFound = $bGroup = 0;
+    while ($i < $iCnt) {
+        $cChar = $address{$i};
+        switch($cChar)
+        {
+        case '<':
+            $iEnd = strpos($address,'>',$i+1);
+            if (!$iEnd) {
+               $sToken = substr($address,$i);
+               $i = $iCnt;
+            } else {
+               $sToken = substr($address,$i,$iEnd - $i +1);
+               $i = $iEnd;
             }
-                    $personal .= $reg[1];
-            $pos += strlen($reg[1]);
-                } else {
-                    ++$pos;
+            $sToken = str_replace($aReplace, $aSpecials,$sToken);
+            $aTokens[] = $sToken;
+            break;
+        case '"':
+            $iEnd = strpos($address,$cChar,$i+1);
+            if (!$iEnd) {
+                $sToken = substr($address,$i);
+                $i = $iCnt;
+            } else {
+                // also remove the surrounding quotes
+                $sToken = substr($address,$i+1,$iEnd - $i -1);
+                $i = $iEnd;
+            }
+            $sToken = str_replace($aReplace, $aSpecials,$sToken);
+            if ($sToken) $aTokens[] = $sToken;
+            break;
+        case '(':
+            $iEnd = strpos($address,')',$i);
+            if (!$iEnd) {
+                $sToken = substr($address,$i);
+                $i = $iCnt;
+            } else {
+                $sToken = substr($address,$i,$iEnd - $i + 1);
+                $i = $iEnd;
+            }
+            $sToken = str_replace($aReplace, $aSpecials,$sToken);
+            $aTokens[] = $sToken;
+            break;
+        case ',':
+            ++$iAddrFound;
+        case ';':
+            if (!$bGroup) {
+               ++$iAddrFound;
+            } else {
+               $bGroup = false;
+            }
+            if ($max && $max == $iAddrFound) {
+               break 2;
+            } else {
+               $aTokens[] = $cChar;
+               break;
+            }
+        case ':':
+           $bGroup = true;
+        case ' ':
+            $aTokens[] = $cChar;
+            break;
+        default:
+            $iEnd = strpos($address,' ',$i+1);
+            if ($iEnd) {
+                $sToken = trim(substr($address,$i,$iEnd - $i));
+                $i = $iEnd-1;
+            } else {
+                $sToken = trim(substr($address,$i));
+                $i = $iCnt;
+            }
+            if ($sToken) $aTokens[] = $sToken;
         }
+        ++$i;
+    }
+    $sPersonal = $sEmail = $sComment = $sGroup = '';
+    $aStack = $aComment = array();
+    foreach ($aTokens as $sToken) {
+        if ($max && $max == count($aAddress)) {
+            return $aAddress;
+        }
+        $cChar = $sToken{0};
+        switch ($cChar)
+        {
+          case '=':
+          case '"':
+          case ' ':
+            $aStack[] = $sToken; 
+            break;
+          case '(':
+            $aComment[] = substr($sToken,1,-1);
+            break;
+          case ';':
+            if ($sGroup) {
+                $sEmail = trim(implode(' ',$aStack));
+                $aAddress[] = array($sGroup,$sEmail);
+                $aStack = $aComment = array();
+                $sGroup = '';
                 break;
-            case '"': /* get the personal name */
-                ++$pos;
-                if ($address{$pos} == '"') {
-                    ++$pos;
-                } else {                
-                    $personal_start = $personal_end = $pos;
-                    while ($pos < $j) {
-                        $personal_end = strpos($address,'"',$pos);
-                        if (($personal_end-2)>0 && (substr($address,$personal_end-2,2) === '\\"' ||
-                            substr($address,$personal_end-2,2) === '\\\\')) {
-                            $pos = $personal_end+1;
-                        } else {
-                            $personal = substr($address,$personal_start,$personal_end-$personal_start);
-                            break;
-                        }
-                    }
-                    if ($personal_end) { /* prohibit endless loops due to very wrong addresses */
-                         $pos = $personal_end+1;
-                    } else {
-                         $pos = $j;
-                    }
-                }
-                break;
-            case '<':  /* get email address */
-                $addr_start = $pos;
-                $addr_end = strpos($address,'>',$addr_start);
-                if($addr_end === FALSE) {
-                    // in case the address doesn't end, prevent loop
-                    $pos++;
-                } else {
-                    $addr = substr($address,$addr_start+1,$addr_end-$addr_start-1);
-                    $pos = $addr_end+1;
-                }
-                break;
-            case '(':  /* rip off comments */
-                $addr_start = $pos;
-                $pos = strpos($address,')');
-                if ($pos !== false) {
-                    $comment = substr($address, $addr_start+1,($pos-$addr_start-1));
-                    $address_start = substr($address, 0, $addr_start);
-                    $address_end   = substr($address, $pos + 1);
-                    $address       = $address_start . $address_end;
+            }
+          case ',':
+            if (!$sEmail) {
+                while (count($aStack) && !$sEmail) {
+                    $sEmail = trim(array_pop($aStack));
                 }
-                $j = strlen($address);
-                $pos = $addr_start + 1;
-                break;
-            case ';': /* we reached a non rfc2822 compliant delimiter */
-                if ($group) {
-                    $address = substr($address, 0, $pos - 1);
-            ++$pos;
+            }
+            if (count($aStack)) {
+                $sPersonal = trim(implode('',$aStack));
+            } else { 
+                $sPersonal = '';
+            }
+            if (!$sPersonal && count($aComment)) {
+                $sComment = implode(' ',$aComment);
+                $sPersonal .= $sComment;
+            }
+            $aAddress[] = array($sEmail,$sPersonal);
+            $sPersonal = $sComment = $sEmail = '';
+            $aStack = $aComment = array();
             break;
-                }
-            case ',':  /* we reached a delimiter */
-                if ($addr == '') {
-                    $addr = substr($address, 0, $pos);
-                } else if ($personal == '') {
-                    $personal = trim(substr($address, 0, $addr_start));
-                }
-                if (!$personal && $comment) $personal = $comment;
-                if ($personal) $personal = decodeHeader($personal);
-                $addr_ar[] = array($addr,$personal);
-                $address = trim(substr($address, $pos+1));
-                $j = strlen($address);
-                $pos = 0;
-                $personal = '';
-                $addr = '';
-                break;
-            case ':':  /* process the group addresses */
-                /* group marker */
-                $group = substr($address, 0, $pos);
-                $address = substr($address, $pos+1);
-                $result = parseAddress($address, $max, $addr_ar, $group);
-                $addr_ar = $result[0];
-                $pos = $result[1];
-                $address = substr($address, $pos++);
-                $j = strlen($address);
-                $group = '';
-                break;
-            default:
-                ++$pos;
-                break;
+          case ':': 
+            $sGroup = implode(' ',$aStack); break;
+            $aStack = array();
+            break;
+          case '<':
+            $sEmail = trim(substr($sToken,1,-1));
+            break;
+          case '>':
+            /* skip */
+            break; 
+          default: $aStack[] = $sToken; break;
         }
     }
-    if ($addr == '') {
-        $addr = substr($address, 0, $pos);
-    } else if ($personal == '') {
-        $personal = trim(substr($address, 0, $addr_start));
+    /* now do the action again for the last address */
+    if (!$sEmail) {
+        while (count($aStack) && !$sEmail) {
+            $sEmail = trim(array_pop($aStack));
+        }
     }
-    if (!$personal && $comment) $personal = $comment;
-    $email = $addr;
-    if ($group && $addr == '') { /* no addresses found in group */
-        $personal = $group;
-        $addr_ar[] = array('',$personal);
-        return (array($addr_ar,$pos+1 ));
-    } elseif ($group) {
-        $addr_ar[] = array($addr,$personal);
-        return (array($addr_ar,$pos+1 ));
+    if (count($aStack)) {
+        $sPersonal = trim(implode('',$aStack));
     } else {
-        if ($personal || $addr) {
-            $addr_ar[] = array($addr, $personal);
-        }
+        $sPersonal = '';
     }
-    return ($addr_ar);
-}
+    if (!$sPersonal && count($aComment)) {
+        $sComment = implode(' ',$aComment);
+        $sPersonal .= $sComment;
+    }
+    $aAddress[] = array($sEmail,$sPersonal);
+    return $aAddress;
+} 
+
+
 
 /*
  * Returns the number of unseen messages in this folder