Index: trunk/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 5083)
+++ trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 5134)
@@ -27,6 +27,11 @@
 	var $foldersLimit;
 	var $imap_sentfolder;
+	var $rawMessage;
 
 	function imap_functions (){
+		$this->init();
+	}
+	
+	function init(){
 		$this->foldersLimit = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] ?  $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] : 20000; //Limit of folders (mailboxes) user can see
 	 	$this->username 	  = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
@@ -53,5 +58,5 @@
 	function open_mbox($folder = False,$force_die=true)
 	{
-		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
+		$folder = mb_convert_encoding($folder, "UTF7-IMAP", mb_detect_encoding($folder.'x', 'UTF-8, ISO-8859-1, UTF7-IMAP'));
 		if (is_resource($this->mbox))
                 {
@@ -80,11 +85,24 @@
 	 }
 
-	function parse_error($error){
+	function parse_error($error, $field = ''){
 		// This error is returned from Imap.
 		if(strstr($error,'Connection refused')) {
 			return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Connection failed with %1 Server. Try later."));
 		}
-		elseif(strstr($error,'virus')) {
+		else if(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."));
+		}
+		else if(strstr($error,'Failed to add recipient:')) {
+			preg_match_all('/:\s([\s\.";@!a-z0-9]+)\s\[SMTP:/', $error, $res);
+			return  str_replace("%1", $res['1']['0'], $this->functions->getLang("SMTP Error: The following recipient addresses failed: %1"));
+		}
+		else if(strstr($error,'Recipient address rejected')) {
+			return str_replace("%1", $this->functions->getLang("Mail"), $this->functions->getLang("Invalid recipients in the message").'.');
+		}
+		else if(strstr($error,'Invalid Mail:')) {
+			return  str_replace("%1", $field, $this->functions->getLang("The recipients addresses failed %1"));
+		}
+		else if(strstr($error,'Message file too big')) {
+			return ($this->functions->getLang("Message file too big."));
 		}
 		// This condition verifies if SESSION is expired.
@@ -102,14 +120,7 @@
 		$msg_range_begin = $params['msg_range_begin'];
 		$msg_range_end = $params['msg_range_end'];
-		$sort_box_type = $params['sort_box_type'];
-		$sort_box_reverse = $params['sort_box_reverse'];
-		$search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
-
-                $folder 			= $params['folder'];
-                $msg_range_begin	= $params['msg_range_begin'];
-                $msg_range_end		= $params['msg_range_end'];
-                $sort_box_type		= $params['sort_box_type'];
-                $sort_box_reverse	= $params['sort_box_reverse'];
-                $search_box_type	= $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
+                $sort_box_type		= isset($params['sort_box_type']) ? $params['sort_box_type'] : '';
+                $sort_box_reverse	= isset($params['sort_box_reverse']) ? $params['sort_box_reverse'] : '';
+                $search_box_type	= (isset($params['search_box_type']) && $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" )? $params['search_box_type'] : false;
 
                 if( !$this->mbox || !is_resource( $this->mbox ) )
@@ -138,5 +149,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;
@@ -238,13 +249,18 @@
                 }
 
+		if(isset($header->from))
 		$from = $header->from;
 		$head_array['from'] = array();
 		$head_array['from']['name'] = ( isset( $from[0]->personal ) ) ? $this->decode_string($from[0]->personal) : NULL;
+		if(isset($from))
 		$head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@" . $from[0]->host;
-		if(!$head_array['from']['name'])
+		else
+			$head_array['from']['email'] = $this->decode_string($from[0]->mailbox) . "@";
+		if(!$head_array['from']['name'] || trim($head_array['from']['name']) === '' )
 			$head_array['from']['name'] = $head_array['from']['email'];
+		if(isset($header->to))
 		$to = $header->to;
 		$head_array['to'] = array();
-		if($to[1] && $to[1]->host == ".SYNTAX-ERROR.") { //E-mails que não possuem o campo "para", vêm com o recipiente preenchido, porém com um recipiente a mais alegando erro de sintaxe.
+		if(isset($to[1]) && $to[1]->host == ".SYNTAX-ERROR.") { //E-mails que não possuem o campo "para", vêm com o recipiente preenchido, porém com um recipiente a mais alegando erro de sintaxe.
 			$head_array['to']['name'] = $head_array['to']['email'] = NULL;
 		}
@@ -256,11 +272,19 @@
 				$head_array['to']['name'] = $head_array['to']['email'];
 		}
+		$cc = null;
+		$cco = null;
+		if(isset($header->cc)){
 		$cc = $header->cc;
+		}
+		if(isset($header->bcc)){
 		$cco = $header->bcc;
+		}
 		if ( ($cc) && (!$head_array['to']['name']) ){
 			$head_array['to']['name'] = ( isset( $cc[0]->personal ) ) ? $this->decode_string($cc[0]->personal) : NULL;
 			$head_array['to']['email'] = $this->decode_string($cc[0]->mailbox) . "@" . $cc[0]->host;
-			if(!$head_array['to']['name'])
-				$head_array['to']['name'] = $head_array['from']['email'];
+			if(!$head_array['to']['name']){
+				$head_array['to']['name'] = $head_array['from']['name'];
+				//$head_array['to']['email'] = $head_array['from']['email'];
+			}
 		}
 		else if ( ($cco) && (!$head_array['to']['name']) ){
@@ -268,7 +292,15 @@
 			$head_array['to']['email'] = $this->decode_string($cco[0]->mailbox) . "@" . $cco[0]->host;
 			if(!$head_array['to']['name'])
-				$head_array['to']['name'] = $head_array['from']['email'];
+				$head_array['to']['name'] = $head_array['from']['name'];
 		}
 		$head_array['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
+		if($head_array['subject'] == "" || $head_array['subject'] == '' || $head_array['subject'] == null ){
+			$head_array['subject'] = $this->functions->getLang("(no subject)   ");
+		}
+	
+		if($head_array['to']['name'] == 'undisclosed-recipients@' || $head_array['to']['name'] == '@'){
+			$head_array['to']['name'] = $head_array['from']['name'];
+			$head_array['to']['email'] = $head_array['from']['email'];
+		}
 
 		$head_array['Size'] = $header->Size;
@@ -280,12 +312,9 @@
 	}
 
-	
 	/**
-	* Decodifica a string da mensagem
 	*
 	* @license    http://www.gnu.org/copyleft/gpl.html GPL
-	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $string
+	* @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
@@ -293,7 +322,8 @@
 	function decode_string($string)
 	{
+        $return = '';
+        $decoded = '';
 		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)
@@ -335,6 +365,6 @@
  	 
  	    }
-        else if (eregi('=?', $string))
-            return iconv_mime_decode($string);
+        else if( strpos( $string , '=?' ) !== false ) 
+            return $this->htmlspecialchars_encode(iconv_mime_decode( $string ));
         
 
@@ -409,7 +439,20 @@
 									$email
 									);
-			if(!$status){
+			if(!$status) {
+				//TODO: remover zip_entry pois ele é tratado apenas ao importar mensagens zipadas
 				array_push($errors,zip_entry_name($zip_entry));
 				zip_entry_close($zip_entry);
+			}
+			
+			if ( isset( $tmp_box ) && ! sizeof( $errors ) ) {
+				$mc = imap_check($this->mbox);
+
+				$result = imap_fetch_overview( $this -> mbox, "1:{$mc -> Nmsgs}", 0 );
+
+				$ids = array( );
+				foreach ($result as $overview)
+					$ids[ ] = $overview -> uid;
+
+				return implode( ',', $ids );
 			}
 		}
@@ -457,5 +500,5 @@
 		}
 
-		$msg = &new message_components($this->mbox);
+		$msg = new message_components($this->mbox);
 		$msg->fetch_structure($params["msg_num"]);/* O fetchbody tava trazendo o email com problemas na acentuação.
 							     Então uso essa classe para verificar a codificação e o charset,
@@ -492,9 +535,9 @@
 					"\r\n".
 					"\r\n".
-					str_replace("\n","\r\n",$this->decodeBody(
+					str_replace("\n","\r\n",preg_replace("/<img[^>]+\>/i", " ", $this->decodeBody(
 							imap_fetchbody($this->mbox,imap_msgno($this->mbox, $params["msg_num"]),$body_part_to_show),
 							$all_body_encoding, $all_body_charset
-							)
-					), "\\Seen"); //Append do novo email, só com header e conteúdo sem anexos.
+							))
+					), "\\Seen"); //Append do novo email, só com header e conteúdo sem anexos. //Remove imagens do corpo, pois estas estão na lista de anexo e serão removidas.
 
 		if(!$status)
@@ -570,5 +613,4 @@
 			$attach_params["num_msg"] = $msg_number;
 			$msg_info['array_attach'] = $exporteml->get_attachments_in_array($attach_params);
-			$msg_info['url_export_file'] = $exporteml->export_to_archive($msg_number,$params["folder"]);
 			imap_close($this->mbox);
 			$this->mbox=false;
@@ -589,10 +631,7 @@
 
 	/**
-	* Retorna a linha do Header da mensagem
-	*
 	* @license    http://www.gnu.org/copyleft/gpl.html GPL
 	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $msg_number
+	* @param     $msg_number numero da mensagem
 	*/
 	function getRawHeader($msg_number)
@@ -601,12 +640,8 @@
 	}
 	
-	
 	/**
-	* Retorna a linha do Corpo da mensagem
-	*
 	* @license    http://www.gnu.org/copyleft/gpl.html GPL
 	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $msg_number
+	* @param     $msg_number numero da mensagem
 	*/
 	function getRawBody($msg_number)
@@ -617,10 +652,7 @@
 	
 	/**
-	* Constrói o Header da mensagem
-	*
 	* @license    http://www.gnu.org/copyleft/gpl.html GPL
 	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $msg
+	* @param     $msg mensagem
 	*/
 	function builderMsgHeader($msg)
@@ -654,12 +686,7 @@
 	
 	/**
-	* Constrói o corpo da mensagem
-	*
-	* @license    http://www.gnu.org/copyleft/gpl.html GPL
-	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $structure
-	* @param      $content
-	* @param      $printHeader
+        * 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)
@@ -676,5 +703,5 @@
                     {
                        case 'text':
-                           $disposition = strtolower($part->disposition);
+                           $disposition = isset($part->disposition) ? strtolower($part->disposition) : '';
                            if($disposition != 'attachment')
                            {
@@ -694,6 +721,6 @@
                                    $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>';
                                 }
-
-
+                                if(strtolower($part->ctype_secondary) == 'calendar')
+                                    $content.= $this->builderMsgCalendar($this->decodeMailPart($part->body, $part->ctype_parameters['charset']));
 
                            }
@@ -735,6 +762,7 @@
                    {
                        case 'text':
-                           
-                           $disposition = strtolower($part->disposition);
+                           $disposition = '';
+                           if(isset($part->disposition))
+                           $disposition = isset($part->disposition) ? strtolower($part->disposition) : '';
                            if($disposition != 'attachment')
                            {
@@ -754,5 +782,6 @@
                                    $content .= '<pre>'. htmlentities($this->decodeMailPart($part->body,$part->ctype_parameters['charset'],false)).'</pre>';
                                 }
-
+                                if(strtolower($part->ctype_secondary) == 'calendar')
+                                    $content .= $this->builderMsgCalendar($part->body);
                         
                            }
@@ -767,5 +796,6 @@
                             break;
                        case 'message':
-
+                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] != '1')
+                        {
                             if(!is_array($part->parts))
                             {
@@ -781,17 +811,15 @@
             }
         }
-	
+        }
 	
 	
 	/**
-	* Retorna o 
-	*
 	* @license    http://www.gnu.org/copyleft/gpl.html GPL
 	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $msg_number
+	* @param     $msg_number numero da mensagem
 	*/
 	function get_msg_sample($msg_number)
 	{
+        $content = '';
 
 		$return = ""; 
@@ -804,8 +832,8 @@
 
 		include_once("class.message_components.inc.php");
-		$msg = &new message_components($this->mbox);
+		$msg = new message_components($this->mbox);
 		$msg->fetch_structure($msg_number);  
 
-		if(!$msg->structure[$msg_number]->parts)
+		if(!isset($msg->structure[$msg_number]->parts))
 		{
 			$content = '';
@@ -827,16 +855,39 @@
 			}
 		}
-		$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 = str_replace($tags_replace," ", nl2br($content));
+		$content = $this->html2txt($content);	
 		$content != "" ? $return['body'] = " - " . $content: $return['body'] = "";
+                $return['body'] = base64_encode(mb_convert_encoding(substr($return['body'], 0, 305),'ISO-8859-1'));
 		return $return;
 	}
+    function html2txt($document){
+        $search = array('@<script[^>]*?>.*?</script>@si',  // Strip out javascript
+                       '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
+                       '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
+                       '@<![\s\S]*?--[ \t\n\r]*>@si'         // Strip multi-line comments including CDATA                    
+        );
+        $text = preg_replace($search, '', $document);
+        return html_entity_decode($text);
+    } 
+
+    function ope_msg_part($params)
+    {
+        $return = array();
+        require_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
 	
+        $atObj = new attachment();
+        $atObj->setStructureFromMail($params['msg_folder'],$params['msg_number']);
+        $mbox_stream = $this->open_mbox($params['save_folder']);
+        $return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$params['save_folder'], $atObj->getAttachment($params['msg_part']), "\\Seen \\Draft");
+        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$params['save_folder'], SA_UIDNEXT);
 	
+        $return['msg_folder']  = $params['save_folder'];
+        $return['msg_number'] = $status->uidnext - 1;        
+
+        return $return;
+
+    }
 	
 	function get_info_msg($params)
@@ -846,5 +897,5 @@
 		$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. 
+		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];
@@ -879,5 +930,5 @@
 	    $return['attachments'] 	= $return_get_body['attachments'];
 	    $return['thumbs'] 		= $return_get_body['thumbs'];
-	    $return['signature']	= $return_get_body['signature'];
+	    //$return['signature']	= $return_get_body['signature'];
 		}
 		$pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm';
@@ -906,20 +957,32 @@
 		$return['msg_folder'] = $msg_folder;
 
-		$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;
+		
+		
+		$msgTimesTamp = $header->udate + $this->functions->CalculateDateOffset(); //Aplica offset do usuario
+		$date_msg = gmdate("d/m/Y",$msgTimesTamp);
+
+//      Removido codigo pois a o método send_nofication precisa da data completa.
+//		if (date("d/m/Y") == $date_msg)
+//			$return['udate'] = gmdate("H:i",$header->udate);
+//		else
+
+//      Passa o a data completa para mensagem.		
+		$return['udate'] = $header->udate;
 
 		$return['msg_day'] = $date_msg;
-		$return['msg_hour'] = gmdate("H:i",$header->udate);
+		$return['msg_hour'] = gmdate("H:i",$msgTimesTamp);
 
 		if (date("d/m/Y") == $date_msg) //no dia
 		{
-			$return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
-			$return['smalldate'] = gmdate("H:i",$header->udate);
-
-			$timestamp_now = strtotime("now") + $offset;
-			$timestamp_msg_time = $header->udate;
+			$return['fulldate'] = gmdate("d/m/Y H:i",$msgTimesTamp);
+			$return['smalldate'] = gmdate("H:i",$msgTimesTamp);
+			
+
+				$timestamp_now = strtotime("now");
+			//	removido offset nao esta sendo parametrizado
+			//	$timestamp_now = strtotime("now") + $offset;
+			
+			
+			$timestamp_msg_time = $msgTimesTamp;
 			// $timestamp_now is GMT and $timestamp_msg_time is MailDate TZ. 
 			// The variable $timestamp_diff is calculated without MailDate TZ.
@@ -945,11 +1008,11 @@
 		}
 		else{
-			$return['fulldate'] = gmdate("d/m/Y H:i",$header->udate);
-			$return['smalldate'] = gmdate("d/m/Y",$header->udate);
+			$return['fulldate'] = gmdate("d/m/Y H:i",$msgTimesTamp);
+			$return['smalldate'] = gmdate("d/m/Y",$msgTimesTamp);
 		}
 
 		$from = $header->from;
 		$return['from'] = array();
-		$return['from']['name'] = $this->decode_string($from[0]->personal);
+		$return['from']['name'] = isset($sender[0]->personal) ? $this->decode_string($from[0]->personal) : '';
 		$return['from']['email'] = $this->decode_string($from[0]->mailbox . "@" . $from[0]->host);
 		if ($return['from']['name'])
@@ -966,6 +1029,7 @@
 		$sender = $header->sender;
 		$return['sender'] = array();
-		$return['sender']['name'] = $this->decode_string($sender[0]->personal);
+		$return['sender']['name'] = isset($sender[0]->personal) ? $this->decode_string($sender[0]->personal): '';
 		$return['sender']['email'] = $this->decode_string($sender[0]->mailbox . "@" . $sender[0]->host);
+		
 		if ($return['sender']['name'])
 		{
@@ -1014,5 +1078,5 @@
 			$return['toaddress2'] = "";
 		}	
-
+		if(isset($header->cc))
 		$cc = $header->cc;
 		$return['cc'] = "";
@@ -1027,5 +1091,9 @@
 					$return['cc'] .= " ";
 					$return['cc'] .= "&lt;";
+					if ($tmp_cc->host != 'unspecified-domain')
 					$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
+					else
+						$return['cc'] .= $tmp_cc->mailbox;
+					//$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
 					$return['cc'] .= "&gt;";
 					$return['cc'] .= ", ";
@@ -1033,5 +1101,9 @@
 				else
 				{
+					if ($tmp_cc->host != 'unspecified-domain')
 					$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
+					else
+						$return['cc'] .= $tmp_cc->mailbox;
+					//$return['cc'] .= $tmp_cc->mailbox . "@" . $tmp_cc->host;
 					$return['cc'] .= ", ";
 				}
@@ -1049,6 +1121,7 @@
 		# @BRIEF Adding the BCC field.
 		##
-                
+        if(isset($header->bcc)){        
 		$bcc = $header->bcc;
+		}
 		$return['bcc'] = "";
 		if (!empty($bcc))
@@ -1062,5 +1135,8 @@
 					$return['bcc'] .= " ";
 					$return['bcc'] .= "&lt;";
+					if ($tmp_bcc->host != 'unspecified-domain')
 					$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
+					else
+						$return['bcc'] .= $tmp_bcc->mailbox;
 					$return['bcc'] .= "&gt;";
 					$return['bcc'] .= ", ";
@@ -1068,5 +1144,9 @@
 				else
 				{
+					if ($tmp_bcc->host != 'unspecified-domain')
 					$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
+					else
+						$return['bcc'] .= $tmp_bcc->mailbox;
+					//$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
 					$return['bcc'] .= ", ";
 				}
@@ -1107,4 +1187,11 @@
 		$return['reply_to'] = $this->decode_string($return['reply_to']);
 		$return['subject'] = $this->decode_string($header->fetchsubject);
+
+		if($return['subject'] == $this->functions->getLang("(no subject)   ")){
+			$return['subject'] = str_replace(" ","", $return['subject']);
+		}
+		if($return['subject'] == '' || $return['subject'] == null){
+			$return['subject'] = $this->functions->getLang("(no subject)   ");
+		}
 		$return['Size'] = $header->Size;
 		$return['reply_toaddress'] = $header->reply_toaddress;
@@ -1115,16 +1202,19 @@
 		$return['reply_toaddress'] = $header->reply_toaddress;
                 
+		if(($return['from']['email'] ==  '@unspecified-domain' || $return['sender']['email'] == null) && $return['msg_folder'] == 'INBOX/Drafts'){
+			$return['from']['email'] = "Rascunho";
+		}
+		if($return['toaddress2'] == 'undisclosed-recipients@, @'){
+			$return['toaddress2'] = $this->functions->getLang('without destination');
+		}
 		return $return;
 	}
 
 	
- 	/**
+	/* 
 	* Converte textos utf8 para o padrão html.
-	*
-	* @license    http://www.gnu.org/copyleft/gpl.html GPL
-	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
+	 * Modificado por Cristiano Corrêa Schmidt
+ 	 * @link http://php.net/manual/en/function.utf8-decode.php 
 	* @author     luka8088 <luka8088@gmail.com> 
-	* @param      $data
 	*/	
  	function utf8_to_html ($data) 
@@ -1138,20 +1228,14 @@
 		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;"; 
+ 		    return html_entity_decode("&#$ret;" , ENT_QUOTES); 
 		} 
  	//------------------------------------------------------------------------------// 
 
 
-	
-	
 		/**
-		* Decodifica a parte do email
-		*
-		* @license    http://www.gnu.org/copyleft/gpl.html GPL
-		* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-		* @sponsor    Caixa Econômica Federal
-		* @param      $part
-		* @param      $encode
-		* @param      $html
+         * 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, $html = true)
@@ -1164,8 +1248,6 @@
 
                 case 'utf-8':
-                    if ($html) 
-						return  $this->utf8_to_html($part); 
-		else
-						return  utf8_decode ($part);
+                    if ($html) return  $this->utf8_to_html($part);
+                    else       return  utf8_decode ($part);
                     break;
 
@@ -1185,15 +1267,19 @@
             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 = '';
 
-            $rawMessageData = $this->getRawHeader($msg_number).$this->getRawBody($msg_number);
+            /* 
+            * Chamada original  $this->getRawHeader($msg_number)."\r\n".$this->getRawBody($msg_number); 
+            * Inserido replace para corrigir um bug que acontece raramente em mensagens vindas do outlook com muitos destinatarios 
+            */ 
+            $rawMessageData = str_replace("\r\n\t", '', $this->getRawHeader($msg_number))."\r\n".$this->getRawBody($msg_number); 
 
             $decoder = new Mail_mimeDecode($rawMessageData);
@@ -1202,4 +1288,6 @@
             $params['decode_bodies']  = true;
             $params['decode_headers'] = true;
+			if(array_key_exists('nested_messages_are_shown', $_SESSION['phpgw_info']['user']['preferences']['expressoMail']) && ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] == '1'))
+				$params['rfc_822bodies']  = true;
             $structure = $decoder->decode($params);
 
@@ -1227,5 +1315,5 @@
 		{
                     $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);
 		}
 
@@ -1241,13 +1329,17 @@
 
                         $msg_subtype = strtolower($structure->ctype_secondary);
+                    if(isset($structure->disposition))
                         $disposition = strtolower($structure->disposition);
+                    else
+                        $disposition = '';
 
                         if(($msg_subtype == "html" || $msg_subtype == 'plain') && ($disposition != 'attachment'))
 			{
-
-
                                 if(strtolower($msg_subtype) == 'plain')
 					{ 
+                        if(isset($structure->ctype_parameters['charset']))
                                         $content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset'],false);
+                        else
+                            $content = $this->decodeMailPart($structure->body, null,false);
 						$content = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $content ); 
 						$content = htmlentities( $content ); 
@@ -1260,13 +1352,17 @@
 								$content = $this->decodeMailPart($structure->body, $structure->ctype_parameters['charset']);
 				}
+                    if(strtolower($structure->ctype_secondary) == 'calendar')
+                           $content .= $this->builderMsgCalendar($structure->body);
 
                     break;
 
                case 'multipart':
-                    $this-> builderMsgBody($structure , $content);
+                    $this->builderMsgBody($structure , $content);
 
                     break;
 
                case 'message':
+                    if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['nested_messages_are_shown'] != 1)
+                    {
                     if(!is_array($structure->parts))
 				{
@@ -1277,15 +1373,47 @@
                                             else
                         $this->builderMsgBody($structure , $content,true);
-
+                    }
                     break;
 
+            case 'application':
+                if(strtolower($structure->ctype_secondary) == 'x-pkcs7-mime')
+                {   
+                  //  $return['body']='isCripted';
+                  // return $return;
+				  
+				  //TODO: Descartar código após atualização do módulo de segurança da SERPRO
+					$rawMessageData2 = $this->extractSignedContents($rawMessageData); 
+					if($rawMessageData2 === false){ 
+						$return['body']='isCripted'; 
+						return $return; 
+					} 
+					$decoder2 = new Mail_mimeDecode($rawMessageData2); 
+ 		            $structure2 = $decoder2->decode($params); 
+ 		            $this-> builderMsgBody($structure2 , $content);  
+ 		 
+ 		            $attachmentManager->setStructure($structure2); 
+ 		            /* 
+ 		            * 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); 
+ 		            }
+                }
+			///////////////////////////////////////////////////////////////////////////////////////////
                default:
                     if(count($attachments) > 0)
                        $content .= '';
-                    else 
-								{ 
-                       $content .= $this->functions->getLang('Message not supported') . '. ';
-		       $content .= $this->functions->getLang('Type') . ': ' . $structure->ctype_primary . '/' . $structure->ctype_secondary;
-								} 
                     break;
 								} 
@@ -1301,4 +1429,181 @@
 	}
 
+	
+	//TODO: Descartar código após atualização do módulo de segurança da SERPRO
+	function extractSignedContents( $data ) 
+    { 
+		$pipes_desc = array( 
+			0 => array('pipe', 'r'), 
+			1 => array('pipe', 'w') 
+	    ); 
+	 
+	    $fp = proc_open( 'openssl smime -verify -noverify -nochain', $pipes_desc, $pipes); 
+	    if (!is_resource($fp)) { 
+			return false; 
+	    } 
+	 
+	    $output = ''; 
+	 
+ 		/* $pipes[0] => writeable handle connected to child stdin 
+ 		$pipes[1] => readable handle connected to child stdout */ 
+ 	    fwrite($pipes[0], $data); 
+ 	    fclose($pipes[0]); 
+ 	 
+ 	    while (!feof($pipes[1])) { 
+			$output .= fgets($pipes[1], 1024); 
+ 	    } 
+ 	    fclose($pipes[1]); 
+ 	    proc_close($fp); 
+ 	 
+ 	    return $output; 
+ 	}
+    ///////////////////////////////////////////////////////////////////////////////////////
+    
+        function builderMsgCalendar($calendar)
+        {
+            $icalService = ServiceLocator::getService('ical');
+
+            $codificao =  mb_detect_encoding($calendar.'x', 'UTF-8, ISO-8859-1');
+            if($codificao == 'UTF-8')
+                $calendar = utf8_decode($calendar);
+
+            if($icalService->setIcal($calendar))
+            {
+                $content = '';
+
+                switch ($icalService->getMethod()) {
+
+                    case 'REPLY':
+                          include_once($_SESSION['rootPath'].'/header.inc.php');
+                          include_once($_SESSION['rootPath'].'/calendar/inc/class.boicalendar.inc.php');
+                          $boicalendar = new boicalendar();
+
+                          $ical = $icalService->getComponent('vevent');
+                          $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br /><br />';
+                          $content.= '<span style="font-size: 12" >';
+                          $notExist = false;
+
+                          foreach ($ical['attendee'] as $attendee)
+                          {
+                                if($attendee['params']['PARTSTAT'] == 'ACCEPTED')
+                                {
+                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'ACCEPTED',$attendee['params']['CN']))
+                                    {
+                                        $content.= $this->functions->getLang('User').' ';
+                                        if($attendee['params']['CN'])
+                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
+                                        else
+                                            $content.= '<b>'.$attendee['value'].'</b> ';
+
+                                        $content.= $this->functions->getLang('accepted your event');
+                                    }
+                                    else
+                                        $notExist = true;
+                                }
+
+                                if($attendee['params']['PARTSTAT'] == 'TENTATIVE')
+                                {
+                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'TENTATIVE',$attendee['params']['CN']))
+                                    {
+                                        $content.= $this->functions->getLang('User').' ';
+                                        if($attendee['params']['CN'])
+                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
+                                        else
+                                            $content.= '<b>'.$attendee['value'].'</b> ';
+
+                                        if($ical['description']['value'])
+                                            $content.= ' <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
+                                        else
+                                            $content.= $this->functions->getLang('provisionally accepted you event');
+                                    }
+                                    else
+                                         $notExist = true;
+                                }
+
+                                if($attendee['params']['PARTSTAT'] == 'DECLINED')
+                                {
+                                    if($boicalendar->updateExParticipantState($ical['uid']['value'],$attendee['value'],'DECLINED',$attendee['params']['CN']))
+                                    {
+                                        $content.= $this->functions->getLang('User').' ';
+                                        if($attendee['params']['CN'])
+                                            $content.= '<b>'.$attendee['params']['CN'].'</b> ';
+                                        else
+                                            $content.= '<b>'.$attendee['value'].'</b> ';
+
+                                        if($ical['description']['value'])
+                                            $content.= ' <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
+                                        else
+                                            $content.= $this->functions->getLang('provisionally decline you event');
+                                    }
+                                    else
+                                        $notExist = true;
+                                }
+                          }
+                          if($notExist)
+                            $content.= '<b><span style="color:red">'.$this->functions->getLang('This event does not exist on its agenda').'.</span></b>';
+                          $content.= '</span><br /><br />';
+
+                        break;
+
+                      case 'CANCEL':
+
+                          $ical = $icalService->getComponent('vevent');
+                          $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br /><br />';
+                          $content.= '<span style="font-size: 12" >';
+                          $content.= '<b><span style="color:red">'.$this->functions->getLang('Your event has been canceled').'</span></b>';
+   
+                          if($ical['description']['value'])
+                              $content.= ' <br /> <br /> '.str_replace('\n','<br />',nl2br($ical['description']['value']));
+
+                          $content.= '<br /><b>* '.$this->functions->getLang('To remove the event from your calendar to import the iCal file attached').'.</b>';
+                          $content.= '</span><br /><br />';
+                        break;
+
+                    case 'REQUEST':
+
+                        $ical = $icalService->getComponent('vevent');
+                        if($ical['dtstart']['value']['tz'] == 'Z')
+                        {
+                            $tz = $_SESSION['phpgw_info']['user']['preferences']['common']['tz_offset'];
+                            $ical['dtstart']['value']['hour'] += $tz;
+                            $ical['dtend']['value']['hour'] += $tz;
+                        }
+                        
+                        $content.= '<b>'.$this->functions->getLang('Event Calendar').'</b><br />'.
+                                   ' <br /> <b>'.$this->functions->getLang('Title').': </b>'.$ical['summary']['value'].
+                                   ' <br /> <b>'.$this->functions->getLang('Location').': </b>'.$ical['location']['value'].
+                                   ' <br /> <b>'.$this->functions->getLang('Details').': </b>'. str_replace('\n','<br />',nl2br($ical['description']['value']));
+                        $content.= ' <br /> <b>'.$this->functions->getLang('Start') . ':  </b>' . $ical['dtstart']['value']['day'] . "/" . $ical['dtstart']['value']['month']  . "/" . $ical['dtstart']['value']['year']  . " - " . $ical['dtstart']['value']['hour']  . ":" . $ical['dtstart']['value']['min'] ;
+                        $content.= ' <br /> <b>'.$this->functions->getLang('End') . ': </b>' . $ical['dtend']['value']['day'] . "/" . $ical['dtend']['value']['month']  . "/" . $ical['dtend']['value']['year']  . " - " . $ical['dtend']['value']['hour']  . ":" . $ical['dtend']['value']['min'] ;
+
+                        if($ical['organizer']['params']['CN'])
+                             $content.= ' <br /> <b>'.$this->functions->getLang('Organizer').': </b>'.$ical['organizer']['params']['CN'].' -  <a href="MAILTO:'.$ical['organizer']['value'].'">'.$ical['organizer']['value'].'</a></li>' ;
+                        else
+                             $content.= ' <br /> <b>'.$this->functions->getLang('Organizer').': </b> <a href="MAILTO:'.$ical['organizer']['value'].'">'.$ical['organizer']['value'].'</a>' ;
+
+                        if($ical['attendee'])
+                        {
+                            $att = ' <br /> <b>'.$this->functions->getLang('Participants').': </b>';
+                            $att .= '<ul> ';
+                            foreach ($ical['attendee'] as $attendee)
+                            {
+                                if($attendee['params']['CN'])
+                                    $att .= '<li>'.$attendee['params']['CN'].' -  <a href="MAILTO:'.$attendee['value'].'">'.$attendee['value'].'</a></li>'  ;
+                                else
+                                    $att .= '<li><a href="MAILTO:'.$attendee['value'].'">'.$attendee['value'].'</a></li>'  ;
+                            }
+                            $att .= '</ul> <br />'  ;
+                        }
+                        $content.= $att;
+
+                        break;
+                    default:
+                        break;
+                }
+      
+            }
+            return $content;
+        }
+        
 	function htmlfilter($body)
 	{
@@ -1454,8 +1759,11 @@
                 $image['cid'] = eregi_replace("<", "", $image['cid']);
                 $image['cid'] = eregi_replace(">", "", $image['cid']);
+				//if is Draft Ticket #1256
+				$image['cid'] = str_replace("@localhost", "@prognus.org", $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);   
+				
+                $body = str_replace("src=\"cid:".$image['cid']."\"", " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\" ", $body);
+                $body = str_replace("src='cid:".$image['cid']."'", " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\"", $body);
+                $body = str_replace("src=cid:".$image['cid'], " src=\"./inc/get_archive.php?msgFolder=$msg_folder&msgNumber=$msgno&indexPart=".$image['pid']."\"", $body); 
 			}
 		return $body;
@@ -1474,7 +1782,13 @@
                 $body = @mb_eregi_replace("POSITION: ABSOLUTE;","",$body);
 
+		//Remove Comentario Expresso 
+				$findExpCom[] = '<!-- TAG <'; 
+				$findExpCom[] = '> Removed by ExpressoMail -->'; 
+				$body = str_replace($findExpCom, '', $body); 
+		///--------------------------------// 
+
 		// tags to be removed doe to security reasons
 		$tag_list = Array(
-			'head','blink','object','frame','iframe',
+			'blink','object','frame','iframe',
 			'layer','ilayer','plaintext','script',
 			'applet','embed','frameset','xml','xmp'
@@ -1482,6 +1796,9 @@
 
 		foreach($tag_list as $index => $tag) {
-			$body = @mb_eregi_replace("<$tag\\b[^>]*>(.*?)</$tag>", "<!-- TAG <$tag> Removed by ExpressoMail -->", $body); 
-			}
+			$body = @mb_eregi_replace("<$tag\\b[^>]*>(.*?)</$tag>", '', $body); 
+			}
+		
+		$body = @mb_eregi_replace("<meta[^>]*>", '', $body);
+		$body = @mb_eregi_replace("<base[^>]*>", '', $body); 
 		
 		//try to wrap CSS code instead of remove STYLE tags
@@ -1492,4 +1809,5 @@
 		$regs_found = array(); 
 		$tags_found = @mb_eregi("<style\b[^>]*>(.*?)</style>", $body, $regs_found);
+		$wrapper_class = 'ExpressoCssWrapper'.time();
 		
 		foreach ($regs_found as $block_found) { 
@@ -1504,4 +1822,5 @@
 			
 			$prefix = ".$wrapper_class "; 
+            if( isset($css->css[41]) && count($css->css[41] > 0))
 			foreach ($css->css[41] as $key => $value) {
 						//explode multiple selectors per block 
@@ -1541,35 +1860,18 @@
 	    //--------------------------------------------------------------------------------------------// 	
 
-		//$body = $this->replace_links($body);
-
 		//Remoção de tags <span></span> para correção de erro no firefox
-//               if($_SESSION['phpgw_session']['phpgw_app_sessions']['phpgwapi']['browser_agent']['content'] != 'IE'){
-//                   $body = mb_eregi_replace("<span><span>","",$body);
-//                   $body = mb_eregi_replace("</span></span>","",$body);
-//               }
-
-                $body = mb_ereg_replace("(<p[^>]*)(text-indent:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body);
-                $body = mb_ereg_replace("(<p[^>]*)(margin-right:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body);
-                $body = mb_ereg_replace("(<p[^>]*)(margin-left:[^>;]*-[^>;]*;)([^>]*>)","\\1\\3",$body);
-//Correção para compatibilização com Outlook, ao visualizar a mensagem 
+		//Comentado pois estes replaces geram erros no html da msg, não se pode garantir que o os </span></span> sejam realmente os fechamentos dos <span><span>.
+		//Caso realmente haja a nescessidade de remover estes spans deve ser repensado a forma de como faze-lo.
+		//		$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 = mb_ereg_replace('<!\[endif\]-->', '<!--[endif]--->', $body);
-		$body = str_replace("\x00", '', $body);
 		
 		return  "<div class=\"$wrapper_class\"><span>".$body.'</span></div>';
-	}
-
-
-
+
+	}
 	
-	/**
-	* Substitui os links do callback
-	*
-	* @license    http://www.gnu.org/copyleft/gpl.html GPL
-	* @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @sponsor    Caixa Econômica Federal
-	* @param      $matches
-	*/
 	function replace_links_callback($matches)  
 	{
@@ -1595,8 +1897,4 @@
 		$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
-		$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 );
 
 	}
@@ -1716,20 +2014,13 @@
 	{
 
-		$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']."' 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 = "./inc/show_img.php?msg_num=".$msg_number."&msg_folder=".$msg_folder."&msg_part=".$image['pid'];
-				 $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++;
+		if (!count($images)) return '';
                
+		foreach ($images as $key => $value) { 
+			$images[$key]['width']  = 160; 
+			$images[$key]['height'] = 120; 
+			$images[$key]['url']    = "inc/get_archive.php?msgFolder=".$msg_folder."&msgNumber=".$msg_number."&indexPart=".$image['pid']."&image=true"; 
     		}
-    	return $thumbs_array;
+
+		return json_encode($images); 
 	}
 
@@ -1755,9 +2046,11 @@
 		$folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
 		$msgs_number = explode(",",$params['msgs_number']);
+		if(array_key_exists('border_ID' ,$params))
 		$border_ID = $params['border_ID'];
-
+		else
+			$border_ID = '';
 		$return = array();
 
-		if ($params['get_previous_msg']){
+		if (array_key_exists('get_previous_msg' , $params) &&  $params['get_previous_msg']){
 			$return['previous_msg'] = $this->get_info_previous_msg($params);
 			// Fix problem in unserialize function JS.
@@ -1786,4 +2079,6 @@
 	{
 
+		$return = array();
+		$return['new_msgs'] = 0;
 		$folder = $params['folder'];
 		$msg_range_begin = $params['msg_range_begin'];
@@ -1799,17 +2094,36 @@
 			return array();
 
+		$return['new_msgs'] = imap_num_recent($this->mbox);
 		$num_msgs = (count($msgs_in_the_server) - imap_num_recent($this->mbox));
+
 		$msgs_in_the_client = explode(",", $msgs_existent);
 
 		$msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
+
+		if(count($msg_to_insert) > 0 && $return['new_msgs'] == 0 && $msgs_in_the_client[0] != ""){
+			$aux = 0;
+			while(array_key_exists($aux, $msg_to_insert)){
+				if($msg_to_insert[$aux] > $msgs_in_the_client[0]){
+					$return['new_msgs'] += 1;
+				}
+				$aux++;
+			}
+		}else if(count($msg_to_insert) > 0 && $msgs_in_the_server && $msgs_in_the_client[0] != "" && $return['new_msgs'] == 0){
+			$aux = 0;
+			while(array_key_exists($aux, $msg_to_insert)){
+				if($msg_to_insert[$aux] == $msgs_in_the_server[$aux]){
+					$return['new_msgs'] += 1;
+				}
+				$aux++;
+			}
+		}else if($num_msgs < $msg_range_end && $return['new_msgs'] == 0 && count($msg_to_insert) > 0){
+			$return['tot_msgs'] = $num_msgs;
+		}
+		
 		$msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
-
 		$msgs_to_exec = array();
 		foreach($msg_to_insert as $msg_number)
 			$msgs_to_exec[] = $msg_number;
 		//sort($msgs_to_exec);
-
-		$return = array();
-                $return['new_msgs'] = imap_num_recent($this->mbox);
 		$i = 0;
 		foreach($msgs_to_exec as $msg_number)
@@ -1864,5 +2178,5 @@
 			$return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
 			//$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
-			if(!$return[$i]['from']['name'])
+			if(!$return[$i]['from']['name'] || trim($return[$i]['from']['name']) === '')
 				$return[$i]['from']['name'] = $return[$i]['from']['email'];
 
@@ -1873,18 +2187,33 @@
 			$to = $header->to;
 			$return[$i]['to'] = array();
+			if(isset($to[0]->personal))
 			$tmp = imap_mime_header_decode($to[0]->personal);
+			if(trim($return[$i]['to']['name']) === '')
+				$return[$i]['to']['name'] = $to[0]->mailbox . "@" . $to[0]->host;
+			else
 			$return[$i]['to']['name'] = $tmp[0]->text;
 			$return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
 			$return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
+			if(isset($header->cc))
 			$cc = $header->cc;
-			if ( ($cc) && (!$return[$i]['to']['name']) ){
+
+			if ( isset($cc) && (!$return[$i]['to']['name'] || $return[$i]['to']['name'] == '@') ){
 				$return[$i]['to']['name'] =  $cc[0]->personal;
 				$return[$i]['to']['email'] = $cc[0]->mailbox . "@" . $cc[0]->host;
 			}
-			$return[$i]['subject'] = $this->decode_string($header->fetchsubject);
-
+                        $return[$i]['subject'] = ( isset( $header->fetchsubject ) ) ? $this->decode_string($header->fetchsubject) : '';
+                        if($return[$i]['subject'] == "" || $return[$i]['subject'] == '' || $return[$i]['subject'] == null ){
+				$return[$i]['subject'] = $this->functions->getLang("(no subject)   ");
+			}
 			$return[$i]['Size'] = $header->Size;
 			$return[$i]['reply_toaddress'] = $header->reply_toaddress;
 
+			if($return[$i]['to']['email'] == '@' || $return[$i]['to']['email'] =='undisclosed-recipients@' || $return[$i]['to']['name'] =='undisclosed-recipients@'
+				|| $return[$i]['to']['name'] == null){
+				$return[$i]['to']['email'] = $return[$i]['from']['email'];
+				$return[$i]['to']['name'] = $return[$i]['from']['name'];
+				$return[$i]['to']['full'] = $return[$i]['reply_toaddress'];
+			}
+			
 			$return[$i]['attachment'] = array();
 			if (!isset($imap_attachment))
@@ -1949,14 +2278,17 @@
 	{
 		$mbox_stream = $this->open_mbox();
-		if($params && $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){
+		if($params &&  array_key_exists('onload', $params)   &&  $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){
 			$this->delete_mailbox(array("del_past" => "INBOX".$this->imap_delimiter."decifradas"));
 		}
 
 		$inbox = 'INBOX';
+		$drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
+		$sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
+		$spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
 		$trash = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
-		$drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
-		$spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
-		$sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
+		if(array_key_exists('uid2cn', $_SESSION['phpgw_info']['user']['preferences']['expressoMail'] ))
 		$uid2cn = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']; 
+		else
+			$uid2cn = false;
 		// Free others requests 
 		session_write_close(); 
@@ -1964,5 +2296,5 @@
 		$serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}"; 
 		
-		if ( $params && $params['noSharedFolders'] )
+		if ( $params && isset($params['noSharedFolders']) )
 			$folders_list = array_merge(imap_getmailboxes($mbox_stream, $serverString, 'INBOX' ), imap_getmailboxes($mbox_stream, $serverString, 'INBOX/*' ) );
 		else
@@ -1973,5 +2305,9 @@
 		$tmp = array(); 
 		$resultMine = array(); 
+		$resultSharedMine = array(); 
 		$resultDefault = array(); 
+		$resultSharedDefault = array(); 
+		$aux = "";
+		$qtd = -1 ;
 
 		if (is_array($folders_list)) {
@@ -1994,9 +2330,6 @@
                             if( $folderUser != "INBOX" && $folderUser != "" )
                             {
-                               $Permission = imap_getacl( $mbox_stream, $folderUser );
+                               $Permission = @imap_getacl( $mbox_stream, $folderUser );
                             }
-
-                            if( $Permission )
-                            {
                                 $tmp_folder_id[1] = mb_convert_encoding( $tmp_folder_id[1], "ISO-8859-1", "UTF7-IMAP" );
 
@@ -2005,5 +2338,8 @@
 					continue;
 				}
+				
+				if(isset($status->unseen))
 				$result[$i]['folder_unseen'] = $status->unseen;
+				
 				$folder_id = $tmp_folder_id[1];
 				$result[$i]['folder_id'] = $folder_id;
@@ -2027,15 +2363,37 @@
 				else
 					$result[$i]['folder_hasChildren'] = 0;
-
+				$user = explode($this->imap_delimiter , $tmp_folder_id[1]);
 				switch ($tmp_folder_id[1]) {
 					case $inbox:
+					case $drafts:
 					case $sent:
-					case $drafts:
 					case $spam:
 					case $trash:
 						$resultDefault[]=$result[$i];
 						break;
+					case "user". $this->imap_delimiter . $user[1]:
+					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']:
+					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']:
+					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']:
+					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']:
+						if($aux != $user[1]){
+							$aux = $user[1];
+							$qtd += 1;
+						}
+						if( isset($resultSharedDefault[$qtd]) && !is_array($resultSharedDefault[$qtd]))
+							$resultSharedDefault[$qtd] = array();
+						$resultSharedDefault[$qtd][]=$result[$i];
+						break;	
 					default:
+						if($user[0] == $inbox)
 						$resultMine[]=$result[$i];
+						else{
+							if($aux != $user[1]){
+								$aux = $user[1];
+								$qtd += 1;
+							}
+							if(!is_array($resultSharedDefault[$qtd]))
+								$resultSharedMine[$qtd] = array();
+							$resultSharedMine[$qtd][]=$result[$i];
 				}
 
@@ -2045,8 +2403,8 @@
 		}
 
-		if ( $params && !$params['noQuotaInfo'] ) {
+		if ( $params && !array_key_exists('noQuotaInfo',$params) ) {
 			//Get quota info of current folder
 			$current_folder = "INBOX";
-			if($params && $params['folder'])
+			if($params && isset($params['folder']))
 				$current_folder = $params['folder'];
 
@@ -2078,8 +2436,8 @@
 					$resultDefault2[0] = $resultDefault[$key];
 					break;
-				case $sent: 
+				case $drafts: 
 					$resultDefault2[1] = $resultDefault[$key];
 					break;
-				case $drafts: 
+				case $sent: 
 					$resultDefault2[2] = $resultDefault[$key];
 					break;
@@ -2093,13 +2451,45 @@
 		}
 		
-		if ( $params && $params['folderType'] && $params['folderType'] == 'default' )
+		$shareds = array();
+		if(!empty($resultSharedDefault))
+		for($i = 0; $i <= $qtd; $i++){			
+			foreach ($resultSharedDefault[$i] as $key => $folder_id)
+			{
+				$user = explode($this->imap_delimiter , $resultSharedDefault[$i][$key]['folder_id']);
+
+				switch ($resultSharedDefault[$i][$key]['folder_id']) {
+					case "user". $this->imap_delimiter . $user[1]: 
+						$resultSharedDefault2[0] = $resultSharedDefault[$i][$key];
+						break;
+					case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']:  
+						$resultSharedDefault2[1] = $resultSharedDefault[$i][$key];
+						break;	
+					case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']:  
+						$resultSharedDefault2[2] = $resultSharedDefault[$i][$key];
+						break;
+					case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']:  
+						$resultSharedDefault2[3] = $resultSharedDefault[$i][$key];
+						break;
+					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']:
+						$resultSharedDefault2[4] = $resultSharedDefault[$i][$key];
+						break;
+				}
+			}
+			if($resultDefault2 != null)
+				$shareds = array_merge($shareds, $resultSharedDefault2);
+			if(isset($resultSharedMine[$i]) && $resultSharedMine[$i] != null)
+				$shareds = array_merge($shareds, $resultSharedMine[$i]);
+			$resultSharedDefault2 = array();
+		}
+		if ( $params && isset($params['folderType']) && $params['folderType'] == 'default' )
 			return array_merge($resultDefault2, $arr_quota_info);
 
-		if ( $params && $params['folderType'] && $params['folderType'] == 'personal' )
+		if ( $params && array_key_exists('folderType', $params) && $params['folderType'] == 'personal' )
 			return array_merge($result2, $arr_quota_info);
 
 		// Merge default folders and personal
 		$result2 = array_merge($resultDefault2, $result2);
-		
+		if(!empty($shareds))
+			$result2 = array_merge($result2, $shareds);
 		return array_merge($result2, $arr_quota_info);
 	}
@@ -2214,9 +2604,12 @@
 	function send_mail($params)
 	{
-		include_once("class.phpmailer.php");
-		$mail = new PHPMailer();
+		require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php';
+		$mailService = ServiceLocator::getService('mail');
+
 		include_once("class.db_functions.inc.php");
 		$db = new db_functions();
 		$fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
+		$message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false; 
+		
 		##
 		# @AUTHOR Rodrigo Souza dos Santos
@@ -2238,4 +2631,14 @@
 		$ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
 		$ccoaddress = implode(',',$db->getAddrs(explode(',',$params['input_cco'])));
+
+		$toaddress  = preg_replace('/<\s+/', '<', $toaddress);			
+		$toaddress  = preg_replace('/\s+>/', '>', $toaddress);
+			
+		$ccaddress  = preg_replace('/<\s+/', '<', $ccaddress);
+		$ccaddress  = preg_replace('/\s+>/', '>', $ccaddress);
+		
+		$ccoaddress = preg_replace('/<\s+/', '<', $ccoaddress);
+		$ccoaddress = preg_replace('/\s+>/', '>', $ccoaddress);
+		
 		$replytoaddress = $params['input_replyto'];
 		$subject = $params['input_subject'];
@@ -2246,5 +2649,114 @@
 		$signed = $params['input_return_digital'];
 
-		if($params['smime'])
+		$message_attachments = $params['message_attachments'];
+                 
+                if(substr($params['input_to'],-1) == ',')
+                    $params['input_to'] = substr($params['input_to'],0,-1);
+
+                if(substr($params['input_cc'],-1) == ',')
+                    $params['input_cc'] = substr($params['input_cc'],0,-1);
+
+                if(substr($params['input_cco'],-1) == ',')
+                    $params['input_cco'] = substr($params['input_cco'],0,-1);
+                
+
+                // Valida numero Maximo de Destinatarios 
+                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'] > 0) 
+                { 
+                    $sendersNumber = count(explode(',',$params['input_to'])); 
+
+                    if($params['input_cc']) 
+                        $sendersNumber +=  count(explode(',',$params['input_cc'])); 
+                    if($params['input_cco']) 
+                        $sendersNumber +=  count(explode(',',$params['input_cco'])); 
+
+                    $userMaxmimumSenders = $db->getMaximumRecipientsUser($this->username); 
+                    if($userMaxmimumSenders) 
+                    { 
+                        if($sendersNumber > $userMaxmimumSenders) 
+                            return $this->functions->getLang('Number of recipients greater than allowed'); 
+                    } 
+                    else 
+                    { 
+                        $ldap = new ldap_functions(); 
+                        $groupsToUser = $ldap->get_user_groups($this->username); 
+
+                        $groupMaxmimumSenders = $db->getMaximumRecipientsGroup($groupsToUser); 
+
+                        if($groupMaxmimumSenders > 0) 
+                        { 
+                            if($sendersNumber > $groupMaxmimumSenders) 
+                                return $this->functions->getLang('Number of recipients greater than allowed'); 
+                        } 
+                        else 
+                        { 
+                             if($sendersNumber > $_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients']) 
+                             return $this->functions->getLang('Number of recipients greater than allowed'); 
+                        } 
+                    } 
+
+                } 
+                //Fim Valida numero maximo de destinatarios 
+                
+                
+                //Valida envio de email para shared accounts
+                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoMail_block_institutional_comunication'] == 'true')
+                {
+                    $ldap = new ldap_functions();
+                    $arrayF = explode(';', $params['input_from']);
+
+                    /*
+                     * Verifica se o remetente n?o ? uma conta compartilhada
+                     */
+                    if(!$ldap->isSharedAccountByMail($arrayF[1]))
+                    {
+                        $groupsToUser = $ldap->get_user_groups($this->username);
+                        $sharedAccounts = $ldap->returnSharedsAccounts($toaddress, $ccaddress, $ccoaddress);
+
+                        /*
+                         * Pega o UID do remetente
+                         */
+                        $uidFrom = $ldap->mail2uid($arrayF[1]);
+
+                         /*
+                         * Remove a conta compartilhada caso o uid do remetente exista na conta compartilhada
+                         */
+                        foreach ($sharedAccounts as $key => $value)
+                        {
+                            if($value)
+                                 $acl = $this->getaclfrombox($value);
+
+                             if (array_key_exists($uidFrom, $acl))
+                                 unset($sharedAccounts[$key]);
+
+                        }
+
+                        /*
+                         * Caso ainda exista contas compartilhadas, verifica se existe alguma exce??o para estas contas
+                         */
+                        if(count($sharedAccounts) > 0)
+                          $accountsBlockeds = $db->validadeSharedAccounts($this->username, $groupsToUser, $sharedAccounts);
+
+                        /*
+                         * Retorna as contas compartilhadas bloqueadas
+                         */
+                        if(count($accountsBlockeds) > 0)
+                        {
+                            $return = '';
+
+                            foreach ($accountsBlockeds as $accountBlocked)
+                                $return.= $accountBlocked.', ';
+
+                             $return = substr($return,0,-2);
+
+                             return $this->functions->getLang('you are blocked  from sending mail to the following addresses').': '.$return;
+                        }
+                    }
+                }
+                // Fim Valida envio de email para shared accounts
+                
+                
+//	    TODO - implementar tratamento SMIME no novo serviço de envio de emails e retirar o AND false abaixo
+	    if($params['smime'] AND false)
         {
             $body = $params['smime'];
@@ -2285,9 +2797,8 @@
         else
         {
-            $body = $params['body'];
 	    //Compatibilização com Outlook, ao encaminhar a mensagem
-	    $body = mb_ereg_replace('<!--\[','<!-- [',$body);
+			$body = mb_ereg_replace('<!--\[', '<!-- [', $params['body']);
         }
-		//echo "<script language=\"javascript\">javascript:alert('".$body."');</script>";
+
 		$attachments = $_FILES;
 		$forwarding_attachments = $params['forwarding_attachments'];
@@ -2298,56 +2809,58 @@
 			//build shared folder path
 			$newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
-			if( $this->folder_exists($newfolder) ) $folder = $newfolder;
-			else $folder =  $params['folder'];  			
+			if($this->folder_exists($newfolder)) 
+				$folder = $newfolder;
+			else 
+				$folder = $params['folder'];
+			
 		} else	{
 			$folder = $params['folder'];			
 		}
 		
-		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
+		$folder = mb_convert_encoding($folder, 'UTF7-IMAP','ISO_8859-1');
+		$folder = preg_replace('/INBOX[\/.]/i', 'INBOX'.$this->imap_delimiter, $folder);
 		$folder_name = $params['folder_name'];
-		// Fix problem with cyrus delimiter changes.
-		// 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 ($folder != 'null'){
-			$mail->SaveMessageInFolder = $folder;
-		}
-////////////////////////////////////////////////////////////////////////////////////////////////////
-		$mail->SMTPDebug = false;
-
-		if($signed && !$params['smime'])
+
+//		TODO - tratar assinatura e remover o AND false
+		if($signed && !$params['smime'] AND false)
 		{
             $mail->Mailer = "smime";
 			$mail->SignedBody = true;
 		}
-		else
-            $mail->IsSMTP();
-
-		$mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
-		$mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
-		$mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
-		$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
-		if($fromaddress){
-			$mail->Sender = $mail->From;
-			$mail->SenderName = $mail->FromName;
-			$mail->FromName = $fromaddress[0];
-			$mail->From = $fromaddress[1];
-		}
-
-		$this->add_recipients("to", $toaddress, &$mail);
-		$this->add_recipients("cc", $ccaddress, &$mail);
+
+
+		if($fromaddress)
+                	$mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
+               else
+                	$mailService->setFrom ('"'.$_SESSION['phpgw_info']['expressomail']['user']['firstname'].' '.$_SESSION['phpgw_info']['expressomail']['user']['lastname'].'" <'.$_SESSION['phpgw_info']['expressomail']['user']['email'].'>');
+		//$mailService->addTo($toaddress);
+		//$mailService->addCc($ccaddress);
+		$bol = $this->add_recipients('to', $toaddress, $mailService);
+		if(!$bol){
+			return $this->parse_error("Invalid Mail:", $toaddress);
+		}
+		$bol = $this->add_recipients('cc', $ccaddress, $mailService);
+		if(!$bol){
+			return $this->parse_error("Invalid Mail:", $ccaddress);
+		}
 		$allow = $_SESSION['phpgw_info']['server']['expressomail']['allow_hidden_copy']; 
  		 
- 		                if( $allow ) 
+		if($allow) 
  		                { 
-		$this->add_recipients("cco", $ccoaddress, &$mail);
+			//$mailService->addBcc($ccoaddress);
+			$bol = $this->add_recipients('cco', $ccoaddress, $mailService);
+
+			if(!$bol){
+				return $this->parse_error("Invalid Mail:", $ccoaddress);
+			}
  		                }
-		$mail->AddReplyTo($replytoaddress);
-		$mail->Subject = $subject;
-		$mail->IsHTML( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true );
-		$mail->Body = $body;
-
-        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed))	// a msg deve ser enviada cifrada...
+
+		$mailService->setSubject($subject);
+		$isHTML = ( (array_key_exists('type', $params) && in_array(strtolower($params['type']), array('html', 'plain')) ) ? 
+						strtolower($params['type']) != 'plain' : true );
+	
+
+//		TODO - tratar mensagem criptografada e remover o AND false abaixo
+        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed) AND false)	// a msg deve ser enviada cifrada...
 		{
 			$email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
@@ -2440,6 +2953,7 @@
             $mail->Certs_crypt = $aux_mails;
         }
-                // Build CID images 
-		$this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments); 
+						
+		if( count($forwarding_attachments) > 0 )// Build CID images 
+			$this->buildEmbeddedImages($mailService,$msg_uid,$forwarding_attachments, $body); 
 
 		//	Build Uploading Attachments!!!
@@ -2447,5 +2961,4 @@
 		{
 			$total_uploaded_size = 0;
-			$upload_max_filesize = str_replace("M","",$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
 			foreach ($attachments as $attach)
 			{
@@ -2454,8 +2967,12 @@
 				if($attach['name']=='Unknown')
 					continue;
-				$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
+				$mailService->addFileAttachment($attach['tmp_name'], $attach['name'], $this->get_file_type($attach['name']), 'base64', 'attachment');
 				$total_uploaded_size = $total_uploaded_size + $attach['size'];
 			}
-			if( $total_uploaded_size > $upload_max_filesize){
+                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
+                        {
+         
+                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
+                            if( $total_uploaded_size > $upload_max_filesize)
 				return $this->parse_error("message file too big");
 			}
@@ -2464,5 +2981,5 @@
 
 			$total_uploaded_size = 0;
-			$upload_max_filesize = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024;
+			
 			foreach($local_attachments as $local_attachment) {
 				$file_description = unserialize(rawurldecode($local_attachment));
@@ -2471,11 +2988,15 @@
 					$tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
 				}
-				$mail->AddAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], "base64", $this->get_file_type($tmp[2]));  // optional name
+				$mailService->addFileAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], $this->get_file_type($tmp[2]), 'base64', 'attachment');
 				$total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
 			}
-			if( $total_uploaded_size > $upload_max_filesize)
-				return 'false';
-		}
-////////////////////////////////////////////////////////////////////////////////////////////////////
+			if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
+                        {
+                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
+                            if( $total_uploaded_size > $upload_max_filesize)
+                                   return $this->parse_error("message file too big");
+                        }
+		}
+
 		//	Build Forwarding Attachments!!!
 		if (count($forwarding_attachments) > 0)
@@ -2490,34 +3011,157 @@
 			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 = 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];
+				if(!array_search(trim($fileName),$name_cid_files)) {
+					$filename_dec = html_entity_decode(rawurldecode($fileName));
+					$mailService->addStringAttachment($fileContent, $filename_dec, $this->get_file_type($file_description[2]), $file_description[4] );
+
+				}
+			}
+		}
+		
+		//Build Message Attachments!!!
+		if(count($message_attachments) > 0 ) 
+		{
+			foreach($message_attachments as $folder_name => $messages)
+			{
+				foreach ($messages as $message_number => $message_subject) 
+				{
+					if (!$message_subject)
+						$message_subject  = 'no title.eml';
+					else 
+						$message_subject .= '.eml';
+					
+					if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
+						$rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
+					else{
+						$mbox_stream = $this->open_mbox($folder_name);
+						$rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
 					}
-					$file_description = $tmp;
-					$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
-					$fileName = $file_description[2];
-					if(!array_search(trim($fileName),$name_cid_files)) {
-						$mail->AddStringAttachment($fileContent,html_entity_decode(rawurldecode($fileName)), $file_description[4], $this->get_file_type($file_description[2]));
-				}
-			}
-		}
-
-////////////////////////////////////////////////////////////////////////////////////////////////////
-		// Important message
+							
+					$return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
+					$mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
+				}
+			}
+		}
+		
+		$message_size_total += strlen($params['body']);   /* Tamanho do corpo da mensagem. */
+		$message_size_total += $total_uploaded_size;      /* Incrementa com os anexos da nova mensagem, se houver. */
+		
+		////////////////////////////////////////////////////////////////////////////////////////////////////	
+		/** 
+		* Faz a validação pelo tamanho máximo de mensagem permitido para o usuário. Se o usuário não estiver em nenhuma regra, usa o tamanho padrão.
+		 */
+		$default_max_size_rule = $db->get_default_max_size_rule();	
+		if(!$default_max_size_rule)
+		{
+			$default_max_size_rule = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024; /* hack para não bloquear o envio de email quando não for configurado um tamanho padrão */
+		}
+		else
+		{
+			foreach($default_max_size_rule as $i=>$value)
+			{		
+				$default_max_size_rule = $value['config_value'];
+			}				
+		}
+		
+		$default_max_size_rule = $default_max_size_rule * 1024 * 1024;		  /* Tamanho da regra padrão, em bytes */
+		$id_user = $_SESSION['phpgw_info']['expressomail']['user']['userid'];	
+		
+		
+		$ldap = new ldap_functions();
+		$groups_user = $ldap->get_user_groups($id_user);
+
+		$size_rule_by_group = array();	
+		foreach($groups_user as $k=>$value_)
+		{	
+			$rule_in_group = $db->get_rule_by_user_in_groups($k);
+			if ($rule_in_group != "")
+				array_push($size_rule_by_group, $rule_in_group);
+		}	
+		
+		$n_rule_groups = 0;
+		$maior_valor_regra_grupo = 0;
+		foreach($size_rule_by_group as $i=>$value)
+		{
+			if(is_array($value[0]))
+			{
+				$n_rule_groups++;
+				if($value[0]['email_max_recipient'] > $maior_valor_regra_grupo)
+					$maior_valor_regra_grupo = $value[0]['email_max_recipient'];
+			}
+		}
+		
+		if($default_max_size_rule)
+		{
+			$size_rule = $db->get_rule_by_user($_SESSION['phpgw_info']['expressomail']['user']['userid']);
+
+			if(!$size_rule && $n_rule_groups == 0) /* O usuário não está em nenhuma regra por usuário nem por grupo. Vai usar a regra padrão. */
+			{
+				if($message_size_total > $default_max_size_rule)
+					return $this->functions->getLang("Message size greateruler than allowed (Default rule)");
+			}
+
+			else 
+			{
+				if(count($size_rule) > 0) /* Verifica se existe regra por usuário. Se houver, ela vai se sobresair das regras por grupo. */
+				{
+					$regra_mais_permissiva = 0;
+					foreach($size_rule as $i=>$value)
+					{	
+						if($regra_mais_permissiva < $value['email_max_recipient'])
+							$regra_mais_permissiva = $value['email_max_recipient'];
+					}
+					$regra_mais_permissiva = $regra_mais_permissiva * 1024 * 1024;			
+					if($message_size_total > $regra_mais_permissiva)
+						return $this->functions->getLang("Message size greater than allowed (Rule By User)");
+				}
+				else /* Regra por grupo */
+				{		
+					$maior_valor_regra_grupo = $maior_valor_regra_grupo * 1024 * 1024;			
+					if($message_size_total > $maior_valor_regra_grupo)
+						return $this->functions->getLang("Message size greater than allowed (Rule By Group)");	
+				
+				
+				}
+			}
+		}
+		/** 
+         * Fim da validação do tamanho da regra do tamanho de mensagem.
+		 */
+		 ////////////////////////////////////////////////////////////////////////////////////////////////////
+		
+		
+		
+		
+		
+		if($isHTML)
+			$mailService->setBodyHtml($body);
+		else
+			$mailService->setBodyText($body);
+
 		if($is_important)
-			$mail->isImportant();
-
-////////////////////////////////////////////////////////////////////////////////////////////////////
-		// Disposition-Notification-To
-		if ($return_receipt)
-			$mail->ConfirmReadingTo = $_SESSION['phpgw_info']['expressomail']['user']['email'];
-////////////////////////////////////////////////////////////////////////////////////////////////////
-
-		$sent = $mail->Send();
-
-		if(!$sent)
-		{
-   			return $this->parse_error($mail->ErrorInfo);
+			$mailService->addHeaderField('Importance','High');
+
+		if($return_receipt)
+			$mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
+
+
+		if ($folder != 'null'){
+			$mbox_stream = $this->open_mbox($folder);
+			@imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen");
+		}
+
+		$sent = $mailService->send();
+
+		if($sent !== true)
+		{
+   			return $this->parse_error($sent);
 		}
 		else
@@ -2536,6 +3180,5 @@
    				error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
 			}
-			if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
-		   	   $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
+			if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
 				$contacts = new dynamic_contacts();
 				$new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
@@ -2554,43 +3197,46 @@
 	* @param     $forwarding_attachments anexos
 	*/
-	function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments) 
+
+	function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments ,&$body)
 	{ 
-		//      Build CID for embedded Images!!! 
-		$pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU'; 
+		//Procura e retorna em $cids_imgs imagens embarcadas no corpo do e-mail
+		$pattern = '/src=("[^"]*?get_archive.php\?msgFolder=(.+)?&(amp;)?msgNumber=(.+)?&(amp;)?indexPart=(.+)?")/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); 
-
+		preg_match_all( $pattern , $body , $cid_imgs , PREG_PATTERN_ORDER );
+		//-------------------------------------------------------------------//
+
+		$attPostions = array(); //Array que linka a possição da imagem com o indice que esta se encontra no array $forwarding_attachments
+
+		foreach ($forwarding_attachments as $i => $v){ // Monta o  array de link
+			$desc = unserialize(rawurldecode($v));
+			$attPostions[$desc[3]] = $i;
+		}
+
+		//Intera as imagens encontradas
+		foreach($cid_imgs[6] as $j => $val)
+        {		
+			$cid = base_convert(microtime().$j, 10, 36); //Gera um cid
+			$body = str_replace($cid_imgs[1][$j], '"cid:'.$cid.'@'.$_SESSION['phpgw_info']['expressomail']['server']['domain_name'].'"', $body ); //tira o src da imagem e coloca o cid, ele e concatenado com o domain do servidor por que a biblioteaca mime faz isso na hora de gerar o mime.
 			$count    = strlen($cid_imgs[6][$j]);
-			$position = substr($cid_imgs[6][$j], 2, $count);
-			$position--;
 					
-			$attach_img = $forwarding_attachments[$position];
+			$attach_img = $forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']];
 			$file_description = unserialize(rawurldecode($attach_img));
 			
 			if (is_array($file_description))
 				foreach($file_description as $i => $descriptor)				
-					$file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
+                      $file_description[$i] = mb_ereg_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"; 
+                $fa = $this->get_forwarding_attachment2($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
+                $fileContent = &$fa['binary'];
+				$fileName = $fa['name'];
+				$fileCode = $fa['encoding'];
+				$fileType =  $fa['type'];
 				$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[3] = '0.'.(string)($j+1);
 				$file_attached[4] = 'base64'; 
 				$file_attached[5] = strlen($fileContent); //Size of file 
@@ -2599,5 +3245,5 @@
 
  				if ($file_attached[3] == $file_description[3] || $msg_uid == 'undefined')
-					unset($forwarding_attachments[$position]);
+					unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
 				
 			} 
@@ -2607,8 +3253,8 @@
 				$fileName = $file_description[2]; 
 				$fileCode = $file_description[4]; 
-				$file_description[3] = '0.'.($j+1);
+				$file_description[3] = '0.'.(string)($j+1);
 				$file_description[6] = $cid_imgs[6][$j];
 				$fileType = $this->get_file_type($file_description[2]); 
-				unset($forwarding_attachments[$position]);
+				unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
 				if (!empty($file_description)) 
 				{ 
@@ -2617,12 +3263,7 @@
 				} 
 			} 
-			$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); 
+				$mail->addStringImage($fileContent,$fileType,$fileName, $cid);					
 		}
 
@@ -2654,4 +3295,5 @@
 		$full_address = preg_replace("/, ?,/",",",$full_address);
 		$parse_address = imap_rfc822_parse_adrlist($full_address, "");
+		$bolean = true;
 		foreach ($parse_address as $val)
 		{
@@ -2665,11 +3307,11 @@
 				{
 					case "to":
-						$mail->AddAddress($val->mailbox."@".$val->host);
+						$mail->AddTo($val->mailbox."@".$val->host);
 						break;
 					case "cc":
-						$mail->AddCC($val->mailbox."@".$val->host);
+						$mail->AddCc($val->mailbox."@".$val->host);
 						break;
 					case "cco":
-						$mail->AddBCC($val->mailbox."@".$val->host);
+						$mail->AddBcc($val->mailbox."@".$val->host);
 						break;
 				}
@@ -2680,24 +3322,39 @@
 				{
 					case "to":
-						$mail->AddAddress($val->mailbox."@".$val->host, $val->personal);
+						$mail->AddTo($val->mailbox."@".$val->host, $val->personal);
 						break;
 					case "cc":
-						$mail->AddCC($val->mailbox."@".$val->host, $val->personal);
+						$mail->AddCc($val->mailbox."@".$val->host, $val->personal);
 						break;
 					case "cco":
-						$mail->AddBCC($val->mailbox."@".$val->host, $val->personal);
+						$mail->AddBcc($val->mailbox."@".$val->host, $val->personal);
 						break;
 				}
 			}
-		}
-		return true;
+			if($val->mailbox == "UNEXPECTED_DATA_AFTER_ADDRESS"){
+				$bolean = false;
+		}
+			
+		}
+		return $bolean;
 	}
 
 	function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
+	{
+            include_once $_SESSION['rootPath'].'/expressoMail1_2/inc/class.attachment.inc.php';
+            $attachment = new attachment();
+			$attachment->decodeConf['rfc_822bodies'] = true; //Forçar a não decodificação de mensagens em anexo.
+            $attachment->setStructureFromMail($msg_folder, $msg_number);
+            return $attachment->getAttachment($msg_part);
+	}
+
+        function get_forwarding_attachment2($msg_folder, $msg_number, $msg_part, $encoding)
 	{
             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);
+            $return = $attachment->getAttachmentInfo($msg_part);
+            $return['binary'] = $attachment->getAttachment($msg_part);
+            return $return;
 	}
 
@@ -2762,8 +3419,9 @@
 					else
 						$from = $header->from;
-
+					if(isset($from[0]->personal))
 					$tmp = imap_mime_header_decode($from[0]->personal);
-
-					if ($tmp[0]->text != "")
+					else
+						$tmp = null;
+					if (isset($tmp[0]->text))
 						$sort[$iuid] = $tmp[0]->text;
 					else
@@ -2786,7 +3444,9 @@
 				$sort = array_reverse($sort,true);
 		}
-
-		if(!is_array($sort))
+		if(empty($sort) or !is_array($sort)){
 			$sort = array();
+		}
+		
+			
 
 
@@ -2836,7 +3496,7 @@
 		$folder = $params['folder'];
 		$mbox_stream = $this->open_mbox($folder);
-                $newmailbox = urldecode($params['new_folder']);
+		$newmailbox = ($params['new_folder']);
                 $newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
-                $new_folder_name = urldecode($params['new_folder_name']);
+		$new_folder_name = $params['new_folder_name'];
                 $msgs_number = $params['msgs_number'];
 		$return = array('msgs_number' => $msgs_number,
@@ -2866,4 +3526,5 @@
         }
         //Este bloco tem a finalidade de transformar o CPF das pastas compartilhadas em common name
+        if(array_key_exists('uid2cn', $_SESSION['phpgw_info']['user']['preferences']['expressoMail'])){
         if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']){
             if (substr($new_folder_name,0,4) == 'user'){
@@ -2877,4 +3538,5 @@
             }
         }
+		}
 
 		// Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior.
@@ -2883,4 +3545,5 @@
 			$return['previous_msg'] = $this->get_info_previous_msg($params);
 			// Fix problem in unserialize function JS.
+			if(array_key_exists('body', $return['previous_msg']))
 			$return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
 		}
@@ -2941,165 +3604,132 @@
 	}
 
+
 	function save_msg($params)
 	{
-
-		include_once("class.phpmailer.php");
-		$mail = new PHPMailer();
-		include_once("class.db_functions.inc.php");
-		$toaddress = $params['input_to'];
-		$ccaddress = $params['input_cc'];
-		$ccoaddress = $params['input_cco'];
+		require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php';
+		$mailService = ServiceLocator::getService('mail');
+
 		$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);
+		$body = preg_replace("/\r/","" ,$body);
+		$body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );
 		$forwarding_attachments = $params['forwarding_attachments'];
+		$message_attachments    = $params['message_attachments'];
 		$attachments = $params['FILES'];
 		$return_files = $params['FILES'];
+		$message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false; 
 
                 if(is_array($params['local_attachments'])){
                     foreach ($params['local_attachments'] as $key => $local_attach) {
                        $tmp = unserialize(urldecode($local_attach));
-                       $attachments[$key]['name'] = $tmp[2];
-                       $return_files[$key]['name'] = $tmp[2];
+			   $attachments[$key]['name'] = urldecode($tmp[2]);
+			   $return_files[$key]['name'] = urldecode($tmp[2]);
                     }
                 }
 
-
-		$folder = $params['folder'];
-		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
-		// Fix problem with cyrus delimiter changes.
-		// 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'];
-		$mail->Port = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpPort'];
-		$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;
-		
-		$return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments);
+		$folder = mb_convert_encoding($params['folder'], "UTF7-IMAP","ISO_8859-1");
+		$folder = @eregi_replace("INBOX[/.]", "INBOX".$this->imap_delimiter, $folder);
+
+		$mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
+		$mailService->addTo($params['input_to']);
+		$mailService->addCc( $params['input_cc']);
+		$mailService->addBcc($params['input_cco']);
+		$mailService->setSubject($params['input_subject']);
+
+		if($is_important){
+			$mailService->addHeaderField('Importance','High');
+		}
+
+		if($return_receipt)
+			$mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
+
+		$isHTML = ( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true );
+
+		
+		if( count($forwarding_attachments) > 0 )
+			$return_forward = $this->buildEmbeddedImages($mailService, $msg_uid, $forwarding_attachments , $body);
+			
+		//Build Message Attachments!!!
+		if(count($message_attachments) > 0 ) 
+		{
+			foreach($message_attachments as $folder_name => $messages)
+			{
+				foreach ($messages as $message_number => $message_subject) 
+				{
+					if (!$message_subject)
+						$message_subject  = 'no title.eml';
+					else 
+						$message_subject .= '.eml';
+					
+					if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
+						$rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
+					else{
+						$mbox_stream = $this->open_mbox($folder_name);$mbox_stream = $this->open_mbox($folder_name);
+						$rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
+					}
+											
+					$return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
+					$mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
+				}
+			}
+		}
+		
 		$imagesParts = array(); 
 
+		if(count($return_forward) > 0 )
 		foreach ($return_forward as $value)
 			$imagesParts[$value[6]] = $value[3]; 	
 
-	//	Build Forwarding Attachments!!!
+		//Build Forwarding Attachments!!!
+		if(count($forwarding_attachments) > 0 ) 
+		{
 			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[2] = html_entity_decode($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]));
+				$mailService->addStringAttachment($fileContent, $file_description[2], $this->get_file_type($file_description[2]), $file_description[4] );
+			}
 			}
 
 		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!!!
+
+		//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
-					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;
-					}
-					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)
-					{
-						$new_width = $width;
-						$new_height = $height;
-					}
-					else if ($width > $max_resolution)
-					{
-						$new_width = $max_resolution;
-						$new_height = $height*($new_width/$width);
-					}
-					else 
-					{
-						$new_height = $max_resolution;
-						$new_width = $width*($new_height/$height);
-					}
-					$image_new = imagecreatetruecolor($new_width, $new_height);
-					imagecopyresampled($image_new, $image_big, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
-                                        $tmpDir = '/tmp';
-
-                                       // $tmpDir = ini_get("session.save_path");
-					$_file = "/cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".dat";
-					imagejpeg($image_new,$tmpDir.$_file, 85);
-					$mail->AddAttachment($tmpDir.$_file, $attach['name'], "base64", $this->get_file_type($tmpDir.$_file));
-				}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->error_count = 0; // reset errors
-		$mail->SetMessageType();
-		$header = $mail->CreateHeader();
-		$body = $mail->CreateBody();
+				$mailService->addFileAttachment($attach['tmp_name'],  $attach['name'],$attach['type'],  'base64', 'attachment');
+
+
+		if (!$body)
+			$body = ' ';
+		
+		if($isHTML)
+			$mailService->setBodyHtml($body);
+		else
+			$mailService->setBodyText($body);
+
 
 		$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");
+		$return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft");
+
 		$status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
 		$return['msg_no'] = $status->uidnext - 1;
@@ -3110,5 +3740,8 @@
 			imap_close($mbox_stream);
 			
-		if (is_array($return_files))
+		$returnFiles = array();                  
+		$ii = 0;
+                		
+		if(count($return_files) > 0)
 		{
 			foreach ($return_files as $index => $_attachment) 
@@ -3116,21 +3749,19 @@
 				if (array_key_exists("name", $_attachment))
 				{
-				unset($return_files[$index]);
-				$return_files[$index] = $_attachment['name']."_SIZE_".$return_files[$index][1] = $_attachment['size'];
-			}
-			else
+					$returnFiles[$ii]['name'] = base64_encode($_attachment['name']);
+					$returnFiles[$ii]['size'] = $_attachment['size'];
+					$ii++;
+			}
+				else if($_attachment[2])
 			{
-				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();
-
+					$returnFiles[$ii]['name'] = base64_encode($_attachment[2]); 
+					$returnFiles[$ii]['size'] = $_attachment[5];         
+					$ii++;
+			}
+		}
+		}
+		$return['files'] = serialize($returnFiles);
+		$return["subject"] = $params['input_subject'];
+		if (!$return['append'])	$return['append'] = imap_last_error();
 		return $return;
 	}
@@ -3139,20 +3770,9 @@
 	{
 		$folder = $params['folder'];
-		$rowids_to_set = $params['msgs_to_set']; // contains the row ids
+		$msgs_to_set = $params['msgs_to_set'];
 		$flag = $params['flag'];
 		$return = array();
-		$return["rowids_to_set"] = $rowids_to_set;
+		$return["msgs_to_set"] = $msgs_to_set;
 		$return["flag"] = $flag;
-
-		$msgs_to_set = '';
-		foreach (explode(',',$rowids_to_set) as $msg) {//extracting message ids
-			$pos = strpos($msg,'_');
-			if ($pos===false)
-				$msgs_to_set .= ','.$msg;
-			else
-				$msgs_to_set .= ','.substr($msg,0,$pos);
-		}
-		$msgs_to_set = substr($msgs_to_set,1);
-		$return["msgs_to_set"] = $msgs_to_set;
 
 		if(!$this->mbox && !is_resource($this->mbox))
@@ -3213,4 +3833,6 @@
 		$file_name = strtolower($file_name);
 	   	$strFileType = strrev(substr(strrev($file_name),0,4));
+	   	if ($strFileType == ".eml")
+   			return "message/rfc822";
 	   	if ($strFileType == ".asf")
    			return "video/x-ms-asf";
@@ -3710,7 +4332,5 @@
 							{
 							    $filter .= '"'.$filter_array[1].'"';
-							}
-							if(trim($filter_array[0]) == 'BEFORE' )
-							{
+							}else if(trim($filter_array[0]) == 'BEFORE' ){
                                                             $filter .= '"'.$this->make_search_date($filter_array[1],true).'"';
 							}else{
@@ -3721,5 +4341,5 @@
 				}
 				
-				$name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
+				$name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
 				$filter = $this->remove_accents($filter);
 
@@ -3737,5 +4357,5 @@
 				}
 				else
-					$folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
+					$folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO-8859-1" );
 				
 				if(!is_resource($mbox_stream))
@@ -3760,5 +4380,5 @@
 							{
 								$elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream); 
-								$elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ); 
+								$elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" ); 
 								$elem['uid'] = $new_search;
                                                                 /* compare dates in ordering */
@@ -3770,4 +4390,5 @@
 				}
 				else{
+					$search_criteria = imap_search($mbox_stream, $filter, SE_UID);
                                     if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag'])
                                     {
@@ -3785,26 +4406,17 @@
                                                 }
                                             }
-
-                                            $new_filter = trim(preg_replace('/UNFLAGGED|FLAGGED/','',$filter));
-
-                                            $search_without_flagged = imap_search($mbox_stream, $new_filter, SE_UID);
-
-                                            if (strpos($filter,"UNFLAGGED") === false)
+						if((count($flagged_msgs) >0) && (strpos($filter,"UNFLAGGED") === false))
                                             {
-                                                $search_criteria = array_intersect($search_without_flagged, $flagged_msgs);
-                                            }
-                                            else
+                                                    $arry_diff = is_array($search_criteria) ? array_diff($flagged_msgs,$search_criteria):$flagged_msgs;
+                                                    foreach($arry_diff as $msg)
                                             {
-                                                $search_criteria = array_diff($search_without_flagged,$flagged_msgs);
+							$search_criteria[] = $msg;
                                             }
                                         }
-                                        else
+						else if((count($flagged_msgs) >0) && (is_array($search_criteria)) && (!strpos($filter,"UNFLAGGED") === false))
                                         {
-                                            $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
+                                                    $search_criteria = array_diff($search_criteria,$flagged_msgs);
                                         }
                                     }
-                                    else
-                                    {
-                                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
                                     }
 
@@ -3814,5 +4426,5 @@
                                         {
                                             $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream);
-                                            $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" );
+							$elem['boxname'] = mb_convert_encoding( $name_box, "ISO-8859-1", "UTF7-IMAP" ); 
                                             $elem['uid'] = $new_search;
                                             /* compare dates in ordering */
@@ -4036,6 +4648,9 @@
 		$mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
 		else
-		  $mbox_acl = imap_getacl($mbox_stream, $user);
+		  $mbox_acl = @imap_getacl($mbox_stream, $user);
+                if(isset($mbox_acl[$this->username]))
 		return $mbox_acl[$this->username];
+                else 
+                    return '';
 	}
 
@@ -4166,4 +4781,15 @@
 	
 	
+/**
+* Descrição do método
+*
+* @license    http://www.gnu.org/copyleft/gpl.html GPL
+* @author     
+* @sponsor    Caixa Econômica Federal
+* @author     
+* @param      <tipo> <$msg_number> <Número da mensagem>
+* @return     <cabeçalho da mensagem>
+* @access     <public>
+*/	
 	function get_header($msg_number)
 	{
@@ -4172,5 +4798,5 @@
 			return false;
 
-		if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
+		if($header->Flagged != "F" ) {
 			$flag = preg_match('/importance *: *(.*)\r/i',
 						imap_fetchheader($this->mbox, imap_msgno($this->mbox, $msg_number))
@@ -4191,9 +4817,12 @@
         $imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
         $imap_options = '/notls/novalidate-cert';
+
+	
+        $folder = mb_convert_encoding( $folder, "UTF7-IMAP","ISO-8859-1");
+
         $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
-        if(imap_last_error())
-        {
+        
+        if(imap_last_error() === 'Mailbox already exists')
             imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
-       	}
         if($timestamp){
 			$pdate = date_parse(date('r')); // pega a data atual do servidor (TODO: pegar a data da mensagem local) 
@@ -4205,6 +4834,6 @@
         	fputs($f,base64_encode($source));
             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));
+            $command = "python ".$_SESSION['rootPath']."/expressoMail1_2/imap.py \"$imap_server\" \"$imap_port\" \"$username\" \"$password\" \"$timestamp\" \"$folder\" \"$file\"";
+            $return['command']= exec($command);
         }else{
             $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
@@ -4230,4 +4859,9 @@
                   imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
                 }
+	
+        //Ignorando erro de AUTH=Plain
+        if($return['error'] === 'SECURITY PROBLEM: insecure server advertised AUTH=PLAIN')
+            $return['error'] = false;
+                                
         if($mbox_stream)
             imap_close($mbox_stream);
@@ -4235,18 +4869,20 @@
     }
 
-    function show_decript($params){
+        function show_decript($params,$dec=0){ 
         $source = $params['source'];
-        //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log'); 
- 		        $source = str_replace(" ", "+", $source,$i); 
  		 
+        //error_log("source: $source\nversao: " . PHP_VERSION); 	 
+        if ($dec == 0) 
+        { 
+            $source = str_replace(" ", "+", $source,$i); 
  		        if (version_compare(PHP_VERSION, '5.2.0', '>=')){ 
  		            if(!$source = base64_decode($source,true)) 
- 		                return "error ".$source."Espaços ".$i; 
+                    return "error ".$source."Espaï¿?os ".$i; 
  		 
  		        } 
  		        else { 
  		            if(!$source = base64_decode($source)) 
- 		                return "error ".$source."Espaços ".$i;
-
+                    return "error ".$source."Espaï¿?os ".$i; 
+            } 
         }
 
@@ -4316,16 +4952,14 @@
         $dest_folder = $params['folder'];
         $sources = explode("#@#@#@",$params['source']);
-        $timestamps = explode("#@#@#@",$params['timestamp']);
+        //Add user timeszone
+        $timestamps 	= $params['timestamp'] + $this->functions->CalculateDateOffset(); 
         $flags = explode("#@#@#@",$params['flags']);
 
-        foreach($sources as $index=>$src)
-        {
-            if($src!="")
-            {
+		foreach($sources as $index=>$src) {
+			if($src!=""){
 		$source = $this->treat_base64_from_post($src);
-		$insert = $this->insert_email($source,$dest_folder,$timestamps[$index],$flags[$index]);
+ 		        $insert = $this->insert_email($source, mb_convert_encoding( $dest_folder,"ISO-8859-1","UTF-8"), $timestamps,$flags[$index]); 
             }
 	}
-        
         return $insert;
     }
@@ -4357,10 +4991,4 @@
 			$msg_user = "Sem mensagem!"; 
  		         
-		$toaddresses = $_SESSION['phpgw_info']['expressomail']['server']['sugestoes_email_to'];  
- 		$toaddress   = explode(",", $toaddresses);       
- 		                 
- 		for($i=0; $i<count($toaddress); $i++) 
-			$toaddress[$i] = trim($toaddress[$i]); 
- 		                 
 		$toname       = $_SESSION['phpgw_info']['expressomail']['user']['fullname']; 
  		 
@@ -4372,10 +5000,155 @@
  		                "$msg_user</body><br><br><hr>"; 
  		             
+ 		require_once $_SESSION['rootPath'] . '/API/class.servicelocator.php';
  		$mailService = ServiceLocator::getService('mail');      
- 		$mailService->addAttachment($mail_content, 'report.eml', 'application/text'); 
- 		$mailService->send($toaddress, $GLOBALS['phpgw_info']['user']['email'], $title, $body); 
+ 		$mailService->addStringAttachment($mail_content, 'report.eml', 'application/text'); 
+ 		$mailService->sendMail($_SESSION['phpgw_info']['expressomail']['server']['sugestoes_email_to'], $GLOBALS['phpgw_info']['user']['email'], $title, $body); 
 	} 
 	
+	function array_msort($array, $cols)
+	{
+		$colarr = array();
+		foreach ($cols as $col => $order) {
+			$colarr[$col] = array();
+			foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
+		}
+		$params = array();
+		foreach ($cols as $col => $order) {
+			$params[] =& $colarr[$col];
+			$params = array_merge($params, (array)$order);
+		}
+		call_user_func_array('array_multisort', $params);
+		$ret = array();
+		$keys = array();
+		$first = true;
+		foreach ($colarr as $col => $arr) {
+			foreach ($arr as $k => $v) {
+				if ($first) { $keys[$k] = substr($k,1); }
+				$k = $keys[$k];
+				if (!isset($ret[$k])) $ret[$k] = $array[$k];
+				$ret[$k][$col] = $array[$k][$col];
+			}
+			$first = false;
+		}
+		
+		return $ret;
+
+	}
+        
+        function parseCriteriaSearchMail($search)
+        {
+            $criteria = '';
+            $searchArray = explode(' ', $search);
+
+            foreach ($searchArray as $v)
+                if(trim($v) !== '' )
+                    $criteria .= 'TEXT "'.$v.'" ' ;
+           
+            return $criteria;
+        }
+        
+	function quickSearchMail( $params )
+	{
+		$return = array();
+		$return['folder'] = $params['folder'];
+		if(!is_array($params['folder']))
+			$params['folder'] = array( $params['folder'] );
+		
+		if(!isset($params['sort']))
+			$params['sort'] = SORTDATE;
+				
+		$params['search'] = mb_convert_encoding($params['search'], 'UTF-8',mb_detect_encoding($params['search'].'x', 'UTF-8, ISO-8859-1'));
+		
+		$i = 0;		
+		if(!isset($params['page'])) $params['page'] = 0;
+		$end = ($this->prefs['max_email_per_page'] * ((int)$params['page'] + 1));	
+		$ini = $end - $this->prefs['max_email_per_page'] ;
+		$count = 0;
+		
+                $search = $this->parseCriteriaSearchMail($params['search']);
+		                
+		foreach ($params['folder'] as $folder) 
+		{
+			$imap = $this->open_mbox( $folder ) ;
+			$msgIds = imap_sort( $imap , SORTDATE , 0 , SE_UID , $search ,'UTF-8');
+						
+			$count += count($msgIds);  
+			
+			foreach ($msgIds as $ii => $v)
+			{				
+				$msg = imap_headerinfo ( $imap,  imap_msgno($imap, $v) );
+				$return['msgs'][$i]['from'] = '';
+				
+				$from = $msg->from[0]->mailbox;
+				if($msg->from[0]->personal != "")
+					$from = $msg->from[0]->personal;
+				$return['msgs'][$i]['from'] 	= mb_convert_encoding($this->decode_string($from), 'UTF-8'); 
+				
+				$return['msgs'][$i]['subject'] = ' ';
+				
+				$subject = imap_mime_header_decode($msg->subject);
+				foreach ($subject as $tmp)
+					$return['msgs'][$i]['subject'] .= mb_convert_encoding($tmp->text, 'UTF-8');
+				
+				$return['msgs'][$i]['flag'] = ' ';
+				$return['msgs'][$i]['flag'] .= $msg->Unseen ? $msg->Unseen : '';
+				$return['msgs'][$i]['flag'] .= $msg->Recent ? $msg->Recent : '';	
+				$return['msgs'][$i]['flag'] .= $msg->Flagged ? $msg->Flagged : '';	
+				$return['msgs'][$i]['flag'] .= $msg->Draft ? $msg->Draft : '';	
+				$return['msgs'][$i]['flag'] .= $msg->Answered ? $msg->Answered : '';	
+				$return['msgs'][$i]['flag'] .= $msg->Deleted ? $msg->Deleted : '';	
+				
+				$return['msgs'][$i]['udate'] = gmdate("d/m/Y",$msg->udate + $this->functions->CalculateDateOffset()); 
+				$return['msgs'][$i]['udatecomp'] = substr ($return['msgs'][$i]['udate'], -4) ."-". substr ($return['msgs'][$i]['udate'], 3, 2) ."-". substr ($return['msgs'][$i]['udate'], 0, 2);
+			    $return['msgs'][$i]['date'] =   $msg->udate;
+				$return['msgs'][$i]['size'] =  $msg->Size;
+				$return['msgs'][$i]['boxname'] = $folder;
+				$return['msgs'][$i]['uid'] = $v;
+				$i++;
+			} 	
+		}
+		
+		$return['num_msgs'] = $count;
+		
+		if(!isset($return['msgs']))
+			$return['msgs'] = array();
+		
+		define('SORTBOX', 69);
+		define('SORTWHO', 2);
+		define('SORTBOX_REVERSE', 69);
+		define('SORTWHO_REVERSE', 2);
+		define('SORTDATE_REVERSE', 0);
+		define('SORTSUBJECT_REVERSE', 3);
+		define('SORTSIZE_REVERSE', 6);
+		
+		switch (constant( $params['sort'] )){
+			case 0 : $sA = 'date'; break;
+			case 2 : $sA = 'from'; break;
+			case 69 : $sA = 'boxname'; break;
+			case 3 : $sA = 'subject'; break;
+			case 6 : $sA = 'size'; break;
+	} 
 	
+		$return['msgs'] = $this->array_msort($return['msgs'] , array( $sA => SORT_ASC));
+			
+		if(strpos($params['sort'],'REVERSE') !== false)
+			$return['msgs'] = array_reverse($return['msgs']);	
+				
+		
+		$k = -1;
+		$nMsgs = array();
+		
+		foreach ($return['msgs'] as $v)
+		{		
+			$k++;
+			if($k < $ini || $k >= $end ) continue;			
+			$nMsgs[] = $v;
+		}
+		$return['msgs'] = $nMsgs;
+		$return = json_encode($return);		
+		$return = base64_encode($return);
+	
+		return $return;
+	}
 	
     function get_quota_folders(){ 
@@ -4416,4 +5189,23 @@
 	    return $data; 
     }  
+    
+    function getaclfrombox($mail)
+        {
+                $mailArray = explode('@', $mail);
+                $boxacl = $mailArray[0];
+                $return = array();
+
+                if(!$this->mbox)
+                     $this->open_mbox();
+
+                $mbox_acl = imap_getacl($this->mbox, 'user' . $this->imap_delimiter . $boxacl);
+
+                foreach ($mbox_acl as $user => $acl)
+                {
+                        if ($user != $boxacl )
+                            $return[$user] = $acl;
+                }
+                return $return;
+        }
 }
 ?>
