Index: /trunk/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- /trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 4784)
+++ /trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 4795)
@@ -88,5 +88,5 @@
 		}
 		// This condition verifies if SESSION is expired.
-		elseif(!count($_SESSION))			
+		elseif(!count($_SESSION))
 			return "nosession";
 
@@ -288,37 +288,37 @@
 	*/
 	function decode_string($string)
-    {    
-        if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
-        {
+	{
+		if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
+		{
             $retun = '';
-            $tmp = imap_mime_header_decode($string);
-            foreach ($tmp as $tmp1)
+			$tmp = imap_mime_header_decode($string);
+			foreach ($tmp as $tmp1)
             {
-                $return .= $this->htmlspecialchars_encode($tmp1->text);
+				$return .= $this->htmlspecialchars_encode($tmp1->text);
             }
-            
+
             return str_replace("\t", "", $return);
-        }
-        else if (strpos(strtolower($string), '=?utf-8') !== false)
-        {
-            $elements = imap_mime_header_decode($string);
-
-              for($i = 0;$i < count($elements);$i++)
-              {
-					$charset = strtolower($elements[$i]->charset); 
-					$text = $elements[$i]->text; 
-					if(!strcasecmp($charset, "utf-8") || !strcasecmp($charset, "utf-7"))
-						$decoded .= $this->functions->utf8_to_ncr($text);
-                  else
-                  {
-                    if( strcasecmp($charset,"default") )
-                        $decoded .= $this->htmlspecialchars_encode(iconv($charset, "iso-8859-1", $text));
-                    else
-                        $decoded .= $this->htmlspecialchars_encode($text);
-                  }
-              }
+		}
+		else if (strpos(strtolower($string), '=?utf-8') !== false)
+		{
+			$elements = imap_mime_header_decode($string);
+
+  			for($i = 0;$i < count($elements);$i++)
+  			{
+   				$charset = strtolower($elements[$i]->charset);
+   				$text = $elements[$i]->text;
+   				if(!strcasecmp($charset, "utf-8") || !strcasecmp($charset, "utf-7"))
+       				$decoded .= $this->functions->utf8_to_ncr($text);
+  				else
+  				{
+					if( strcasecmp($charset,"default") )
+						$decoded .= $this->htmlspecialchars_encode(iconv($charset, "iso-8859-1", $text));
+					else
+						$decoded .= $this->htmlspecialchars_encode($text);
+  				}
+  			}
 
               return str_replace("\t", "", $decoded);
-        }
+		}
 		else if(strpos(strtolower($string), '=?us-ascii') !== false) 
  	   { 
@@ -335,6 +335,6 @@
         
 
-        return $this->htmlspecialchars_encode($string);
-    }
+			return $this->htmlspecialchars_encode($string);
+	}
 	/**
 	* Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
@@ -581,5 +581,5 @@
 		return $return;
 	}
-	
+
 	/**
 	* @license   http://www.gnu.org/copyleft/gpl.html GPL
@@ -822,24 +822,24 @@
 		
 		if(preg_match('(.+)(_[a-zA-Z0-9]+)',$msg_number,$matches)) { //Verifies if it comes from a tab diferent of the main one. 
- 			$msg_number = $matches[1]; 
- 			$plus_id = $matches[2]; 
-		} 
-		else { 
- 			$plus_id = ''; 
-		} 
-		
+			$msg_number = $matches[1];
+			$plus_id = $matches[2];
+		}
+		else {
+			$plus_id = '';
+		}
+
 		if(!$this->mbox || !is_resource($this->mbox))
-			$this->mbox = $this->open_mbox($msg_folder);		
+			$this->mbox = $this->open_mbox($msg_folder);
 		
 		$header = $this->get_header($msg_number);
 		if (!$header) {
-			$return['status_get_msg_info'] = "false";			
+			$return['status_get_msg_info'] = "false";
 			return $return;
 		}
-		
-		$header_ = imap_fetchheader($this->mbox, $msg_number, FT_UID);		
+
+		$header_ = imap_fetchheader($this->mbox, $msg_number, FT_UID);
 		$return_get_body = $this->get_body_msg($msg_number, $msg_folder);
 		$body = $return_get_body['body'];
-		
+
 		if($return_get_body['body']=='isCripted'){
 			$exporteml = new ExportEml();
@@ -851,20 +851,20 @@
 			//return $return;
 		}else{
-            $return['body'] 		= $body;
-            $return['attachments'] 	= $return_get_body['attachments'];
-            $return['thumbs'] 		= $return_get_body['thumbs'];
-            $return['signature']	= $return_get_body['signature'];
-        }
+	    $return['body'] 		= $body;
+	    $return['attachments'] 	= $return_get_body['attachments'];
+	    $return['thumbs'] 		= $return_get_body['thumbs'];
+	    $return['signature']	= $return_get_body['signature'];
+		}
 		$pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm';
 		if (preg_match($pattern, $header_, $fields))
 		{
-			if(preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches)){
-				$return['DispositionNotificationTo'] = "<".$matches[0].">";
-			}
+			if(preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches)){ 
+				$return['DispositionNotificationTo'] = "<".$matches[0].">"; 
+			} 
 		}
 
 		$return['Recent']	= $header->Recent;
 		$return['Unseen']	= $header->Unseen;
-		$return['Deleted']	= $header->Deleted;		
+		$return['Deleted']	= $header->Deleted;
 		$return['Flagged']	= $header->Flagged;
 
@@ -872,13 +872,13 @@
 			$return['Forwarded'] = 'F';
 		}
- 
+
 		else {
 			$return['Answered']	= $header->Answered;
-			$return['Draft']	= $header->Draft;	
-		}
-
-		$return['msg_number'] = $msg_number.$plus_id; 
+			$return['Draft']	= $header->Draft;
+		}
+
+		$return['msg_number'] = $msg_number.$plus_id;
 		$return['msg_folder'] = $msg_folder;
-	
+
 		$date_msg = gmdate("d/m/Y",$header->udate);
 		if (date("d/m/Y") == $date_msg)
@@ -886,8 +886,8 @@
 		else
 			$return['udate'] = $date_msg;
-		
-		$return['msg_day'] = $date_msg; 
+
+		$return['msg_day'] = $date_msg;
 		$return['msg_hour'] = gmdate("H:i",$header->udate);
-		
+
 		if (date("d/m/Y") == $date_msg) //no dia
 		{
@@ -895,5 +895,5 @@
 			$return['smalldate'] = gmdate("H:i",$header->udate);
 
-			$timestamp_now = strtotime("now") + $offset;  			
+			$timestamp_now = strtotime("now") + $offset;
 			$timestamp_msg_time = $header->udate;
 			// $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ. 
@@ -901,5 +901,5 @@
 			$pdate = date_parse($header->MailDate);
 			$timestamp_diff = $timestamp_now - $timestamp_msg_time  + ($pdate['zone']*(-60));
-			
+
 			if (gmdate("H",$timestamp_diff) > 0)
 			{
@@ -923,5 +923,5 @@
 			$return['smalldate'] = gmdate("d/m/Y",$header->udate);
 		}
-		
+
 		$from = $header->from;
 		$return['from'] = array();
@@ -937,8 +937,8 @@
 		else
 			$return['from']['full'] = $return['from']['email'];
-		
+
 		// Sender attribute
 		$sender = $header->sender;
-		$return['sender'] = array();		
+		$return['sender'] = array();
 		$return['sender']['name'] = $this->decode_string($sender[0]->personal);
 		$return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
@@ -989,5 +989,5 @@
 			$return['toaddress2'] = "";
 		}	
-		
+
 		$cc = $header->cc;
 		$return['cc'] = "";
@@ -1017,5 +1017,5 @@
 		{
 			$return['cc'] = "";
-		}	
+		}
 
 		##
@@ -1025,5 +1025,5 @@
 		##
                 
-                $bcc = $header->bcc;
+		$bcc = $header->bcc;
 		$return['bcc'] = "";
 		if (!empty($bcc))
@@ -1052,5 +1052,5 @@
 		{
 			$return['bcc'] = "";
-		}	
+		}
 
 		$reply_to = $header->reply_to;
@@ -1082,12 +1082,12 @@
 		$return['reply_to'] = $this->decode_string($return['reply_to']);
 		$return['subject'] = $this->decode_string($header->fetchsubject);
-		$return['Size'] = $header->Size;		
+		$return['Size'] = $header->Size;
 		$return['reply_toaddress'] = $header->reply_toaddress;
-		
+
 		//All this is to help in local messages
-		$return['timestamp'] = $header->udate;
+                $return['timestamp'] = $header->udate;
 		$return['login'] = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];//$GLOBALS['phpgw_info']['user']['account_id'];
 		$return['reply_toaddress'] = $header->reply_toaddress;
-	
+                
 		return $return;
 	}
@@ -1099,18 +1099,18 @@
  	 */ 
  	function utf8_to_html ($data) 
- 	{ 
+	{
  	    return preg_replace("/([\\xC0-\\xF7]{1,1}[\\x80-\\xBF]+)/e", '$this->_utf8_to_html("\\1")', $data); 
  	} 
- 		 
+
  	function _utf8_to_html ($data) 
- 	{ 
+		{ 
  	    $ret = 0; 
 		foreach((str_split(strrev(chr((ord($data{0}) % 252 % 248 % 240 % 224 % 192) + 128) . substr($data, 1)))) as $k => $v) 
 			$ret += (ord($v) % 128) * pow(64, $k); 
  		    return "&#$ret;"; 
- 	} 
+		} 
  	//------------------------------------------------------------------------------// 
-	
-	
+
+
 	
 	
@@ -1122,7 +1122,7 @@
          */
         function decodeMailPart($part, $encode, $html = true)
-        {
+		{
             switch (strtolower($encode))
-            {
+			{
                 case 'iso-8859-1':
                     return $part;
@@ -1132,5 +1132,5 @@
                     if ($html) 
 						return  $this->utf8_to_html($part); 
- 	                else       
+		else
 						return  utf8_decode ($part);
                     break;
@@ -1138,8 +1138,8 @@
                 default:
                     return mb_convert_encoding($part, 'iso-8859-1');
-                    break;
-            }
-        }
-	
+					break;
+				}
+			}
+
 	
 	function get_body_msg($msg_number, $msg_folder)
@@ -1151,11 +1151,11 @@
             require_once $_SESSION['rootPath'].'/library/mime/mimeDecode.php';
             require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
-            include_once ("class.message_components.inc.php");
+		include_once("class.message_components.inc.php");
             //--------------------------------------------------------------------//
 
             $return = array();
 
-            $msg = &new message_components($this->mbox);
-            $msg->fetch_structure($msg_number);
+		$msg = &new message_components($this->mbox);
+		$msg->fetch_structure($msg_number);
 
             $content = '';
@@ -1190,18 +1190,18 @@
             //----------------------------------------------//
 
-            if(!$this->has_cid)
-            {
+		if(!$this->has_cid)
+		{
                     $return['thumbs']    = $this->get_thumbs($images,$msg_number,$msg_folder);
-                    $return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
-            }
+			$return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
+		}
 
             switch (strtolower($structure->ctype_primary))
-            {
+		{
                 case 'text':
                         if(strtolower($structure->ctype_secondary) == 'x-pkcs7-mime')
                         {
-                                $return['body']='isCripted';
-                                return $return;
-                        }
+				$return['body']='isCripted';
+				return $return;
+			}
                         $attachment = array();
 
@@ -1210,20 +1210,20 @@
 
                         if(($msg_subtype == "html" || $msg_subtype == 'plain') && ($disposition != 'attachment'))
-                        {
-                                
+			{
+
 
                                 if(strtolower($msg_subtype) == 'plain')
-                                {
+					{ 
                                         $content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset'],false);
-										$content = str_replace(array('<', '>'), array(' #$<$# ', ' #$>$# '), $content);
-                                        $content = htmlentities($content);
+						$content = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $content ); 
+						$content = htmlentities( $content ); 
                                         $this->replace_links($content);
-                                        $content = str_replace(array(' #$&lt;$# ', ' #$&gt;$# '), array('&lt;', '&gt;'), $content);
-                                        $content = '<pre>' . $content . '</pre>';
-                                        $return[ 'body' ] = $content;
-                                        return $return;
-                                }
+						$content = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $content ); 
+						$content = '<pre>' . $content . '</pre>'; 
+                                                $return[ 'body' ] = $content;
+						return $return; 
+					} 
 								$content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset']);
-                        }
+				}
 
                     break;
@@ -1236,10 +1236,10 @@
                case 'message':
                     if(!is_array($structure->parts))
-                    {
+				{
                         $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
                         $content .= '<pre>'.htmlentities($this->decodeMailPart($structure->body, $structure->ctype_parameters['charset'],false)).'</pre>';
                         $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
-                    }
-                    else
+						}
+                                            else
                         $this->builderMsgBody($structure , $content,true);
 
@@ -1250,19 +1250,19 @@
                        $content .= '';
                     else 
-		    {
+								{ 
                        $content .= $this->functions->getLang('Message not supported') . '. ';
 		       $content .= $this->functions->getLang('Type') . ': ' . $structure->ctype_primary . '/' . $structure->ctype_secondary;
-		    }
+								} 
                     break;
-            }
+								} 
 
 		$params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");
 		$this->set_messages_flag($params);
 		$content = $this->process_embedded_images($images,$msg_number,$content, $msg_folder);
-	        $content = $this->replace_special_characters($content);
+		$content = $this->replace_special_characters($content);
                 $this->replace_links($content);
 		$return['body'] = &$content;
                 
-		return $return;    
+		return $return;
 	}
 
@@ -1391,16 +1391,16 @@
 		{
 			$body = quoted_printable_decode($body);
-           
-                }
-                else if ($encoding == 'base64')
-                {
-                        $body = base64_decode($body);
-                }
-                        // All other encodings are returned raw.
-                if (strtolower($charset) == "utf-8")
-                                return utf8_decode($body);
-                else
-                                return $body;
-                }
+
+			}
+    	else if ($encoding == 'base64')
+    	{
+        	$body = base64_decode($body);
+    	}
+		// All other encodings are returned raw.
+		if (strtolower($charset) == "utf-8")
+			return utf8_decode($body);
+    	else
+			return $body;
+	}
 
 				
@@ -1417,13 +1417,13 @@
 
             foreach ($images as $image)
-            {    
+		{
                 $image['cid'] = eregi_replace("<", "", $image['cid']);
                 $image['cid'] = eregi_replace(">", "", $image['cid']);
-                $body = eregi_replace("<br/>", "", $body);
+				$body = eregi_replace("<br/>", "", $body);
                 $body = str_replace("src=\"cid:".$image['cid']."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=".$image['pid']."\" ", $body);
                 $body = str_replace("src='cid:".$image['cid']."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=".$image['pid']."\" ", $body);
                 $body = str_replace("src=cid:".$image['cid'], " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=".$image['pid']."\" ", $body);   
-            }
-            return $body;
+			}
+		return $body;
 	}
 
@@ -1432,11 +1432,11 @@
 		// Suspected TAGS!
 		// $tag_list = Array('blink','object','meta','html','link','frame','iframe','layer','ilayer','plaintext','script','style','img','applet','embed','head','frameset','xml','xmp');
-		
+
 		// remove MS Office's proprietary tag
 		//$body = mb_ereg_replace('<!\-\-\[if [^!]* mso .*\]>.*<!\[endif\]\-\->', '', $body);
 		
-		// Layout problem: Change html elements 
-		// with absolute position to relate position, CASE INSENSITIVE. 
-		$body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body);
+		// Layout problem: Change html elements
+		// with absolute position to relate position, CASE INSENSITIVE.
+                $body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body);
 
 		// tags to be removed doe to security reasons
@@ -1446,8 +1446,8 @@
 			'applet','embed','frameset','xml','xmp'
 		);
-		
+
 		foreach($tag_list as $index => $tag) {
 			$body = @mb_eregi_replace("<$tag\\b[^>]*>(.*?)</$tag>", "<!-- TAG <$tag> Removed by ExpressoMail -->", $body); 
-		}
+			}
 		
 		//try to wrap CSS code instead of remove STYLE tags
@@ -1478,5 +1478,5 @@
 								//skip selecto '*' 
   	  	 	                    continue; 
-  	  	 	                } 
+		}
   	  	 	                                         
 							$selector = eregi_replace('[^#\.]*body.*', '', $selector); 
@@ -1497,5 +1497,5 @@
 				$body = str_replace($rest[1][$i],"<".$rest[2][$i].$rest[3][$i].$rest[7][$i].">",$body);
 		}
-		
+
 		/*
 		* Remove deslocamento a esquerda colocado pelo Outlook.
@@ -1506,21 +1506,21 @@
  	    $body = mb_ereg_replace("(<p[^>]*)(margin-left:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body); 
 	    //--------------------------------------------------------------------------------------------// 	
+
+		//$body = $this->replace_links($body);
+
+		//Remoção de tags <span></span> para correção de erro no firefox 
+		$body = mb_eregi_replace("<span><span>","",$body);
+		$body = mb_eregi_replace("</span></span>","",$body);
+                $body =  preg_replace("/text-indent:.*;/i","", $body);
 		
-		//$body = $this->replace_links($body);
-
-		//Remoção de tags <span></span> para correção de erro no firefox
-		$body = mb_eregi_replace("<span><span>","",$body); 
-		$body = mb_eregi_replace("</span></span>","",$body); 
-		$body = preg_replace("/text-indent:.*;/i","", $body);
+		//Correção para compatibilização com Outlook, ao visualizar a mensagem 
+		$body = mb_ereg_replace('<!--\[','<!-- [',$body); 
+		$body = mb_ereg_replace('&lt;!\[endif\]--&gt;', '<![endif]-->', $body);
 		
-		//Correção para compatibilização com Outlook, ao visualizar a mensagem
-		$body = mb_ereg_replace('<!--\[','<!-- [',$body);
-		$body = mb_ereg_replace('&lt;!\[endif\]--&gt;', '<![endif]-->', $body);
-			
 		return  "<div class=\"$wrapper_class\"><span>".$body.'</span></div>';
-	}	
-
-	
-	
+	}
+
+
+
 	function replace_links_callback($matches)  
  	{ 
@@ -1529,9 +1529,9 @@
  	    else 
 			$pref = $matches[3] = 'http'; 
- 	        
+
  	    return '<a href="'.$pref.'://'.$matches[4].$matches[5].'" target="_blank">'.$matches[4].$matches[5].'</a>'; 
  	} 
-	
-	
+
+
 	/**
 	* @license   http://www.gnu.org/copyleft/gpl.html GPL
@@ -1540,5 +1540,5 @@
 	*/
 	function replace_links(&$body)
-   	{
+		{ 
 		// Trata urls do tipo aaaa.bbb.empresa  
 		// Usadas na intranet.  
@@ -1546,10 +1546,10 @@
 		$replacement = '<a href="://$4$5" target="_blank">$4$5</a>'; 
  	    $body = preg_replace_callback($pattern,array( &$this, 'replace_links_callback'), $body);
-		// E-mail address in the text should create a new e-mail on ExpressoMail  
+		// E-mail address in the text should create a new e-mail on ExpressoMail
 		$pattern = '/( |<|&lt;|>)([A-Za-z0-9\.~?\/_=#\-]*@[A-Za-z0-9\.~?\/_=#\-]*)( |>|&gt;|<)/im'; 
-		$replacement = '$1<a href="mailto:$2">$2</a>$3'; 
-		$body = preg_replace($pattern, $replacement, $body); 
- 		             
-	} 
+		$replacement = '$1<a href="mailto:$2">$2</a>$3';
+		$body = preg_replace( $pattern, $replacement, $body );
+
+	}
 
 	function get_signature($msg, $msg_number, $msg_folder)
@@ -1667,9 +1667,9 @@
 	{
 
-            $thumbs_array = array();
-            $i = 0;
+		$thumbs_array = array();
+		$i = 0;
 
             foreach ($images as $x => $image)
-            {
+    	{
                  if($x && $x == 'names')
                     continue;
@@ -1679,8 +1679,8 @@
 				 $anchor = "<a class=\"expressomail-thumbs-link\" onMouseDown='save_image(event,this,\"".$image['type']."\")' href=\"".$href."\" onclick=\"window.open('".$href."','mywindow','width=700,height=600,scrollbars=yes');return false;\">". $img ."</a>";
                  $thumbs_array[] = $anchor; 
-                 $i++;
+    			$i++;
                
-            }
-            return $thumbs_array;
+    		}
+    	return $thumbs_array;
 	}
 
@@ -1702,12 +1702,12 @@
 	function delete_msgs($params)
 	{
-		
+
 		$folder = $params['folder'];
 		$folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
 		$msgs_number = explode(",",$params['msgs_number']);
 		$border_ID = $params['border_ID'];
-		
+
 		$return = array();
-		
+
 		if ($params['get_previous_msg']){
 			$return['previous_msg'] = $this->get_info_previous_msg($params);
@@ -1716,7 +1716,7 @@
 		}
 
-		//$mbox_stream = $this->open_mbox($folder);	 	
+		//$mbox_stream = $this->open_mbox($folder);
 	 	$mbox_stream = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => $this->parse_error(imap_last_error()))));
-		
+
 		foreach ($msgs_number as $msg_number)
 		{
@@ -1724,8 +1724,8 @@
 				$return['msgs_number'][] = $msg_number;
 		}
-		
+
 		$return['folder'] = $folder;
 		$return['border_ID'] = $border_ID;
-		
+
 		if($mbox_stream)
 			imap_close($mbox_stream, CL_EXPUNGE);
@@ -2484,20 +2484,20 @@
 	* @param     $forwarding_attachments anexos
 	*/
-	function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments)
-	{
-		//Build CID for embedded Images!!!
-		$pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
-		$cid_imgs = '';
-		preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
-		$cid_array = array();
-
-		foreach($cid_imgs[6] as $j => $val){
-			if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
-			{
-				$cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
-			}
-			$cid = $cid_array[$cid_imgs[4][$j].$val];
-
-			$mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
+	function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments) 
+	{ 
+		//      Build CID for embedded Images!!! 
+		$pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU'; 
+		$cid_imgs = ''; 
+		preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER); 
+		$cid_array = array(); 
+
+		foreach($cid_imgs[6] as $j => $val){ 
+			if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) ) 
+			{ 
+				$cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36); 
+			} 
+			$cid = $cid_array[$cid_imgs[4][$j].$val];  
+
+			$mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body); 
 
 			$count    = strlen($cid_imgs[6][$j]);
@@ -2514,49 +2514,49 @@
 			// The image is not in the same mail?
 			if ($msg_uid != $cid_imgs[4][$j]) 
-			{
-				$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
+			{ 
+				$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64'); 
 				$fileName = ($msg_uid != 'undefined') ? "image_".($j).".jpg" : $file_description[2];
-				$fileCode = "base64";
-				$fileType = "image/jpg";
-				$file_attached[0] = $cid_imgs[2][$j];
-				$file_attached[1] = $cid_imgs[4][$j];
-				$file_attached[2] = $fileName;
+				$fileCode = "base64"; 
+				$fileType = "image/jpg"; 
+				$file_attached[0] = $cid_imgs[2][$j]; 
+				$file_attached[1] = $cid_imgs[4][$j]; 
+				$file_attached[2] = $fileName; 
 				$file_attached[3] = '0.'.($j+1);
-				$file_attached[4] = 'base64';
-				$file_attached[5] = strlen($fileContent); //Size of file
+				$file_attached[4] = 'base64'; 
+				$file_attached[5] = strlen($fileContent); //Size of file 
 				$file_attached[6] = $cid_imgs[6][$j];
-				$return_forward[] = $file_attached;
+				$return_forward[] = $file_attached; 
 
  				if ($file_attached[3] == $file_description[3] || $msg_uid == 'undefined')
 					unset($forwarding_attachments[$position]);
 				
-			}
-			else
-			{
-				$fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
-				$fileName = $file_description[2];
-				$fileCode = $file_description[4];
+			} 
+			else 
+			{ 
+				$fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64'); 
+				$fileName = $file_description[2]; 
+				$fileCode = $file_description[4]; 
 				$file_description[3] = '0.'.($j+1);
 				$file_description[6] = $cid_imgs[6][$j];
-				$fileType = $this->get_file_type($file_description[2]);
+				$fileType = $this->get_file_type($file_description[2]); 
 				unset($forwarding_attachments[$position]);
-				if (!empty($file_description))
-				{
-					$file_description[5] = strlen($fileContent); //Size of file
-					$return_forward[] = $file_description;
-				}
-			}
+				if (!empty($file_description)) 
+				{ 
+					$file_description[5] = strlen($fileContent); //Size of file 
+					$return_forward[] = $file_description; 
+				} 
+			} 
 			$tempDir = '/tmp';
-			$file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";					
-			$f = fopen($tempDir.'/'.$file,"w");
-			fputs($f,$fileContent);
-			fclose($f);
-
-			if ($fileContent)
-				$mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);					
-		}
-			
-		return $return_forward;
-	}
+			$file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";                                        
+			$f = fopen($tempDir.'/'.$file,"w"); 
+			fputs($f,$fileContent); 
+			fclose($f); 
+
+			if ($fileContent) 
+				$mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType); 
+		}
+
+		return $return_forward; 
+	} 
 	function add_recipients_cert($full_address)
 	{
@@ -2874,34 +2874,34 @@
 	{
 
-        include_once("class.phpmailer.php");
+		include_once("class.phpmailer.php");
 		$mail = new PHPMailer();
 		include_once("class.db_functions.inc.php");
-		$toaddress    = $params['input_to'];
-		$ccaddress    = $params['input_cc'];
+		$toaddress = $params['input_to'];
+		$ccaddress = $params['input_cc'];
 		$ccoaddress = $params['input_cco'];
-        $return_receipt = $params['input_return_receipt'];
-        $is_important = $params['input_important_message'];
-		$subject      = $params['input_subject'];
-		$msg_uid      = $params['msg_id'];
-		$body         = $params['body'];
+		$return_receipt = $params['input_return_receipt'];
+		$is_important = $params['input_important_message'];
+		$subject = $params['input_subject'];
+		$msg_uid = $params['msg_id'];
+		$body = $params['body'];
 		$body = str_replace("%nbsp;","&nbsp;",$body);
 		$body = preg_replace("/\n/"," ",$body);
 		$body = preg_replace("/\r/","",$body);
 		$forwarding_attachments = $params['forwarding_attachments'];
-		$attachments  = $params['FILES'];
+		$attachments = $params['FILES'];
 		$return_files = $params['FILES'];
 
 		 
 		$folder = $params['folder'];
-		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");		
+		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
 		// Fix problem with cyrus delimiter changes.
-		// Dots in names: enabled/disabled.				
+		// Dots in names: enabled/disabled.
 		$folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
 		$folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
 		// End Fix.
-					
+
 		$mail->SaveMessageInFolder = $folder;
 		$mail->SMTPDebug = false;
-						
+
 		$mail->IsSMTP();
 		$mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
@@ -2909,10 +2909,10 @@
 		$mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
 		$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
-		
+
 		$mail->Sender = $mail->From;
 		$mail->SenderName = $mail->FromName;
 		$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
 		$mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
-				
+
 		$this->add_recipients("to", $toaddress, &$mail);
 		$this->add_recipients("cc", $ccaddress, &$mail);
@@ -2920,29 +2920,29 @@
 		$mail->IsHTML(true);
 		$mail->Body = $body;
-
+		
 		$return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
 		$imagesParts = array(); 
-		
+
 		foreach ($return_forward as $value)
 			$imagesParts[$value[6]] = $value[3]; 	
 
-		//Build Forwarding Attachments!!!	             
-		foreach($forwarding_attachments as $forwarding_attachment) 
-		{
-			$file_description = unserialize(rawurldecode($forwarding_attachment));
+	//	Build Forwarding Attachments!!!
+			foreach($forwarding_attachments as $forwarding_attachment)
+			{
+				$file_description = unserialize(rawurldecode($forwarding_attachment));
 			$file_description = array_values($file_description); 
  	                          	
- 	                        foreach($file_description as $i => $descriptor){                                 
+				foreach($file_description as $i => $descriptor){
   	  	 	                                $file_description[$i] = eregi_replace('\'*\'','',$descriptor); 
-  	  	 	                        } 
-  	  	 	                        $fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]); 
-  	  	 	                        $fileName = $file_description[2]; 
-  	  	 	                         
-  	  	 	                        $file_description[5] = strlen($fileContent); //Size of file 
-  	  	 	                        $return_forward[] = $file_description; 
-  	  	 	                 
-  	  	 	                        $mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2])); 
-		}
-		
+				}
+				$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
+				$fileName = $file_description[2];
+
+				$file_description[5] = strlen($fileContent); //Size of file
+				$return_forward[] = $file_description;
+
+					$mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
+			}
+
 		if ((count($return_forward) > 0) && (count($return_files) > 0))
 		{
@@ -2951,8 +2951,8 @@
 		else if (count($return_files) < 1)
 		{
-			$return_files = $return_forward;
-		}
-
-		//Build Uploading Attachments!!!
+				$return_files = $return_forward;
+		}
+
+		//	Build Uploading Attachments!!!
 		$sizeof_attachments = count($attachments);
 		if ($sizeof_attachments)
@@ -2965,16 +2965,16 @@
 					switch ($image_type)
 					{
-						// Do not corrupt animated gif
-						//case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
+					// Do not corrupt animated gif
+					//case 1: $image_big = imagecreatefromgif($attach['tmp_name']);break;
 						case 2: 
 							$image_big = imagecreatefromjpeg($attach['tmp_name']);  break;
 						case 3: 
 							$image_big = imagecreatefrompng($attach['tmp_name']); break;
-						case 6:
-							require_once("gd_functions.php");
-							$image_big = imagecreatefrombmp($attach['tmp_name']); break;
-						default:
-							$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
-							break;
+					case 6:
+						require_once("gd_functions.php");
+						$image_big = imagecreatefrombmp($attach['tmp_name']); break;
+					default:
+						$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
+						break;
 					}
 					header('Content-type: image/jpeg');
@@ -3008,20 +3008,20 @@
 					$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
 				
-			}
-		}
-		
+				}
+		}
+
 		if(!empty($mail->AltBody))
-                    $mail->ContentType = "multipart/alternative";
+            $mail->ContentType = "multipart/alternative";
 
 		$mail->error_count = 0; // reset errors
 		$mail->SetMessageType();
 		$header = $mail->CreateHeader();
-		$body   = $mail->CreateBody(); 
-
-		$mbox_stream = $this->open_mbox($folder);	
-		$new_header  = str_replace("\n", "\r\n", $header);
-		$new_body    = str_replace("\n", "\r\n", $body);
+		$body = $mail->CreateBody();
+
+		$mbox_stream = $this->open_mbox($folder);
+		$new_header = str_replace("\n", "\r\n", $header);
+		$new_body = str_replace("\n", "\r\n", $body);
 		$return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
-		$status      = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
+		$status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
 		$return['msg_no'] = $status->uidnext - 1;
 		$return['folder_id'] = $folder;
@@ -3037,18 +3037,18 @@
 				if (array_key_exists("name", $_attachment))
 				{
-					unset($return_files[$index]);
-					$return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
-				}
-				else
-				{
-					unset($return_files[$index]);
-					$return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
-				}
-			}
-		}
-		
+				unset($return_files[$index]);
+				$return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
+			}
+			else
+			{
+				unset($return_files[$index]);
+				$return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
+			}
+		}
+		}
+
 		$return['files'] = serialize($return_files);
 		$return["subject"] = $subject;
-				
+
 		if (!$return['append'])
 			$return['append'] = imap_last_error();
@@ -3569,15 +3569,15 @@
 	 	"SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
 	}
-	
-	function make_search_date($date,$before = false){ 
+
+        function make_search_date($date,$before = false){
 
             //TODO: Adaptar a data de acordo com o locale do sistema.
             list($day,$month,$year) = explode("/", $date);
-			$before?$day=(int)$day+1:$day=(int)$day; 
- 	        $timestamp = mktime(0,0,0,(int)$month,$day,(int)$year); 
- 	        $search_date = date('d-M-Y',$timestamp);
+            $before?$day=(int)$day+1:$day=(int)$day;
+            $timestamp = mktime(0,0,0,(int)$month,$day,(int)$year);
+            $search_date = date('d-M-Y',$timestamp);
             return $search_date;
 
-    }
+        }
 
 	function search_msg( $params = false )
@@ -3623,8 +3623,8 @@
 							if(trim($filter_array[0]) == 'BEFORE' )
 							{
-								$filter .= '"'.$this->make_search_date($filter_array[1],true).'"'; 
- 		                    }else{ 
-								$filter .= '"'.$this->make_search_date($filter_array[1]).'"'; 
- 	                        } 
+                                                            $filter .= '"'.$this->make_search_date($filter_array[1],true).'"';
+							}else{
+                                                            $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
+                                                        }
 						}
 					}
@@ -3671,7 +3671,7 @@
 								$elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream); 
 								$elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ); 
-								$elem['uid'] = $new_search; 
-								/* compare dates in ordering */ 
-								$elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);  
+								$elem['uid'] = $new_search;
+                                                                /* compare dates in ordering */
+								$elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
 								$retorno[] = $elem; 
 							}
@@ -3717,6 +3717,6 @@
 							$elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream); 
 							$elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ); 
-							$elem['uid'] = $new_search; 
-							/* compare dates in ordering */ 
+							$elem['uid'] = $new_search;
+                                                        /* compare dates in ordering */
 							$elem['udatecomp'] = substr ($elem['udate'], -4) ."-". substr ($elem['udate'], 3, 2) ."-". substr ($elem['udate'], 0, 2);
 							$retorno[] = $elem;
@@ -4070,5 +4070,5 @@
 	function get_header($msg_number)
 	{
-        $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
+                $header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
 		if (!is_object($header))
 			return false;
@@ -4106,5 +4106,5 @@
     		$f = fopen($file,"w");
         	fputs($f,base64_encode($source));
-            fclose($f);           
+            fclose($f);
 		   $command = "python ".$_SESSION['rootPatch']."/expressoMail1_2/imap.py ".escapeshellarg($imap_server)." ".escapeshellarg($imap_port)." ".escapeshellarg($username)." ".escapeshellarg($password)." ".escapeshellarg($timestamp)." ".escapeshellarg($folder)." ".escapeshellarg($file);
             $return['command']=exec(escapeshellcmd($command));
