Index: sandbox/2.2.0.2/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- sandbox/2.2.0.2/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 4413)
+++ sandbox/2.2.0.2/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 4416)
@@ -84,13 +84,9 @@
 			return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
 		}
-		// This error is returned from Postfix.
-		elseif(strstr($error,'message file too big')) {
-			return str_replace("%1",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'],$this->functions->getLang('The size of this message has exceeded  the limit (%1B).'));
-		}
 		elseif(strstr($error,'virus')) {
 			return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Your message was rejected by antivirus. Perhaps your attachment has been infected."));
 		}
 		// This condition verifies if SESSION is expired.
-		elseif(!count($_SESSION))
+		elseif(!count($_SESSION))			
 			return "nosession";
 
@@ -141,5 +137,5 @@
 				{
 					$temp = $this->get_info_head_msg($msg_number);
-                                        $temp['msg_sample'] = $this->get_msg_sample($msg_number,$folder);
+					//$temp['msg_sample'] = $this->get_msg_sample($msg_number,$folder);
 					if(!$temp)
 						return false;
@@ -283,43 +279,56 @@
 	}
 
+	/**
+	* 
+	* @license    http://www.gnu.org/copyleft/gpl.html GPL
+	* @param      string $string String a ser decodificada
+	* @return     string
+	* @todo       Verificar a possibilidade de se utilizar a função iconv_mime_decode, que é capaz de identificar a codificação por si só, mas que pode ser interpretada de forma diversa dependendo da implementação do sistema
+	* @todo       Executar testes suficientes para validar a funçao iconv_mime_decode em substituição à este método decode_string
+	*/
 	function decode_string($string)
-	{
-
-		if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
-		{
-			$return = '';
-			$tmp = imap_mime_header_decode($string);
-			foreach ($tmp as $tmp1)
-				$return .= $this->htmlspecialchars_encode($tmp1->text);
-
-			$return = str_replace("\t", "", $return); 
-			return $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);
-  				}
-  			}
-	  		return $decoded;
-		}
-		else
-			return $this->htmlspecialchars_encode($string);
-	}
+    {    
+        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)
+            {
+                $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);
+                  }
+              }
+
+              return str_replace("\t", "", $decoded);
+        }
+        else if (eregi('=?', $string))
+        {
+            return iconv_mime_decode($string);
+        }
+
+        return $this->htmlspecialchars_encode($string);
+    }
 	/**
 	* Função que importa arquivos .eml exportados pelo expresso para a caixa do usuário. Testado apenas
@@ -566,32 +575,244 @@
 		return $return;
 	}
-
+	
+	function getRawHeader($msg_number)
+    {
+		return imap_fetchheader($this->mbox, $msg_number, FT_UID);
+	}
+	
+	function getRawBody($msg_number)
+    {
+		return  imap_body($this->mbox, $msg_number, FT_UID);	
+	}
+
+	function builderMsgHeader($msg)
+    {
+
+  
+            $fromMail =  str_replace('<','', str_replace('>','',$msg->headers['from']));
+            $tosMails =  str_replace('<','', str_replace('>','',$msg->headers['to']));
+
+            $tos = explode(',',$tosMails);
+            $to = '';
+            foreach ($tos as $value)
+            {
+                $to .= '<a href="mailto:'.str_replace(' ','',$value).'">'.$value.'</a>, ';
+            }
+
+            $header = '
+                <table style="margin: 2px; border: 1px solid black; background: none repeat scroll 0% 0% rgb(234, 234, 234);">
+                <tbody>
+                <tr><td><b>'.$this->functions->getLang('Subject').':</b></td><td>'.$msg->headers['subject'].'</td></tr>
+                <tr><td><b>'.$this->functions->getLang('From').':</b></td><td><a href="mailto:'.$fromMail.'">'.$fromMail.'</a></td></tr>
+                <tr><td><b>'.$this->functions->getLang('Date').':</b></td><td>'.$msg->headers['date'].'</td></tr>
+                <tr><td><b>'.$this->functions->getLang('To').':</b></td><td>'.$to.'</td></tr>
+                </tbody>
+                </table>
+                <br />'
+            ;
+
+          return $header;
+    }
+	
+	/**
+        * Constroe o corpo da msg direto na variavel de conteudo
+        * @param Mail_mimeDecode $structure
+        * @param <type> $content Ponteiro para Variavel de conteudo da msg
+        */
+        function builderMsgBody($structure , &$content , $printHeader = false)
+        {
+            if(strtolower($structure->ctype_primary) == 'multipart' && strtolower($structure->ctype_secondary) == 'alternative')
+            {
+                $numParts = count($structure->parts) - 1;
+
+                for($i = $numParts; $i >= 0; $i--)
+                {
+                    $part = $structure->parts[$i];
+
+                    switch (strtolower($part->ctype_primary))
+                    {
+                       case 'text':
+                           $disposition = strtolower($part->disposition);
+                           if($disposition != 'attachment')
+                           {
+                                if(strtolower($part->ctype_secondary) == 'html')
+                                {
+                                   if($printHeader)
+                                        $content .= $this->builderMsgHeader($part);
+
+                                   $content .= $this->decodeMailPart($part->body,$part->ctype_parameters['charset']);
+                                }
+
+                                if(strtolower($part->ctype_secondary) == 'plain' )
+                                {
+                                  if($printHeader)
+                                      $content .= $this->builderMsgHeader($part);
+
+                                   $content .= '<pre>'.$this->decodeMailPart($part->body,$part->ctype_parameters['charset']).'</pre>';
+                                }
+
+
+
+                           }
+
+                            $i = -1;
+                            break;
+
+                       case 'multipart':
+
+                            if($printHeader)
+                               $content .= $this->builderMsgHeader($part);
+
+                            $this->builderMsgBody($part,$content);
+
+                            $i = -1;
+                            break;
+
+                       case 'message':
+
+                            if(!is_array($part->parts))
+                            {
+                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
+                                $content .= '<pre>'. $this->decodeMailPart($part->body, $structure->ctype_parameters['charset']).'</pre>';
+                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
+                            }
+                            else
+                                $this->builderMsgBody($part,$content,true);
+
+                            $i = -1;
+                            break;
+                    }
+                }
+            }
+            else
+            {
+                foreach ($structure->parts  as $index => $part)
+                {
+                   switch (strtolower($part->ctype_primary))
+                   {
+                       case 'text':
+                           
+                           $disposition = strtolower($part->disposition);
+                           if($disposition != 'attachment')
+                           {
+                                if(strtolower($part->ctype_secondary) == 'html')
+                                {
+                                   if($printHeader)
+                                        $content .= $this->builderMsgHeader($part);
+
+                                   $content .= $this->decodeMailPart($part->body,$part->ctype_parameters['charset']);
+                                }
+
+                                if(strtolower($part->ctype_secondary) == 'plain')
+                                {
+                                  if($printHeader)
+                                      $content .= $this->builderMsgHeader($part);
+
+                                   $content .= '<pre>'.$this->decodeMailPart($part->body,$part->ctype_parameters['charset']).'</pre>';
+                                }
+
+                        
+                           }
+                            break;
+                       case 'multipart':
+
+                            if($printHeader)
+                               $content .= $this->builderMsgHeader($part);
+
+                            $this->builderMsgBody($part,$content);
+
+                            break;
+                       case 'message':
+
+                            if(!is_array($part->parts))
+                            {
+                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
+                                $content .= '<pre>'. $this->decodeMailPart($part->body, $structure->ctype_parameters['charset']).'</pre>';
+                                $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
+                            }
+                            else
+                                $this->builderMsgBody($part,$content,true);
+                        break;
+                 }
+               }
+            }
+        }
+	
+	
+	
+		function get_msg_sample($msg_number)
+	{
+
+		$return = ""; 
+		if( (!isset($this->prefs['preview_msg_subject']) || ($this->prefs['preview_msg_subject'] != "1")) &&
+			(!isset($this->prefs['preview_msg_tip']    ) || ($this->prefs['preview_msg_tip']     != "1")) )
+		{ 
+			$return['body'] = ""; 
+			return $return; 
+		} 
+
+		include_once("class.message_components.inc.php");
+		$msg = &new message_components($this->mbox);
+		$msg->fetch_structure($msg_number);  
+
+		if(!$msg->structure[$msg_number]->parts)
+		{
+			$content = '';
+			if (strtolower($msg->structure[$msg_number]->subtype) == "plain" || strtolower($msg->structure[$msg_number]->subtype) == "html")
+			{
+				$content = $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID|FT_PEEK), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
+			}
+		}
+		else
+		{
+			foreach($msg->pid[$msg_number] as $values => $msg_part)
+			{
+
+				$file_type = strtolower($msg->file_type[$msg_number][$values]);
+				if($file_type == "text/plain" || $file_type == "text/html") {
+					$content = $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID|FT_PEEK), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
+					break;
+				}
+			}
+		}
+		$content = $this->replace_special_characters($content);
+		$tags_replace = array("<br>","<br/>","<br />");
+		$content = str_replace($tags_replace," ", $content);
+		$content = strip_tags($content);
+		$content = str_replace(array("{","}","&nbsp;"), " ", $content);
+		$content = trim($content);
+		$content = html_entity_decode(substr($content,0,300));
+		$content != "" ? $return['body'] = " - " . $content: $return['body'] = "";
+		return $return;
+	}
+	
+	
 	function get_info_msg($params)
 	{
 		$return = array();
 		$msg_number = $params['msg_number'];
-		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_folder = urldecode($params['msg_folder']);
-
+		
+		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 = ''; 
+		} 
+		
 		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();
@@ -603,24 +824,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'];
-		}
-		
-		$flag = preg_match('/importance *: *(.*)\r/i', $header_, $importance);
-		$return['Importance'] = ($flag == 0) ? "Normal" : $importance[1];
-
+            $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;
 
@@ -628,36 +845,34 @@
 			$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;
-
-		$offset = $this->functions->CalculateDateOffset();
-		$msgTimestamp = $header->udate + $offset;
-
-		$date_msg = gmdate("d/m/Y",$msgTimestamp);
-//		if (date("d/m/Y") == $date_msg)
-//			$return['udate'] = $header->udate;
-//		else
-		$return['udate'] = $header->udate;
-
-		$return['msg_day'] = $date_msg;
-		$return['msg_hour'] = gmdate("H:i",$msgTimestamp);
-
+	
+		$date_msg = gmdate("d/m/Y",$header->udate);
+		if (date("d/m/Y") == $date_msg)
+			$return['udate'] = gmdate("H:i",$header->udate);
+		else
+			$return['udate'] = $date_msg;
+		
+		$return['msg_day'] = $date_msg; 
+		$return['msg_hour'] = gmdate("H:i",$header->udate);
+		
 		if (date("d/m/Y") == $date_msg) //no dia
 		{
-			$return['fulldate'] = gmdate("d/m/Y H:i",$msgTimestamp);
-			$return['smalldate'] = gmdate("H:i",$msgTimestamp);
-
-			$timestamp_now = strtotime("now");
-			$timestamp_msg_time = $msgTimestamp;
-			// $timestamp_now and $timestamp_msg_time are GMT.
+			$return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
+			$return['smalldate'] = gmdate("H:i",$header->udate);
+
+			$timestamp_now = strtotime("now");  			
+			$timestamp_msg_time = $header->udate;
+			// $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ. 
 			// The variable $timestamp_diff is calculated without MailDate TZ.
-			$timestamp_diff = $timestamp_now - $timestamp_msg_time;
-
+			$pdate = date_parse($header->MailDate);
+			$timestamp_diff = $timestamp_now - $timestamp_msg_time  + ($pdate['zone']*(-60));
+			
 			if (gmdate("H",$timestamp_diff) > 0)
 			{
@@ -678,8 +893,8 @@
 		}
 		else{
-			$return['fulldate'] = gmdate("d/m/Y H:i",$msgTimestamp);
-			$return['smalldate'] = gmdate("d/m/Y",$msgTimestamp);
-		}
-
+			$return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
+			$return['smalldate'] = gmdate("d/m/Y",$header->udate);
+		}
+		
 		$from = $header->from;
 		$return['from'] = array();
@@ -695,8 +910,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);
@@ -743,5 +958,9 @@
 			$return['toaddress2'] = $this->del_last_two_caracters($return['toaddress2']);
 		}
-
+		else
+		{
+			$return['toaddress2'] = "&lt;Empty&gt;";
+		}	
+		
 		$cc = $header->cc;
 		$return['cc'] = "";
@@ -771,5 +990,5 @@
 		{
 			$return['cc'] = "";
-		}
+		}	
 
 		##
@@ -778,5 +997,6 @@
 		# @BRIEF Adding the BCC field.
 		##
-		$bcc = $header->bcc;
+                
+                $bcc = $header->bcc;
 		$return['bcc'] = "";
 		if (!empty($bcc))
@@ -805,5 +1025,5 @@
 		{
 			$return['bcc'] = "";
-		}
+		}	
 
 		$reply_to = $header->reply_to;
@@ -835,302 +1055,163 @@
 		$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['timestamp'] = $header->udate;
 		$return['login'] = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];//$GLOBALS['phpgw_info']['user']['account_id'];
 		$return['reply_toaddress'] = $header->reply_toaddress;
-                
-                if($return_get_body['body']=='isSigned'){
-                    imap_close($this->mbox);
-                    $new_mail = $this->show_decript($return_get_body,$dec = 1);
-                    //$new_mail['signature'] =  $return_get_body['signature'];
-                    $return['body'] 		= $new_mail['body'];
-                    $return['attachments'] 	= $new_mail['attachments'];
-                    $return['thumbs'] 		= $new_mail['thumbs'];
-                    $return['folder'] = $return['msg_folder'];
-                    $return['original_ID'] =  $return['msg_number'];
-                    $return['msg_folder']	= 'INBOX'.$this->imap_delimiter.'decifradas';
-                    $return['msg_number']	= $new_mail['msg_no'];
-                    //$return['signature']	= $return_get_body['signature'];
-		}
+	
 		return $return;
 	}
 
-	function get_msg_sample($msg_number)
-	{
-
-		$return = ""; 
-		if( (!isset($this->prefs['preview_msg_subject']) || ($this->prefs['preview_msg_subject'] != "1")) &&
-			(!isset($this->prefs['preview_msg_tip']    ) || ($this->prefs['preview_msg_tip']     != "1")) )
-		{ 
-			$return['body'] = ""; 
-			return $return; 
-		} 
-
-		include_once("class.message_components.inc.php");
-		$msg = &new message_components($this->mbox);
-		$msg->fetch_structure($msg_number);  
-
-		if(!$msg->structure[$msg_number]->parts)
-		{
-			$content = '';
-			if (strtolower($msg->structure[$msg_number]->subtype) == "plain" || strtolower($msg->structure[$msg_number]->subtype) == "html")
-			{
-				$content = $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID|FT_PEEK), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
-			}
-		}
-		else
-		{
-			foreach($msg->pid[$msg_number] as $values => $msg_part)
-			{
-
-				$file_type = strtolower($msg->file_type[$msg_number][$values]);
-				if($file_type == "text/plain" || $file_type == "text/html") {
-					$content = $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID|FT_PEEK), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
-					break;
-				}
-			}
-		}
-		$content = $this->replace_special_characters($content);
-		$tags_replace = array("<br>","<br/>","<br />");
-		$content = str_replace($tags_replace," ", $content);
-		$content = strip_tags($content);
-		$content = str_replace(array("{","}","&nbsp;"), " ", $content);
-		$content = trim($content);
-		$content = html_entity_decode(substr($content,0,300));
-		$content != "" ? $return['body'] = " - " . $content: $return['body'] = "";
-		return $return;
-	}
-
+		/**
+         * Decodifica uma part da mensagem para iso-8859-1
+         * @param <type> $part parte do email
+         * @param <type> $encode codificação da parte
+         * @return <type> string decodificada
+         */
+        function decodeMailPart($part, $encode)
+        {
+            switch (strtolower($encode))
+            {
+                case 'iso-8859-1':
+                    return $part;
+                    break;
+
+                case 'utf-8':
+                    return utf8_decode($part);
+                    break;
+
+                default:
+                    return mb_convert_encoding($part, 'iso-8859-1');
+                    break;
+            }
+        }
+	
+	
 	function get_body_msg($msg_number, $msg_folder)
 	{
-		include_once("class.message_components.inc.php");
-		$msg = &new message_components($this->mbox);
-		$msg->fetch_structure($msg_number);
-		$return = array();
-		$return['attachments'] = $this-> download_attachment($msg,$msg_number);
-		if(!$this->has_cid)
-		{
-			$return['thumbs']  = $this->get_thumbs($msg,$msg_number,urlencode($msg_folder));
-			$return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
-		}
-
-		if(!$msg->structure[$msg_number]->parts) //Simple message, only 1 piece
-		{
-			if((strtolower($msg->structure[$msg_number]->subtype) == 'x-pkcs7-mime') && (count($return['signature']) == 0 ) ){
-				$return['body']='isCripted';
-				return $return;
-			}
-
-			$attachment = array(); //No attachments
-
-			if (strtolower($msg->structure[$msg_number]->subtype) == "x-pkcs7-mime")
-			{
-                                $return['body']='isSigned';
-				$headers = imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number));
-				$header_body_array = explode('MIME-Version: 1.0', $headers);
-				$show_pkcs7 = $header_body_array[0] . 'MIME-Version: 1.0' . chr(0x0D) .chr(0x0A). $return['signature'][0];
-				$return['source']=$show_pkcs7;
-				array_shift($return['signature']);
-				$return['signature'];
-				//$return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
-				imap_close($this->mbox);
+			/*
+             * Requires of librarys
+             */
+            require_once $_SESSION['rootPath'].'/library/mime/mimePart.php';
+            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");
+            //--------------------------------------------------------------------//
+
+            $return = array();
+
+            $msg = &new message_components($this->mbox);
+            $msg->fetch_structure($msg_number);
+
+            $content = '';
+
+            $rawMessageData = $this->getRawHeader($msg_number).$this->getRawBody($msg_number);
+
+            $decoder = new Mail_mimeDecode($rawMessageData);
+
+            $params['include_bodies'] = true;
+            $params['decode_bodies']  = true;
+            $params['decode_headers'] = true;
+            $structure = $decoder->decode($params);
+
+            /*
+             * Inicia Gerenciador de Anexos
+             */
+            $attachmentManager = new attachment();
+            $attachmentManager->setStructure($structure);
+            //----------------------------------------------//
+
+            /*
+             * Monta informações dos anexos para o cabecarios
+             */
+            $attachments = $attachmentManager->getAttachmentsInfo();
+            $return['attachments'] = $attachments;
+            //----------------------------------------------//
+
+            /*
+            * Monta informações das imagens
+            */
+            $images = $attachmentManager->getEmbeddedImagesInfo();
+            //----------------------------------------------//
+
+            if(!$this->has_cid)
+            {
+                    $return['thumbs']    = $this->get_thumbs($images,$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;
-			}
-
-			$content = ''; 
-			// If simple message is subtype 'html' or 'plain', then get content body. 
-			if(strtolower($msg->structure[$msg_number]->subtype) == "html" ||  
-				strtolower( $msg -> structure[ $msg_number ] -> subtype ) == 'plain'){ 
-
-					$content = $this->decodeBody( 
-						imap_body( $this -> mbox, $msg_number, FT_UID ), 
-						$msg -> encoding[ $msg_number ][ 0 ], 
-						$msg -> charset[ $msg_number ][ 0 ] 
-					); 
-
-					if ( strtolower( $msg -> structure[ $msg_number ] -> subtype ) == 'plain' ) 
-					{ 
-						$content = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $content ); 
-						$content = htmlentities( $content ); 
-						$content = $this -> replace_links( $content ); 
-						$content = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $content ); 
-						$content = '<pre>' . $content . '</pre>'; 
-						$content = str_replace("\x00", '', $content);
-                                                $return[ 'body' ] = $content;
-
-						return $return; 
-					} 
-				}
-		}
-		else
-		{ //Complicated message, multiple parts
-			$html_body = '';
-			$content = '';
-			$has_multipart = true;
-                        $is_alternative = false;
-			$this->has_cid = false;
-                        $alternative_content;
-                        array_shift($return['signature']);
-			if (strtolower($msg->structure[$msg_number]->subtype) == "related")
-				$this->has_cid = true;
-
-			if (strtolower($msg->structure[$msg_number]->subtype) == "alternative") {
-                                $is_alternative = true;
-				$show_only_html = false;
-				foreach($msg->pid[$msg_number] as $values => $msg_part) {
-					$file_type = strtolower($msg->file_type[$msg_number][$values]);
-					if($file_type == "text/html")
-						$show_only_html = true;
-				}
-			}
-			else
-				$show_only_html = false;
-
-			foreach($msg->pid[$msg_number] as $values => $msg_part)
-			{
-
-				$file_type = strtolower($msg->file_type[$msg_number][$values]);
-				if($file_type == "message/rfc822" || $file_type == "multipart/alternative") 
-				{ 
-					// Show only 'text/html' part, when message/rfc822 format contains 'text/plain' alternative part. 
-					if(array_key_exists($values+1, $msg->file_type[$msg_number]) && 
-						strtolower($msg->file_type[$msg_number][$values+1]) == 'text/plain' && 
-						array_key_exists($values+2, $msg->file_type[$msg_number]) && 
-						strtolower($msg->file_type[$msg_number][$values+2]) == 'text/html') { 
-							$has_multipart = false; 
-						} 
-				} 	
-
-				if(($file_type == "text/plain"
-					|| $file_type == "text/html")
-						&& $file_type != 'attachment')
-				{
-
-				       
-				       if($this->prefs['max_msg_size'] == "1")
-					    $max_size = 1048576;
-					else
-					    $max_size = 102400;
-
-					if($file_type == "text/plain" && !$show_only_html && $has_multipart)
-					{
-						// if TXT file size > 100kb, then it will not expand.
-						if(!($file_type == "text/plain" && $msg->fsize[$msg_number][$values] > $max_size)) {
-							 $content .= htmlentities($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values])); 
-							$content = '<pre>' . $content . '</pre>';
-						}
-					}
-					// if HTML attachment file size > 300kb, then it will not expand.
-					else if($file_type == "text/html"  && $msg->fsize[$msg_number][$values] < $max_size*3)
-					{
-                                            if ($is_alternative)
-                                            {
-                                                $alternative_content = $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
-                                            }
-                                            else
-                                                {
-                                                    $content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
-                                                    $show_only_html = true;
-                                                }
-					}
-				}
-				 else if($file_type == "message/delivery-status" || $file_type == "message/feedback-report"){ 
-					$content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
-					$content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]); 
-                    $content = '<pre>' . $content . '</pre>'; 
-				}
-				else if($file_type == "message/rfc822" || $file_type == "text/rfc822-headers"){
-
-					include_once("class.imap_attachment.inc.php");
-					$att = new imap_attachment();
-					$attachments =  $att -> get_attachment_info($this->mbox,$msg_number);
-					if($attachments['number_attachments'] > 0) { 
-						foreach($attachments ['attachment'] as $index => $attachment) 
-						{ 
-							if ( in_array( strtolower( $attachment[ 'type' ] ), array( 'delivery-status', 'rfc822', 'rfc822-headers', 'plain' ) ) ) 
-							{ 
-								$obj = imap_rfc822_parse_headers( imap_fetchbody( $this -> mbox, $msg_number, $msg_part, FT_UID ), $msg -> encoding[ $msg_number ][ $values ] ); 
-
-								$content .= '<hr align="left" width="95%" style="border:1px solid #DCDCDC">'; 
-								$content .= '<br><table  style="margin:2px;border:1px solid black;background:#EAEAEA">'; 
-
-								$content .= '<tr><td><b>' . $this->functions->getLang("Subject") 
-									. ':</b></td><td>' .$this->decode_string($obj->subject) . '</td></tr>'; 
-
-								$content .= '<tr><td><b>' . $this -> functions -> getLang( 'From' ) . ':</b></td><td>' 
-									. $this -> replace_links( $this -> decode_string( $obj -> from[ 0 ] -> mailbox . '@' . $obj -> from[ 0 ] -> host) ) 
-									. '</td></tr>'; 
-
-								$content .= '<tr><td><b>' . $this->functions->getLang("Date") . ':</b></td><td>' . $obj->date . '</td></tr>'; 
-
-								$content .= '<tr><td><b>' . $this -> functions -> getLang( 'TO' ) . ':</b></td><td>' 
-									. $this -> replace_links( $this -> decode_string( $obj -> to[ 0 ] -> mailbox . '@' . $obj -> to[ 0 ] -> host ) ) 
-									. '</td></tr>'; 
-
-								if ( $obj->cc ) 
-									$content .= '<tr><td><b>' . $this -> functions -> getLang( 'CC' ) . ':</b></td><td>' 
-										. $this -> replace_links( $this -> decode_string( $obj -> cc[ 0 ] -> mailbox . '@' . $obj -> cc[ 0 ] -> host ) ) 
-										. '</td></tr>'; 
-
-								$content .= '</table><br>'; 
-
-
-								$id = ( ( strtolower( $attachment[ 'type' ] ) == 'delivery-status' ) ? false : true ); 
-								if ( strtolower( $msg->structure[$msg_number]->parts[1]->parts[0]->subtype ) == 'plain' ) 
-								{ 
-									$id = !$id; 
-									if ( $msg->structure[$msg_number]->parts[1]->parts[0]->encoding == 4 ) 
-										$msg->encoding[ $msg_number ][ $values ] = 'quoted-printable'; 
-								} 
-
-								$body = $this->decodeBody( 
-									imap_fetchbody( 
-										$this->mbox, 
-										$msg_number, 
-										( $attachment['part_in_msg'] + ( ( int ) $id ) ) . ".1", 
-										FT_UID 
-									), 
-									$msg->encoding[ $msg_number ][ $values ], 
-									$msg->charset[ $msg_number ][ $values ] 
-								); 
-
-								if ( strtolower( $msg->structure[$msg_number]->parts[1]->parts[0]->subtype ) == 'plain' ) 
-								{ 
-									$body = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $body ); 
-									$body = htmlentities( $body ); 
-									$body = $this -> replace_links( $body ); 
-									$body = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $body ); 
-									$body = '<pre>' . $body . '</pre>'; 
-								} 
-
-								$content .= $body; 
-								break; 
-							}
-						}
-					}
-				}
-			}
-                        if ($is_alternative && !empty($alternative_content))
+                        }
+                        $attachment = array();
+
+                        $msg_subtype = strtolower($structure->ctype_secondary);
+                        $disposition = strtolower($structure->disposition);
+
+                        if(($msg_subtype == "html" || $msg_subtype == 'plain') && ($disposition != 'attachment'))
                         {
-                            $content .= $alternative_content;
+                                $content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset']) ;
+
+                                if(strtolower($msg_subtype) == 'plain')
+                                {
+                                        $content = str_replace(array('<', '>'), array(' #$<$# ', ' #$>$# '), $content);
+                                        $content = htmlentities($content);
+                                        $content = $this -> replace_links($content);
+                                        $content = str_replace(array(' #$&lt;$# ', ' #$&gt;$# '), array('&lt;', '&gt;'), $content);
+                                        $content = '<pre>' . $content . '</pre>';
+                                        $return[ 'body' ] = $content;
+                                        return $return;
+                                }
                         }
-			if($file_type == "text/plain" && ($show_only_html &&  $msg_part == 1) ||  (!$show_only_html &&  $msg_part == 3)){
-				if(strtolower($msg->structure[$msg_number]->subtype) == "mixed" &&  $msg_part == 1)
-					$content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
-				else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
-					$content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));
-			}
-		}
-		// Force message with flag Seen (imap_fetchbody not works correctly)
+
+                        
+                        
+
+                    break;
+               case 'multipart':
+
+                    $this-> builderMsgBody($structure , $content);
+
+                    break;
+
+               case 'message':
+
+                    if(!is_array($structure->parts))
+                    {
+                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
+                        $content .= '<pre>'.$this->decodeMailPart($structure->body, $structure->ctype_parameters['charset']).'</pre>';
+                        $content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
+                    }
+                    else
+                        $this->builderMsgBody($structure , $content,true);
+
+                        break;
+
+                default:
+
+                        if(count($attachments) > 0)
+                            $content .= '';
+                        else
+                            $content .= $this->functions->getLang('Message does not supported').'. '.$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($msg,$msg_number,$content, $msg_folder);
-		$content = $this->replace_special_characters($content);
-		$return['body'] = $content;
-		return $return;
+		$content = $this->process_embedded_images($images,$msg_number,$content, $msg_folder);
+	        $content = $this->replace_special_characters($content);
+                $this->replace_links($content);
+		$return['body'] = &$content;
+                
+		return $return;    
 	}
 
@@ -1255,59 +1336,34 @@
 	function decodeBody($body, $encoding, $charset=null)
 	{
-		/**
-		* replace e-mail by anchor.
-		*/
-		// HTML Filter
-		//$body = preg_replace("#(^|[\n ])([a-z0-9&\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=# onclick=\"javascript:new_message('new_by_message', '\\2@\\3')\">\\2@\\3</a>", $body);
-    	//$body = str_replace("\r\n", "\n", $body);
+
 		if ($encoding == 'quoted-printable')
 		{
-			/*
-
-			for($i=0;$i<256;$i++) {
-				$c1=dechex($i);
-				if(strlen($c1)==1){$c1="0".$c1;}
-				$c1="=".$c1;
-				$myqprinta[]=$c1;
-				$myqprintb[]=chr($i);
-			}
-			 */
-			$body = str_replace($myqprinta,$myqprintb,($body));
 			$body = quoted_printable_decode($body);
-        	while (ereg("=\n", $body))
-        	{
-           		$body = ereg_replace ("=\n", '', $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;
-	}
-
-	function process_embedded_images($msg, $msgno, $body, $msg_folder)
-	{
-		if (count($msg->inline_id[$msgno]) > 0)
-		{
-			foreach ($msg->inline_id[$msgno] as $index => $cid)
-			{
-				$cid = eregi_replace("<", "", $cid);
-				$cid = eregi_replace(">", "", $cid);
-				$msg_part = $msg->pid[$msgno][$index];
-				//$body = eregi_replace("alt=\"\"", "", $body);
-				$body = eregi_replace("<br/>", "", $body);
-				$body = str_replace("src=\"cid:".$cid."\"", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
-				$body = str_replace("src='cid:".$cid."'", " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
-				$body = str_replace("src=cid:".$cid, " src=\"./inc/show_embedded_attach.php?msg_folder=$msg_folder&msg_num=$msgno&msg_part=$msg_part\" ", $body);
-			}
-		}
-
-		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;
+                }
+
+	function process_embedded_images($images, $msgno, $body, $msg_folder)
+	{
+
+            foreach ($images as $image)
+            {    
+                $image['cid'] = eregi_replace("<", "", $image['cid']);
+                $image['cid'] = eregi_replace(">", "", $image['cid']);
+                $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;
 	}
 
@@ -1315,113 +1371,148 @@
 	{
 		// Suspected TAGS!
-		/*$tag_list = Array(
-			'blink','object','meta',
-			'html','link','frame',
-			'iframe','layer','ilayer',
-			'plaintext','script','style','img',
-			'applet','embed','head',
-			'frameset','xml','xmp');
-		*/
-
-		// Layout problem: Change html elements
-		// with absolute position to relate position, CASE INSENSITIVE.
-                $body = str_replace("\x00", '', $body);
-                $body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body);
-
-		$tag_list = Array('head','blink','object','frame',
-			'iframe','layer','ilayer','plaintext','script',
-			'applet','embed','frameset','xml','xmp','style');
-
-		$blocked_tags = array();
+		// $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);
+
+		// tags to be removed doe to security reasons
+		$tag_list = Array(
+			'head','blink','object','frame','iframe',
+			'layer','ilayer','plaintext','script',
+			'applet','embed','frameset','xml','xmp'
+		);
+		
 		foreach($tag_list as $index => $tag) {
-			$new_body = @mb_eregi_replace("<$tag", "<!--$tag", $body);
-			if($body != $new_body) {
-				$blocked_tags[] = $tag;
-			}
-			$body = @mb_eregi_replace("</$tag>", "</$tag-->", $new_body);
-		}
+			$body = @mb_eregi_replace("<$tag\\b[^>]*>(.*?)</$tag>", "<!-- TAG <$tag> Removed by ExpressoMail -->", $body); 
+		}
+		
+		//try to wrap CSS code instead of remove STYLE tags
+		require_once('../library/csstidy/class.csstidy.php');
+		$css = new csstidy();
+		$css->set_cfg('preserve_css', false);
+
+		$regs_found = array(); 
+		$tags_found = @mb_eregi("<style\b[^>]*>(.*?)</style>", $body, $regs_found);
+                $wrapper_class = 'ExpressoCssWrapper'.time();
+		
+		foreach ($regs_found as $block_found) { 
+			$n_start      = strpos($block_found, '>')+1;
+			$n_length     = strrpos($block_found, '<')-$n_start;
+			$bf_innerHTML = substr($block_found, $n_start, $n_length);
+			
+			$bf_innerHTML = mb_ereg_replace('<!--', '', $bf_innerHTML);
+			$bf_innerHTML = mb_ereg_replace('-->', '', $bf_innerHTML);
+
+			$css->parse($bf_innerHTML);
+			
+			$prefix = ".$wrapper_class "; 
+			foreach ($css->css[41] as $key => $value) {
+			//explode multiple selectors per block
+                         $selectors = explode(',', $key);
+                        foreach ($selectors as $selector) {
+                                if (ereg('\*', $key)) {
+                                        //skip selecto '*'
+                                        continue;
+                                }
+
+                                $selector = eregi_replace('[^#\.]*body.*', '', $selector);
+                                $css->css[41][$prefix.trim($selector)] = $value;
+                        }
+                        unset($css->css[41][$key]);
+			}
+			
+			$body = str_replace($block_found, '<style>'.$css->print->plain().'</style>', $body); 
+		}
+
+
 		// Malicious Code Remove
 		$dirtyCodePattern = "/(<([\w]+[\w0-9]*)(.*)on(mouse(move|over|down|up)|load|blur|change|error|click|dblclick|focus|key(down|up|press)|select)([\n\ ]*)=([\n\ ]*)[\"'][^>\"']*[\"']([^>]*)>)(.*)(<\/\\2>)?/misU";
 		preg_match_all($dirtyCodePattern,$body,$rest,PREG_PATTERN_ORDER);
-		foreach($rest[0] as $i => $val)
+		foreach($rest[0] as $i => $val) { 
 			if (!(preg_match("/javascript:window\.open\(\"([^'\"]*)\/index\.php\?menuaction=calendar\.uicalendar\.set_action\&cal_id=([^;'\"]+);?['\"]/i",$rest[1][$i]) && strtoupper($rest[4][$i]) == "CLICK" )) //Calendar events
 				$body = str_replace($rest[1][$i],"<".$rest[2][$i].$rest[3][$i].$rest[7][$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); 
-		//Correção para compatibilização com Outlook, ao visualizar a mensagem 
-		$body = mb_ereg_replace('<!--\[','<!-- [',$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);
+		
+		//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);
-		$body = str_replace("\x00", '', $body);
-		
-		return  "<span>".$body;	
-	}
-
-	function replace_links( $body )
-	{
-  		// Domains and IPs addresses found in the text and which is not a link yet should be replaced by one. 
-		// See more informations in www.iana.org 
-		$octets = array( 
-			'first' => '(2[0-3][0-9]|1[0-9]{2}|[1-9][0-9]?)', 
-			'middle' => '(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})', 
-			'last' => '(25[0-4]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)' 
-		); 
-
-		$ip = "\b{$octets[ 'first' ]}\.({$octets[ 'middle' ]}\.){2}{$octets[ 'last' ]}\b"; 
-
-		$top_level_domains = '(\.(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|as|asia|at|au|aw|ax|az|' 
-			. 'ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bl|bm|bn|bo|br|bs|bt|bv|bw|by|bz|' 
-			. 'ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cu|cv|cx|cy|cz|' 
-			. 'de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|' 
-			. 'ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|' 
-			. 'hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|' 
-			. 'ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|' 
-			. 'ma|mc|md|me|mf|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|' 
-			. 'mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|' 
-			. 'pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|ps|pt|pw|py|qa|re|ro|rs|ru|rw|' 
-			. 'sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|' 
-			. 'tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|' 
-			. 'ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw))+\b'; 
-
-		$path = '(?>\/[\w\d\/\.\'\(\)\-\+~?!&#@$%|:;,*=_]+)?'; 
-		$port = '(?>:\d{2,5})?'; 
-		$domain = '(?>[\w\d_\-]+)'; 
-		$subdomain = "(?>{$domain}\.)*"; 
-		$protocol = '(?>(http|ftp)(s)?:\/\/)?'; 
-		$url = "(?>{$protocol}((?>{$subdomain}{$domain}{$top_level_domains}|{$ip}){$port}{$path}))"; 
+			
+		return  "<div class=\"$wrapper_class\"><span>".$body.'</span></div>';
+	}	
+
+function replace_links(&$body)
+   	{
+		// Domains and IPs addresses found in the text and which is not a link yet should be replaced by one.
+		// See more informations in www.iana.org
+		$octets = array(
+			'first' => '(2[0-3][0-9]|1[0-9]{2}|[1-9][0-9]?)',
+			'middle' => '(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})',
+			'last' => '(25[0-4]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)'
+		);
+
+		$ip = "\b{$octets[ 'first' ]}\.({$octets[ 'middle' ]}\.){2}{$octets[ 'last' ]}\b";
+
+		$top_level_domains = '(\.(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|as|asia|at|au|aw|ax|az|'
+			. 'ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bl|bm|bn|bo|br|bs|bt|bv|bw|by|bz|'
+			. 'ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cu|cv|cx|cy|cz|'
+			. 'de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|'
+			. 'ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|'
+			. 'hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|'
+			. 'ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|'
+			. 'ma|mc|md|me|mf|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|'
+			. 'mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|'
+			. 'pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|ps|pt|pw|py|qa|re|ro|rs|ru|rw|'
+			. 'sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|'
+			. 'tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|'
+			. 'ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw))+\b';
+		
+		$path = '(?>\/[\w\d\/\.\'\(\)\-\+~?!&#@$%|:;,*=_]+)?';
+		$port = '(?>:\d{2,5})?';
+		$domain = '(?>[\w\d_\-]+)';
+		$subdomain = "(?>{$domain}\.)*";
+		$protocol = '(?>(http|ftp)(s)?:\/\/)?';
+		$url = "(?>{$protocol}((?>{$subdomain}{$domain}{$top_level_domains}|{$ip}){$port}{$path}))";
 
 		$pattern = "/(<\w[^>]+|[\/\"'@=])?{$url}/";
-		ini_set( 'pcre.backtrack_limit', 300000 ); 
-
-		/* 
-		// PHP 5.3 
-		$replace = function( $matches ) 
-		{ 
-			if ( $matches[ 1 ] ) 
-				return $matches[ 0 ]; 
-
-			$url = ( $matches[ 2 ] ) ? $matches[ 2 ] : 'http'; 
-			$url .= "{$matches[ 3 ]}://{$matches[ 4 ]}"; 
-			return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>"; 
-		}; 
-		$body = preg_replace_callback( $pattern, $replace, $body ); 
-		 */ 
-
-		// PHP 5.2.x - Remover assim que possível 
-		$body = preg_replace_callback( $pattern, 
-			create_function( 
-				'$matches', 
-				'if ( $matches[ 1 ] ) return $matches[ 0 ];' 
-				. '$url = ( $matches[ 2 ] ) ? $matches[ 2 ] : "http";'
-				. '$url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";'
-				. 'return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";'
+		
+		ini_set( 'pcre.backtrack_limit', 300000 );
+		/*
+		// PHP 5.3
+		$replace = function( $matches )
+		{
+			if ( $matches[ 1 ] )
+				return $matches[ 0 ];
+
+			$url = ( $matches[ 2 ] ) ? $matches[ 2 ] : 'http';
+			$url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";
+			return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";
+		};
+		$body = preg_replace_callback( $pattern, $replace, $body );
+		*/
+
+		// PHP 5.2.x - Remover assim que possível
+		$body = preg_replace_callback( $pattern,
+			create_function(
+				'$matches',
+				'if ( $matches[ 1 ] ) return $matches[ 0 ];'
+					. '$url = ( $matches[ 2 ] ) ? $matches[ 2 ] : "http";'
+					. '$url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";'
+					. 'return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";'
 			), $body
 		);
-		ini_set( 'pcre.backtrack_limit', 100000 ); 
+		ini_set( 'pcre.backtrack_limit', 100000 );
+
 		// 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'; 
+		$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 );
@@ -1533,21 +1624,22 @@
 	}
 
-	function get_thumbs($msg, $msg_number, $msg_folder)
-	{
-		$thumbs_array = array();
-		$i = 0;
-    	foreach ($msg->file_type[$msg_number] as $index => $file_type)
-    	{
-    		$file_type = strtolower($file_type);
-    		if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') {
-	    		if (($file_type == 'image/jpeg') || ($file_type == 'image/pjpeg') || ($file_type == 'image/gif') || ($file_type == 'image/png')) {
-	    			$img = "<IMG id='".$msg_folder.";;".$msg_number.";;".$i.";;".$msg->pid[$msg_number][$index].";;".$msg->encoding[$msg_number][$index]."' style='border:2px solid #fde7bc;padding:5px' title='".$this->functions->getLang("Click here do view (+)")."'src=./inc/show_thumbs.php?file_type=".$file_type."&msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$msg->pid[$msg_number][$index].">";
-	    			$href = "<a onMouseDown='save_image(event,this,\"".$file_type."\")' href='#".$msg_folder.";;".$msg_number.";;".$i.";;".$msg->pid[$msg_number][$index].";;".$msg->encoding[$msg_number][$index]."' onClick=\"window.open('./inc/show_img.php?msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$msg->pid[$msg_number][$index]."','mywindow','width=700,height=600,scrollbars=yes');\">". $img ."</a>";
-					$thumbs_array[] = $href;
-	    		}
-    			$i++;
-    		}
-    	}
-    	return $thumbs_array;
+	function get_thumbs($images, $msg_number, $msg_folder)
+	{
+
+            $thumbs_array = array();
+            $i = 0;
+
+            foreach ($images as $x => $image)
+            {
+                 if($x && $x == 'names')
+                    continue;
+                 
+                 $img = "<IMG id='".$msg_folder.";;".$msg_number.";;".$i.";;".$image['pid'].";;".$image['encoding']."' style='border:2px solid #fde7bc;padding:5px' title='".$this->functions->getLang("Click here do view (+)")."'src=./inc/show_thumbs.php?&msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$image['pid'].">";
+                 $href = "<a onMouseDown='save_image(event,this,\"".$image['type']."\")' href='#".$msg_folder.";;".$msg_number.";;".$i.";;".$image['pid'].";;".$image['encoding']."' onClick=\"window.open('./inc/show_img.php?msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$image['pid']."','mywindow','width=700,height=600,scrollbars=yes');\">". $img ."</a>";
+                 $thumbs_array[] = $href;
+                 $i++;
+               
+            }
+            return $thumbs_array;
 	}
 
@@ -1569,12 +1661,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);
@@ -1583,7 +1675,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)
 		{
@@ -1591,8 +1683,8 @@
 				$return['msgs_number'][] = $msg_number;
 		}
-
+		
 		$return['folder'] = $folder;
 		$return['border_ID'] = $border_ID;
-
+		
 		if($mbox_stream)
 			imap_close($mbox_stream, CL_EXPUNGE);
@@ -2339,70 +2431,80 @@
 		}
 	}
-	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); 
-
-			if ($msg_uid != $cid_imgs[4][$j]) // The image is not in the same mail? 
-			{ 
-				$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64'); 
-				//prototype: get_forwarding_attachment ( folder, msg number, part, encoding) 
-				$fileName = "image_".($j).".jpg"; 
-				$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] = $cid_imgs[6][$j]; 
-				$file_attached[4] = 'base64'; 
-				$file_attached[5] = strlen($fileContent); //Size of file 
-				$return_forward[] = $file_attached; 
-
-				$attachment_ = unserialize(rawurldecode($forwarding_attachments[$cid_imgs[6][$j]-2])); 
-				if ($file_attached[3] == $attachment_[3]) 
-					unset($forwarding_attachments[$cid_imgs[6][$j]-2]); 	
-			} 
-			else 
-			{ 
-				$attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2]; 
-				$file_description = unserialize(rawurldecode($attach_img)); 
-				if (is_array($file_description)) 
-					foreach($file_description as $i => $descriptor){                                 
-						$file_description[$i]  = eregi_replace('\'*\'','',$descriptor); 
-					} 
-				$fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64'); 
-				$fileName = $file_description[2]; 
-				$fileCode = $file_description[4]; 
-				$fileType = $this->get_file_type($file_description[2]); 
-				unset($forwarding_attachments[$cid_imgs[6][$j]-2]); 
-				if (!empty($file_description)) 
-				{ 
-					$file_description[5] = strlen($fileContent); //Size of file 
-					$return_forward[] = $file_description; 
-				} 
-			} 
-			$tempDir = ini_get("session.save_path"); 
-			$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); 
-			//else 
-			//      return "Error loading image attachment content";                                                 
-
-		} 
-		return $return_forward; 
-	} 
+	
+	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]);
+			$position = substr($cid_imgs[6][$j], 2, $count);
+			$position--;
+					
+			$attach_img = $forwarding_attachments[$position];
+			$file_description = unserialize(rawurldecode($attach_img));
+			
+			if (is_array($file_description))
+				foreach($file_description as $i => $descriptor)				
+					$file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
+
+			// 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');
+				$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;
+				$file_attached[3] = '0.'.($j+1);
+				$file_attached[4] = 'base64';
+				$file_attached[5] = strlen($fileContent); //Size of file
+				$file_attached[6] = $cid_imgs[6][$j];
+				$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];
+				$file_description[3] = '0.'.($j+1);
+				$file_description[6] = $cid_imgs[6][$j];
+				$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;
+				}
+			}
+			$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;
+	}
 	function add_recipients_cert($full_address)
 	{
@@ -2472,16 +2574,8 @@
 	function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
 	{
-		$mbox_stream = $this->open_mbox(utf8_decode(urldecode($msg_folder)));
-		$fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
-		if($encoding == 'base64')
-			# The function imap_base64 adds a new line
-			# at ASCII text, with CRLF line terminators.
-			# So is being exchanged for base64_decode.
-			#
-			#$fileContent = imap_base64($fileContent);
-			$fileContent = base64_decode($fileContent);
-		else if($encoding == 'quoted-printable')
-			$fileContent = quoted_printable_decode($fileContent);
-		return $fileContent;
+            include_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
+            $attachment = new attachment();
+            $attachment->setStructureFromMail($msg_folder, $msg_number);
+            return $attachment->getAttachment($msg_part);
 	}
 
@@ -2728,34 +2822,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'];
-		$body = str_replace("%nbsp;","&nbsp;", $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.
-		if(strtoupper($folder) == 'INBOX/DRAFTS') $mail->SaveMessageAsDraft = $folder;
-
+					
 		$mail->SaveMessageInFolder = $folder;
 		$mail->SMTPDebug = false;
-
+						
 		$mail->IsSMTP();
 		$mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
@@ -2763,87 +2857,88 @@
 		$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);
-    $this->add_recipients("cco", $ccoaddress, &$mail);
-		$mail->AddReplyTo($replytoaddress);
 		$mail->Subject = $subject;
 		$mail->IsHTML(true);
 		$mail->Body = $body;
-		
-		// Important message
-		if($is_important)
-			$mail->isImportant();
-
-		// Disposition-Notification-To
-		if ($return_receipt)
-			$mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
-
-		$return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments); 
-
-	//	Build Forwarding Attachments!!!
-		if (count($forwarding_attachments) > 0)
-		{
-			foreach($forwarding_attachments as $forwarding_attachment)
-			{
-				$file_description = unserialize(rawurldecode($forwarding_attachment));
-				$tmp = array_values($file_description);
-				foreach($file_description as $i => $descriptor){
-					$tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
-				}
-				$file_description = $tmp;
-
-				$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]));
-			}
-		}
-
+
+		$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));
+			
+			$file_description = array_values($file_description);
+			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]));
+		}
+		
 		if ((count($return_forward) > 0) && (count($return_files) > 0))
+		{
 			$return_files = array_merge_recursive($return_forward,$return_files);
-		else
-			if (count($return_files) < 1)
-				$return_files = $return_forward;
-
-		//	Build Uploading Attachments!!!
+		}
+		else if (count($return_files) < 1)
+		{
+			$return_files = $return_forward;
+		}
+
+		//Build Uploading Attachments!!!
 		$sizeof_attachments = count($attachments);
 		if ($sizeof_attachments)
-			foreach ($attachments as $numb => $attach){
-				if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true'){ // Auto-resize image
+		{
+			foreach ($attachments as $numb => $attach)
+			{
+				if ($numb == ($sizeof_attachments-1) && $params['insertImg'] == 'true')
+				{ // Auto-resize image
 					list($width, $height,$image_type) = getimagesize($attach['tmp_name']);
 					switch ($image_type)
 					{
-					// 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;
+						// 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;
 					}
 					header('Content-type: image/jpeg');
 					$max_resolution = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['image_size'];
 					$max_resolution = ($max_resolution==""?'65536':$max_resolution);
-					if ($width < $max_resolution && $height < $max_resolution){
+					if ($width < $max_resolution && $height < $max_resolution)
+					{
 						$new_width = $width;
 						$new_height = $height;
 					}
-					else if ($width > $max_resolution){
+					else if ($width > $max_resolution)
+					{
 						$new_width = $max_resolution;
 						$new_height = $height*($new_width/$width);
 					}
-					else {
+					else 
+					{
 						$new_height = $max_resolution;
 						$new_width = $width*($new_height/$height);
@@ -2851,5 +2946,7 @@
 					$image_new = imagecreatetruecolor($new_width, $new_height);
 					imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
-					$tmpDir = ini_get("session.save_path");
+                                        $tmpDir = '/tmp';
+
+                                       // $tmpDir = ini_get("session.save_path");
 					$_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat";
 					imagejpeg($image_new,$tmpDir.$_file, 85);
@@ -2858,48 +2955,50 @@
 				else
 					$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));
-				// optional 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;
+		$return['imagesParts'] = $imagesParts; 
 
 		if($mbox_stream)
 			imap_close($mbox_stream);
+			
 		if (is_array($return_files))
-			foreach ($return_files as $index => $_attachment) {
-				if (array_key_exists("name",$_attachment)){
-				unset($return_files[$index]);
-				$return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
-			}
-			else
+		{
+			foreach ($return_files as $index => $_attachment) 
 			{
-				unset($return_files[$index]);
-				$return_files[$index] = $_attachment[2]."_SIZE_". $return_files[$index][1] = $_attachment[5];
-			}
-		}
-
+				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];
+				}
+			}
+		}
+		
 		$return['files'] = serialize($return_files);
 		$return["subject"] = $subject;
-
-		if (!$return['append']) {
+				
+		if (!$return['append'])
 			$return['append'] = imap_last_error();
-			$return['has_error'] = true;
-		}
 
 		return $return;
@@ -3850,20 +3949,39 @@
 	}
 
-	function spam($params)
-	{
-		$is_spam = $params['spam'];
-		$folder = $params['folder'];
-		$mbox_stream = $this->open_mbox($folder);
+function spam($params)
+	{
+		
+		$mbox_stream = $this->open_mbox($params['folder']);
 		$msgs_number = explode(',',$params['msgs_number']);
 
-		foreach($msgs_number as $msg_number) {
+                $user = Array();
+
+                if(substr($params['folder'], 0, 4) == 'user')
+                {
+                    $ldapObject = new ldap_functions();
+
+                    $folderArray = Array();
+                    $folderArray = explode($this->imap_delimiter, $params['folder']);
+
+                    $user['name'] = $folderArray[1];
+                    $user['email'] = $ldapObject->getMailByUid($user['name']);
+                
+                }
+                else
+                {
+                    $user['name'] = $this->username;
+                    $user['email'] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
+                }
+
+		foreach($msgs_number as $msg_number)
+                {
 			$imap_msg_number = imap_msgno($mbox_stream, $msg_number);
 			$header = imap_fetchheader($mbox_stream, $imap_msg_number);
 			$body = imap_body($mbox_stream, $imap_msg_number);
 			$msg = $header . $body;
-			$email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
-			$username = $this->username;
-			strtok($email, '@');
+			strtok($user['email'], '@');
 			$domain = strtok('@');
+
+           
 
 			//Encontrar a assinatura do dspam no cabecalho
@@ -3880,13 +3998,16 @@
 
 			// Seleciona qual comando a ser executado
-			switch($is_spam){
+			switch($params['spam']){
 				case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
 				case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
 			}
 
+                      
 			$tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##', '##MSGID##');
-			$cmd = str_replace($tags, array($email, $username, $domain, $signature, $msg_id), $cmd);
+			$cmd = str_replace($tags, array($user['email'], $user['name'], $domain, $signature, $msg_id), $cmd);
+                        
  			system($cmd);
 		}
+
 		imap_close($mbox_stream);
 		return false;
Index: sandbox/2.2.0.2/expressoMail1_2/inc/class.exporteml.inc.php
===================================================================
--- sandbox/2.2.0.2/expressoMail1_2/inc/class.exporteml.inc.php	(revision 4348)
+++ sandbox/2.2.0.2/expressoMail1_2/inc/class.exporteml.inc.php	(revision 4416)
@@ -304,5 +304,5 @@
 		$body		= $this-> getBody($id_number);
 		
-		$file = "source_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".eml";
+		$file = "source_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]."_".time().".php"; //source_[sessao]_[timestamp].php
 		$f = fopen($tempDir.'/'.$file,"w");
 		fputs($f,$header ."\r\n\r\n". $body);
@@ -351,10 +351,13 @@
 		$return_attachments = array();
 
-		$id_number = $params['num_msg'];
+		$id_number = $params['num_msg'];		
 		$attachments =unserialize(rawurldecode($params['s_attachments']));
-
-		$tempDir = $_SESSION['phpgw_info']['server']['temp_dir'];
+		
+		$tempDir = dirname( __FILE__ ) . '/../tmpLclAtt';
+		$tempSubDir = md5(microtime());
+		exec('mkdir ' . $tempDir . '/'.$tempSubDir.'; cd ' . $tempDir . '/'.$tempSubDir);
+		
 		$this-> folder = $params['folder'];
-		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
+		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
 		$this->connectImap();
 
@@ -366,27 +369,33 @@
 			if($i && $i == 'names')
 				continue;
-
-			$fileName = $_SESSION[ 'phpgw_session' ][ 'session_id' ].md5($attachment['name'].microtime());
+			$fileNameReal = $this->remove_accents($attachment['name']);
 			$ContentType = $this->getFileType($fileNameReal);
-			$f = fopen($tempDir . '/'.$fileName,"wb");
+			$fileName = $fileNameReal . ".php";
+			$f = fopen($tempDir . '/'.$tempSubDir.'/'.$fileName,"wb");
 			if(!$f)
-				return false;
+				return $tempDir . '/'.$tempSubDir.'/'.$fileName;			
 
 			$fileContent = imap_fetchbody($this->mbox_stream, $id_number,$attachment['pid'], FT_UID);
-
+			$urlPath = 'tmpLclAtt/'.$tempSubDir.'/'.$fileName;
+			
+			$headers = "<?php header('Content-Type: ".$ContentType."');
+				header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
+				header('Pragma: public');
+				header('Expires: 0'); // set expiration time
+	 	 		header('Content-Disposition: attachment; filename=\"". addslashes($fileNameReal) ."\"');\n echo ";
+			
 			if($attachment['encoding'] == 'base64') {
-				$headers=imap_base64($fileContent);
+				$headers.=" imap_base64('".$fileContent."');?>";
 			}
 			else if($attachment['encoding'] == 'quoted_printable_decode') {
-				$headers=quoted_printable_decode($fileContent);
+				$headers.=" quoted_printable_decode('".$fileContent."');?>";
 			}
 			else {
-				$headers=$fileContent;
-			}
-
+				$headers.=" '".$fileContent."';?>";
+			}
+			
 			fputs($f,$headers);
 
-			$url =  "inc/gotodownload.php?idx_file=".$tempDir .'/'.$fileName."&newfilename=".$attachment['name'];
-			array_push($return_attachments,array('name' => $fileName,'url' => $url,'pid' =>$attachment['pid']));
+			array_push($return_attachments,array('name' => $fileName,'url' => $urlPath,'pid' =>$attachment['pid']));
 			fclose($f);
 		}
Index: sandbox/2.2.0.2/expressoMail1_2/inc/show_thumbs.php
===================================================================
--- sandbox/2.2.0.2/expressoMail1_2/inc/show_thumbs.php	(revision 3018)
+++ sandbox/2.2.0.2/expressoMail1_2/inc/show_thumbs.php	(revision 4416)
@@ -1,39 +1,40 @@
 <?php
+/*
+ * Requieres
+ */
+ require_once '../../header.session.inc.php';
+ require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
+ //------------------------//
 
-	require_once '../../header.session.inc.php'; 
-	$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
-	$password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
-	$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
-	$imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
-	if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
-	{
-		$imap_options = '/tls/novalidate-cert';
-	}
-	else
-	{
-		$imap_options = '/notls/novalidate-cert';
-	}
+ /*
+  * Get variables
+  */
+$fileType = $_GET['file_type'];
+$msgFolder = $_GET['msg_folder'];
+$msgNumber = $_GET['msg_num'];
+$part = $_GET['msg_part'];
+//-------------------------------------//
 
-	$file_type = $_GET['file_type'];
-	$msg_num = $_GET['msg_num'];
-	$msg_part = $_GET['msg_part'];
-	$msg_folder = $_GET['msg_folder'];
-	$msg_folder = mb_convert_encoding($msg_folder,"UTF7-IMAP", mb_detect_encoding($msg_folder, "UTF-8, ISO-8859-1", true));
-	$mb = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$msg_folder, $username, $password);
 
-	$image_mail = imap_fetchbody($mb, $msg_num, $msg_part, FT_UID);
-	$image = imap_base64($image_mail);
-	$pic = @imagecreatefromstring ($image);
-	if($pic !== FALSE) { 
-		header("Content-Type: ".$file_type); 
-		header("Content-Disposition: inline");
-		$width = imagesx($pic);
-		$height = imagesy($pic);
-		$twidth = 160; # width of the thumb 160 pixel
-		$theight = $twidth * $height / $width; # calculate height
-		$theight =  $theight < 1 ? 1 : $theight; 
-		$thumb = imagecreatetruecolor ($twidth, $theight);
-		imagecopyresized($thumb, $pic, 0, 0, 0, 0,$twidth, $theight, $width, $height); # resize image into thumb
-		imagejpeg($thumb,"",75); # Thumbnail as JPEG
-	}
+/*
+ * Main
+ */
+$attachmentObj = new attachment();
+$attachmentObj->setStructureFromMail($msgFolder, $msgNumber);
+$fileContent = $attachmentObj->getAttachment($part);
+$pic = @imagecreatefromstring($fileContent);
+if($pic !== FALSE)
+{
+    header("Content-Type: ".$fileType);
+    header("Content-Disposition: inline");
+    $width = imagesx($pic);
+    $height = imagesy($pic);
+    $twidth = 160; # width of the thumb 160 pixel
+    $theight = $twidth * $height / $width; # calculate height
+    $theight =  $theight < 1 ? 1 : $theight;
+    $thumb = imagecreatetruecolor ($twidth, $theight);
+    imagecopyresized($thumb, $pic, 0, 0, 0, 0,$twidth, $theight, $width, $height); # resize image into thumb
+    imagejpeg($thumb,"",75); # Thumbnail as JPEG
+}
+//------------------------------------------//
 ?>
Index: sandbox/2.2.0.2/expressoMail1_2/inc/show_img.php
===================================================================
--- sandbox/2.2.0.2/expressoMail1_2/inc/show_img.php	(revision 3163)
+++ sandbox/2.2.0.2/expressoMail1_2/inc/show_img.php	(revision 4416)
@@ -1,58 +1,56 @@
 <?php
+/*
+ * Requieres
+ */
+ require_once '../../header.session.inc.php';
+ require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
+ //------------------------//
 
-	require_once '../../header.session.inc.php'; 
-	header("Content-Type: image/jpeg");
-	if($_GET['msg_num'] && $_GET['msg_part'] && $_GET['msg_folder']) {
-		$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
-		$password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
-		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
-		$imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
-	if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
-	{
-		$imap_options = '/tls/novalidate-cert';
-	}
-	else
-	{
-		$imap_options = '/notls/novalidate-cert';
-	}
-		
-		$msg_num = $_GET['msg_num'];
-		$msg_part = $_GET['msg_part'];
-		$msg_folder = $_GET['msg_folder'];
-		$msg_folder = mb_convert_encoding($msg_folder,"UTF7-IMAP", mb_detect_encoding($msg_folder, "UTF-8, ISO-8859-1", true));
-		
-	$mb = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$msg_folder, $username, $password);
-		
-		$image_mail = imap_fetchbody($mb, $msg_num, $msg_part, FT_UID);	
+ /*
+  * Get variables
+  */
+$fileType = $_GET['file_type'];
+$msgFolder = $_GET['msg_folder'];
+$msgNumber = $_GET['msg_num'];
+$part = $_GET['msg_part'];
+//-------------------------------------//
 
-		header("Content-Disposition: inline");
-		$image = imap_base64($image_mail);
-		echo $image;		
-	}
-	else{
-		$expires = 60*60*24*30; /* 30 days */
-		header("Cache-Control: maxage=".$expires);
-		header("Pragma: public");
-		header("Expires: ".gmdate('D, d M Y H:i:s', time()+$expires));
-		if($_SESSION['phpgw_info']['expressomail']['contact_photo']){	
-			$data  = $_SESSION['phpgw_info']['expressomail']['contact_photo'];
+/*
+ * Main
+ */
+header("Content-Type: image/jpeg");
 
-			if($data) {
+if($_GET['msg_num'] != null && $_GET['msg_part'] != null && $_GET['msg_folder'] != null)
+{
+    $attachmentObj = new attachment();
+    $attachmentObj->setStructureFromMail($msgFolder, $msgNumber);
+    $fileContent = $attachmentObj->getAttachment($part);
+    header("Content-Disposition: inline");
 
-				$photo = imagecreatefromstring($data[0]);
-				if($photo){
-					$width = imagesx($photo);
-					$height = imagesy($photo);
-					$twidth = 60;
-					$theight = 80;
-					$small_photo = imagecreatetruecolor ($twidth, $theight);
-					imagecopyresampled($small_photo, $photo, 0, 0, 0, 0,$twidth, $theight, $width, $height);
-					imagejpeg($small_photo,'',100);
-					unset($_SESSION['phpgw_info']['expressomail']['contact_photo']);
-				}
-			}
-		}
-		else
-			readfile("./../../contactcenter/templates/default/images/photo_celepar.png");
-	}
+    echo $fileContent;
+}
+else if($_SESSION['phpgw_info']['expressomail']['contact_photo'])
+{
+    $data  = $_SESSION['phpgw_info']['expressomail']['contact_photo'];
+
+    if($data)
+    {
+        $photo = imagecreatefromstring($data[0]);
+        if($photo)
+        {
+                $width = imagesx($photo);
+                $height = imagesy($photo);
+                $twidth = 60;
+                $theight = 80;
+                $small_photo = imagecreatetruecolor ($twidth, $theight);
+                imagecopyresampled($small_photo, $photo, 0, 0, 0, 0,$twidth, $theight, $width, $height);
+                imagejpeg($small_photo,'',100);
+                unset($_SESSION['phpgw_info']['expressomail']['contact_photo']);
+        }
+    }
+}
+else
+       readfile("./../../contactcenter/templates/default/images/photo_celepar.png");
+//------------------------------------------//
+
 ?>
Index: sandbox/2.2.0.2/expressoMail1_2/inc/show_embedded_attach.php
===================================================================
--- sandbox/2.2.0.2/expressoMail1_2/inc/show_embedded_attach.php	(revision 3018)
+++ sandbox/2.2.0.2/expressoMail1_2/inc/show_embedded_attach.php	(revision 4416)
@@ -1,36 +1,31 @@
 <?php
+/*
+ * Requieres
+ */
+ require_once '../../header.session.inc.php';
+ require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
+ //------------------------//
 
-	require_once '../../header.session.inc.php'; 
+ /*
+  * Get variables
+  */
+$msgFolder = $_GET['msg_folder'];
+$msgNumber = $_GET['msg_num'];
+$embeddedPart = $_GET['msg_part'];
+//-------------------------------------//
 
-	$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
-	$password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
-	$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
-	$imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
-	$msg_folder = $_GET['msg_folder'];
-	$msg_folder = mb_convert_encoding($msg_folder,"UTF7-IMAP", mb_detect_encoding($msg_folder, "UTF-8, ISO-8859-1", true));
-	if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
-	{
-		$imap_options = '/tls/novalidate-cert';
-	}
-	else
-	{
-		$imap_options = '/notls/novalidate-cert';
-	}
-	
-	if (is_array($_SESSION['phpgw_info']['expressomail']['email_server']))
-	{
-		$mb = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$msg_folder, $username, $password);
-	
-		if ($mb)
-		{
-			$msgno = $_GET['msg_num'];
-			$embedded_part = $_GET['msg_part'];
-	
-			$embedded_body = imap_fetchbody($mb, $msgno, $embedded_part, FT_UID);
-	
-			header("Content-Type: image/jpeg");
-			header("Content-Disposition: inline");
-			echo imap_base64($embedded_body);
-		}
-	}
+
+/*
+ * Main
+ */
+$attachmentObj = new attachment();
+$attachmentObj->setStructureFromMail($msgFolder, $msgNumber);
+$fileContent = $attachmentObj->getAttachment($embeddedPart);
+
+header("Content-Type: image/jpeg");
+header("Content-Disposition: inline");
+
+echo $fileContent;
+//------------------------------------------//
+
 ?>
Index: sandbox/2.2.0.2/expressoMail1_2/js/common_functions.js
===================================================================
--- sandbox/2.2.0.2/expressoMail1_2/js/common_functions.js	(revision 4413)
+++ sandbox/2.2.0.2/expressoMail1_2/js/common_functions.js	(revision 4416)
@@ -224,5 +224,5 @@
 	div_attachment = document.getElementById("id_div_attachment");
 	var params = '';
-
+	
 	if (div_attachment == null){
 		var div_attachment = document.createElement("DIV");
@@ -230,10 +230,16 @@
 		document.body.appendChild(div_attachment);
 	}
-	if(new_file_name)
-		params = "&newfilename="+escape(new_file_name);
+	if(new_file_name) {
+		var extension = new_file_name.substring(new_file_name.length-4, new_file_name.length);
+		if (extension == ".eml") // if the extension is .eml
+			params = "&newFilename="+new_file_name; //name_of_message.eml
+		else // when more than one message
+			params = "&newFilename="+escape(new_file_name); //mensagens.zip
+	}
 	if(encoding)
 		params += "&encoding="+encoding;
 
-	div_attachment.innerHTML="<iframe style='display:none;width:0;height:0' name='attachment' src='inc/gotodownload.php?msg_folder="+msg_folder+"&msg_number="+msg_number+"&idx_file="+idx_file+"&msg_part="+msg_part+params+"'></iframe>";
+        div_attachment.innerHTML="<iframe style='display:none;width:0;height:0' name='attachment' src='inc/get_archive.php?msgFolder="+msg_folder+"&msgNumber="+msg_number+"&idx_file="+idx_file+"&indexPart="+msg_part+params+"'></iframe>";
+
 }
 
