Index: trunk/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 432)
+++ trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 449)
@@ -7,5 +7,5 @@
 {
 	var $public_functions = array
-	(
+	(	
 		'get_range_msgs'				=> True,
 		'get_info_msg'					=> True,
@@ -26,7 +26,7 @@
 		$this->imap_port	  = $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
 		$this->imap_delimiter = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDelimiter'];
-		$this->functions	  = new functions();
+		$this->functions	  = new functions();		
 		$this->has_cid = false;
-
+		
 		if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
 		{
@@ -53,13 +53,13 @@
 		$msg_range_begin = $params['msg_range_begin'];
 		$msg_range_end = $params['msg_range_end'];
-		$sort_box_type = $params['sort_box_type'];
+		$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_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
-
+		$sort_array_msg = $this-> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);				
+		
 		$return = array();
 		$i = 0;
 		$num_msgs = (is_array($sort_array_msg) ? count($sort_array_msg) : 0);
-		if($num_msgs) {
+		if($num_msgs) { 
 			for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= $num_msgs)); $msg_range_begin++)
 		{
@@ -68,6 +68,6 @@
 			$header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
 			if (!is_object($header))
-				return false;
-
+				return false;			
+			
 			$return[$i]['Recent'] = $header->Recent;
 			$return[$i]['Unseen'] = $header->Unseen;
@@ -77,12 +77,12 @@
 			else {
 				$return[$i]['Answered']	= $header->Answered;
-				$return[$i]['Draft']	= $header->Draft;
+				$return[$i]['Draft']	= $header->Draft;	
 			}
 			$return[$i]['Deleted'] = $header->Deleted;
 			$return[$i]['Flagged'] = $header->Flagged;
-
+			
 			$return[$i]['msg_number'] = $msg_number;
 			//$return[$i]['msg_folder'] = $folder;
-
+			
 			$date_msg = date("d/m/Y",$header->udate);
 			if (date("d/m/Y") == $date_msg)
@@ -90,5 +90,5 @@
 			else
 				$return[$i]['udate'] = $date_msg;
-
+			
 			$from = $header->from;
 			$return[$i]['from'] = array();
@@ -108,17 +108,17 @@
 
 			$return[$i]['Size'] = $header->Size;
-
+			
 			$return[$i]['attachment'] = array();
-			$return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
+			$return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);			
 			$i++;
 		}
 		}
-		$return['num_msgs'] = $num_msgs;
-
+		$return['num_msgs'] = $num_msgs;		
+		
 		return $return;
 	}
-
+	
 	function decode_string($string)
-	{
+	{	
 		if ((strpos(strtolower($string), '=?iso-8859-1') !== false) || (strpos(strtolower($string), '=?windows-1252') !== false))
 		{
@@ -145,5 +145,5 @@
 			return $this->htmlspecialchars_encode($string);
 	}
-
+	
 	function get_info_msg($params)
 	{
@@ -151,12 +151,8 @@
 		$msg_number = $params['msg_number'];
 		$msg_folder = $params['msg_folder'];
-
+		
 		if(!$this->mbox || !is_resource($this->mbox))
-			$this->mbox = $this->open_mbox($msg_folder);
-
-
-		//if(!$this->mbox)
-		//	$this->mbox = $this->open_mbox($msg_folder);
-
+			$this->mbox = $this->open_mbox($msg_folder);		
+		
 		$header = @imap_headerinfo($this->mbox, imap_msgno($this->mbox, $msg_number), 80, 255);
 		if (!$header) {
@@ -166,10 +162,10 @@
 		$all_header = explode("\n", imap_fetchheader($this->mbox, $msg_number, FT_UID));
 		$return_get_body = $this->get_body_msg($msg_number, $msg_folder);
-
+		
 		$return['body'] 		= $return_get_body['body'];
 		$return['attachments'] 	= $return_get_body['attachments'];
 		$return['thumbs'] 		= $return_get_body['thumbs'];
 		$return['signature']	= $return_get_body['signature'];
-
+		
 		foreach($all_header as $line) {
 			if (eregi("^Disposition-Notification-To", $line)) {
@@ -180,5 +176,5 @@
 		$return['Recent']	= $header->Recent;
 		$return['Unseen']	= $header->Unseen;
-		$return['Deleted']	= $header->Deleted;
+		$return['Deleted']	= $header->Deleted;		
 		$return['Flagged']	= $header->Flagged;
 
@@ -188,10 +184,10 @@
 		else {
 			$return['Answered']	= $header->Answered;
-			$return['Draft']	= $header->Draft;
+			$return['Draft']	= $header->Draft;	
 		}
 
 		$return['msg_number'] = $msg_number;
 		$return['msg_folder'] = $msg_folder;
-
+	
 		$date_msg = date("d/m/Y",$header->udate);
 		if (date("d/m/Y") == $date_msg)
@@ -199,17 +195,17 @@
 		else
 			$return['udate'] = $date_msg;
-
-		$return['msg_day'] = $date_msg;
+		
+		$return['msg_day'] = $date_msg; 
 		$return['msg_hour'] = date("H:i",$header->udate);
-
+		
 		if (date("d/m/Y") == $date_msg) //no dia
 		{
 			$return['fulldate'] = date("d/m/Y H:i",$header->udate);
 			$return['smalldate'] = date("H:i",$header->udate);
-
+			
 			$timestamp_now = strtotime("now");
 			$timestamp_msg_time = $header->udate;
 			$timestamp_diff = $timestamp_now - $timestamp_msg_time;
-
+			
 			if (gmdate("H",$timestamp_diff) > 0)
 			{
@@ -233,5 +229,5 @@
 			$return['smalldate'] = date("d/m/Y",$header->udate);
 		}
-
+		
 		$from = $header->from;
 		$return['from'] = array();
@@ -248,5 +244,5 @@
 		else
 			$return['from']['full'] = $return['from']['email'];
-
+		
 		// Sender attribute
 		$sender = $header->sender;
@@ -300,6 +296,6 @@
 		{
 			$return['toaddress2'] = "&lt;Empty&gt;";
-		}
-
+		}	
+		
 		$cc = $header->cc;
 		$return['cc'] = "";
@@ -329,5 +325,39 @@
 		{
 			$return['cc'] = "";
-		}
+		}	
+
+		##
+		# @AUTHOR Rodrigo Souza dos Santos
+		# @DATE 2008/09/12
+		# @BRIEF Adding the BCC field.
+		##
+		$bcc = $header->bcc;
+		$return['bcc'] = "";
+		if (!empty($bcc))
+		{
+			foreach ($bcc as $tmp_bcc)
+			{
+				if (!empty($tmp_bcc->personal))
+				{
+					$personal_tmp_bcc = imap_mime_header_decode($tmp_bcc->personal);
+					$return['bcc'] .= '"' . $personal_tmp_bcc[0]->text . '"';
+					$return['bcc'] .= " ";
+					$return['bcc'] .= "&lt;";
+					$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
+					$return['bcc'] .= "&gt;";
+					$return['bcc'] .= ", ";
+				}
+				else
+				{
+					$return['bcc'] .= $tmp_bcc->mailbox . "@" . $tmp_bcc->host;
+					$return['bcc'] .= ", ";
+				}
+			}
+			$return['bcc'] = $this->del_last_two_caracters($return['bcc']);
+		}
+		else
+		{
+			$return['bcc'] = "";
+		}	
 
 		$reply_to = $header->reply_to;
@@ -361,8 +391,8 @@
 		$return['Size'] = $header->Size;
 		$return['reply_toaddress'] = $header->reply_toaddress;
-
+		
 		return $return;
 	}
-
+	
 	function get_body_msg($msg_number, $msg_folder)
 	{
@@ -371,15 +401,15 @@
 		$msg->fetch_structure($msg_number);
 		$return = array();
-		$return['attachments'] = $this-> download_attachment($msg,$msg_number);
+		$return['attachments'] = $this-> download_attachment($msg,$msg_number);		
 		if(!$this->has_cid)
 		{
 			$return['thumbs']  = $this->get_thumbs($msg,$msg_number,urlencode($msg_folder));
 			$return['signature'] = $this->get_signature($msg,$msg_number,$msg_folder);
-		}
-
+		}			
+		
 		if(!$msg->structure[$msg_number]->parts) //Simple message, only 1 piece
 		{
 			$attachment = array(); //No attachments
-
+			
 			$content = '';
 			if (strtolower($msg->structure[$msg_number]->subtype) == "plain")
@@ -392,5 +422,5 @@
 			}
 		}
-		else
+		else 
 		{ //Complicated message, multiple parts
 			$html_body = '';
@@ -398,8 +428,8 @@
 			$has_multipart = true;
 			$this->has_cid = false;
-
+			
 			if (strtolower($msg->structure[$msg_number]->subtype) == "related")
 				$this->has_cid = true;
-
+			
 			if (strtolower($msg->structure[$msg_number]->subtype) == "alternative")
                         {
@@ -409,5 +439,5 @@
 					$file_type = strtolower($msg->file_type[$msg_number][$values]);
 					if($file_type == "text/html")
-						$show_only_html = true;
+				$show_only_html = true;			
 				}
                         }
@@ -417,13 +447,13 @@
 			foreach($msg->pid[$msg_number] as $values => $msg_part)
 			{
-
+				
 				$file_type = strtolower($msg->file_type[$msg_number][$values]);
 				if($file_type == "message/rfc822")
 					$has_multipart = false;
-
+	
 				if($file_type == "multipart/alternative")
 					$has_multipart = false;
-
-				if(($file_type == "text/plain"
+	
+				if(($file_type == "text/plain" 
 					|| $file_type == "text/html")
 					&& $file_type != 'attachment')
@@ -433,9 +463,9 @@
 						// if TXT file size > 100kb, then it will not expand.
 						if(!($file_type == "text/plain" && $msg->fsize[$msg_number][$values] > 102400)) {
-							$content .= nl2br(htmlentities($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values])));
+							$content .= nl2br(htmlentities($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values])));							
 						}
 					}
 					// if HTML attachment file size > 300kb, then it will not expand.
-					else if($file_type == "text/html"  && $msg->fsize[$msg_number][$values] < 3072000)
+					else if($file_type == "text/html"  && $msg->fsize[$msg_number][$values] < 307200)
 					{
 						$content .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]);
@@ -445,21 +475,21 @@
 				else if($file_type == "message/delivery-status"){
 					$content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
-					$content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));
+					$content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));						
 
 				}
 				else if($file_type == "message/rfc822" || $file_type == "text/rfc822-headers"){
-
+					
 					include_once("class.imap_attachment.inc.php");
 					$att = new imap_attachment();
 					$attachments =  $att -> get_attachment_info($this->mbox,$msg_number);
-					if($attachments['number_attachments'] > 0) {
+					if($attachments['number_attachments'] > 0) {												
 						foreach($attachments ['attachment'] as $index => $attachment){
 							if(strtolower($attachment['type']) == "delivery-status" ||
-								strtolower($attachment['type']) == "rfc822" ||
+								strtolower($attachment['type']) == "rfc822" ||								
 								strtolower($attachment['type']) == "rfc822-headers" ||
 								strtolower($attachment['type']) == "plain"
 							){
-								$obj = imap_rfc822_parse_headers(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values]);
-								$content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";
+								$obj = imap_rfc822_parse_headers(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values]);					
+								$content .= "<hr align='left' width='95%' style='border:1px solid #DCDCDC'>";					
 								$content .= "<br><table  style='margin:2px;border:1px solid black;background:#EAEAEA'>";
 								$content .= "<tr><td><b>".$this->functions->getLang("Subject").":</b></td><td>".$this->decode_string($obj->subject)."</td></tr>";
@@ -467,8 +497,8 @@
 								$content .= "<tr><td><b>".$this->functions->getLang("Date").":</b></td><td>".$obj->date."</td></tr>";
 								$content .= "<tr><td><b>".$this->functions->getLang("TO").":</b></td><td>".$this->decode_string($obj->to[0]->mailbox."@".$obj->to[0]->host)."</td></tr>";
-								$content .= !$obj->cc ? "</table><br>" :"<tr><td><b>".$this->functions->getLang("CC").":</b></td><td>".$this->decode_string($obj->cc[0]->mailbox."@".$obj->cc[0]->host)."</td></tr></table><br>";
+								$content .= !$obj->cc ? "</table><br>" :"<tr><td><b>".$this->functions->getLang("CC").":</b></td><td>".$this->decode_string($obj->cc[0]->mailbox."@".$obj->cc[0]->host)."</td></tr></table><br>";								
 								$ix_part = 	strtolower($attachment['type']) == "delivery-status" ? 1 : 0;
-								$content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, ($attachment['part_in_msg']+$ix_part).".1", FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));
-								break;
+								$content .= nl2br($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, ($attachment['part_in_msg']+$ix_part).".1", FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]));								
+								break;			
 							}
 						}
@@ -480,9 +510,9 @@
 					$content .= nl2br(imap_base64(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID)));
 				else if(!strtolower($msg->structure[$msg_number]->subtype) == "mixed")
-					$content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));
-			}
-		}
+					$content .= nl2br(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID));				
+			}
+		} 
 		// Force message with flag Seen (imap_fetchbody not works correctly)
-		$params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");
+		$params = array('folder' => $msg_folder, "msgs_to_set" => $msg_number, "flag" => "seen");				
 		$this->set_messages_flag($params);
 		$content = $this->process_embedded_images($msg,$msg_number,$content, $msg_folder);
@@ -491,9 +521,9 @@
 		return $return;
 	}
-
+	
 	function htmlfilter($body)
 	{
 		require_once('htmlfilter.inc');
-
+		
 		$tag_list = Array(
 				false,
@@ -568,6 +598,6 @@
                         		  '\\1round:\\2\\1'
                           		)
-		                    ),
-
+		                    ),     
+          
 		          '/^style/i' =>
     		              Array(
@@ -595,6 +625,6 @@
 				'/^a$/i' => Array('target' => '"_new"')
 		);
-
-
+    	
+    	
 		$trusted_body = sanitize($body,
 				$tag_list,
@@ -606,8 +636,8 @@
 				$add_attr_to_tag
 		);
-
+    	
 	    return $trusted_body;
 	}
-
+	
 	function decodeBody($body, $encoding, $charset=null)
 	{
@@ -620,5 +650,5 @@
 		if ($encoding == 'quoted-printable')
 	    {
-
+			
 			for($i=0;$i<256;$i++) {
 				$c1=dechex($i);
@@ -627,19 +657,19 @@
 				$myqprinta[]=$c1;
 				$myqprintb[]=chr($i);
-			}
+			}	    	
 			$body = str_replace($myqprinta,$myqprintb,($body));
 			$body = quoted_printable_decode($body);
-        	while (ereg("=\n", $body))
+        	while (ereg("=\n", $body)) 
         	{
            		$body = ereg_replace ("=\n", '', $body);
         	}
     	}
-    	else if ($encoding == 'base64')
+    	else if ($encoding == 'base64') 
     	{
         	$body = base64_decode($body);
     	}
-    	/*else if ($encoding == '7bit')
+    	/*else if ($encoding == '7bit') 
     	{
-        	$body = quoted_printable_decode($body);
+        	$body = quoted_printable_decode($body);        	        	        	
     	}*/
 		// All other encodings are returned raw.
@@ -649,5 +679,5 @@
 			return $body;
 	}
-
+	
 	function process_embedded_images($msg, $msgno, $body, $msg_folder)
 	{
@@ -666,12 +696,12 @@
 			}
 		}
-
+		
 		return $body;
 	}
-
+	
 	function replace_special_characters($body)
 	{
 		// Suspected TAGS!
-		/*$tag_list = Array(
+		/*$tag_list = Array(   
 			'blink','object','meta',
 			'html','link','frame',
@@ -682,6 +712,6 @@
 		*/
 
-		// Layout problem: Change html elements
-		// with absolute position to relate position, CASE INSENSITIVE.
+		// Layout problem: Change html elements 
+		// with absolute position to relate position, CASE INSENSITIVE. 
 		$body = @eregi_replace("POSITION: ABSOLUTE;","",$body);
 
@@ -691,5 +721,5 @@
 
 		$body = $this-> replace_links($body);
-		$blocked_tags = array();
+		$blocked_tags = array();		
 		foreach($tag_list as $index => $tag) {
 			$new_body = eregi_replace("<$tag", "<!--$tag", $body);
@@ -703,31 +733,28 @@
 	}
 
-	function replace_links($body) {
-		// Search for links,then open the link in new window.
-		//$body = @ereg_replace('[a-zA-Z]+://(([.]?[a-zA-Z0-9_/-])*)', '<a href="\\0" title="'.$this->functions->getLang("Open in New Window").'">\\0</a>',$body);
-  		//Search for emails, then open a new message tab.
-  		//$body = @ereg_replace('[a-zA-Z0-9!#$%&\'*+/=?^_`{|}~]+@([.]?[a-zA-Z0-9_/-])*', '<a title=\''.$this->functions->getLang("New Message").' -> \\0\'" onclick="Element(\'msg_number\').value=\'\\0\';new_message(\'new\',\'null\')" href="#">\\0</a>',$body);
-  		//$matches = array();
+	function replace_links($body) {					
+  		$matches = array();
 		// Verify exception.
-		//@preg_match("/<a href=\"notes:\/\/\//",$body,$matches);
+		@preg_match("/<a href=\"notes:\/\/\//",$body,$matches);
 		// It no has exception,then open the link in new window.
-		/*if(!count($matches)){
-			$body = @eregi_replace("<a (.*) href=", "<a \\1 target='_blank' href=", $body);
-			$body = @str_replace("<a href=", "<a target='_blank' href=", $body);
-			$body = @eregi_replace("target=\"\"", "target='_blank'", $body);
-			$body = @eregi_replace("target=''", "target='_blank'", $body);
-		}*/
-		$body = preg_replace('/(?<=[\s|(<br>)|\n|\r|;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\/\w.\-~&=?%;@+]*))/i', '<a href="http$3://$4$5" target="_blank">http$3://$4$5</a>', $body);
-   		return $body;
+		if(count($matches))
+			return $body;
+	
+		$pattern = '/(?<=[\s|(<br>)|\n|\r|;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[:\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\:\/\w.\-~&=?%;@+]*))/i';
+		$replacement = '<a href="http$3://$4$5" target="_blank">$1</a>';
+		return preg_replace($pattern, $replacement, $body); 
+		
+		// Original
+		//return preg_replace('/(?<=[\s|(<br>)|\n|\r|;])((http(s?):\/\/((?:[\w]\.?)+(?::[\d]+)?[\/.\-~&=?%;@#,+\w]*))|((?:www?\.)(?:\w\.?)*(?::\d+)?[\/\w.\-~&=?%;@+]*))/i', '<a href="http$3://$4$5" target="_blank">http$3://$4$5</a>', $body);
 	}
 
 	function get_signature($msg, $msg_number, $msg_folder)
-	{
+	{ 
 		foreach ($msg->file_type[$msg_number] as $index => $file_type)
 		{
 			$file_type = strtolower($file_type);
-			if(strtolower($msg->encoding[$msg_number][$index]) == 'base64')
-			{
-				if ($file_type == 'application/x-pkcs7-signature')
+			if(strtolower($msg->encoding[$msg_number][$index]) == 'base64') 
+			{
+				if ($file_type == 'application/x-pkcs7-signature') 
 				{
 					$export_mail = new ExportEml();
@@ -735,5 +762,5 @@
 					$params['msgs_to_export'] = $msg_number;
 				    $tempDir = ini_get("session.save_path");
-					$cert_file = $tempDir."/certificate_".base_convert(microtime(), 10, 36).".crt";
+					$cert_file = $tempDir."/certificate_".base_convert(microtime(), 10, 36).".crt";					
 					$result = openssl_pkcs7_verify($export_mail->export_msg($params),PKCS7_NOVERIFY,$cert_file);
 					if (file_exists($cert_file))
@@ -755,5 +782,5 @@
 			}
 		}
-   		return $sign;
+   		return $sign;	
 	}
 
@@ -776,12 +803,12 @@
     	return $thumbs_array;
 	}
-
+		
 	/*function delete_msg($params)
 	{
 		$folder = $params['folder'];
 		$msgs_to_delete = explode(",",$params['msgs_to_delete']);
-
+		
 		$mbox_stream = $this->open_mbox($folder);
-
+		
 		foreach ($msgs_to_delete as $msg_number){
 			imap_delete($mbox_stream, $msg_number, FT_UID);
@@ -794,18 +821,21 @@
 	function delete_msgs($params)
 	{
-
+		
 		$folder = $params['folder'];
 		$folder =  mb_convert_encoding($folder, "UTF7-IMAP","ISO-8859-1");
 		$msgs_number = explode(",",$params['msgs_number']);
 		$border_ID = $params['border_ID'];
-
+		
 		$return = array();
-
-		if ($params['get_previous_msg'])
+		
+		if ($params['get_previous_msg']){
 			$return['previous_msg'] = $this->get_info_previous_msg($params);
+			// Fix problem in unserialize function JS.
+			$return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
+		}
 
 		//$mbox_stream = $this->open_mbox($folder);
 	 	$mbox_stream = @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$folder, $this->username, $this->password) or die(serialize(array('imap_error' => imap_last_error())));
-
+		
 		foreach ($msgs_number as $msg_number)
 		{
@@ -813,8 +843,8 @@
 				$return['msgs_number'][] = $msg_number;
 		}
-
+		
 		$return['folder'] = $folder;
 		$return['border_ID'] = $border_ID;
-
+		
 		if($mbox_stream)
 			imap_close($mbox_stream, CL_EXPUNGE);
@@ -822,14 +852,14 @@
 	}
 
-
+		
 	function refresh($params)
 	{
 		include("class.imap_attachment.inc.php");
-		$imap_attachment = new imap_attachment();
+		$imap_attachment = new imap_attachment();		
 		$folder = $params['folder'];
 		$msg_range_begin = $params['msg_range_begin'];
 		$msg_range_end = $params['msg_range_end'];
 		$msgs_existent = $params['msgs_existent'];
-		$sort_box_type = $params['sort_box_type'];
+		$sort_box_type = $params['sort_box_type'];		
 		$sort_box_reverse = $params['sort_box_reverse'];
 		$msgs_in_the_server = array();
@@ -839,9 +869,9 @@
 		if(!count($sort_array_msg))
 			return array();
-
+			
 		$num_msgs = (count($sort_array_msg) - imap_num_recent($this->mbox));
 		$msgs_in_the_client = explode(",", $msgs_existent);
 
-
+		
 		for ($msg_range_begin; (($msg_range_begin <= $msg_range_end) && ($msg_range_begin <= count($sort_array_msg))); $msg_range_begin++)
 		{
@@ -858,8 +888,8 @@
 			}
 		}
-
+		
 		$msg_to_insert  = array_diff($msgs_in_the_server, $msgs_in_the_client);
 		$msg_to_delete = array_diff($msgs_in_the_client, $msgs_in_the_server);
-
+		
 		$msgs_to_exec = array();
 		if ((count($msg_to_insert)) && ($msgs_existent))
@@ -887,5 +917,5 @@
 			}
 		}
-
+		
 		$return = array();
 		$i = 0;
@@ -895,8 +925,8 @@
 			if (!is_object($header))
 				return false;
-
+			
 			$return[$i]['msg_number']	= $msg_number;
 			$return[$i]['command']		= $command;
-
+			
 			$return[$i]['msg_folder']	= $folder;
 			$return[$i]['Recent']		= $header->Recent;
@@ -912,5 +942,5 @@
 			else
 				$return[$i]['udate'] = $date_msg;
-
+			
 			$from = $header->from;
 			$return[$i]['from'] = array();
@@ -918,8 +948,8 @@
 			$return[$i]['from']['name'] = $tmp[0]->text;
 			$return[$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
-			//$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>';
+			//$return[$i]['from']['full'] ='"' . $return[$i]['from']['name'] . '" ' . '<' . $return[$i]['from']['email'] . '>'; 
 			if(!$return[$i]['from']['name'])
 				$return[$i]['from']['name'] = $return[$i]['from']['email'];
-
+			
 			/*$toaddress = imap_mime_header_decode($header->toaddress);
 			$return[$i]['toaddress'] = '';
@@ -932,10 +962,10 @@
 			$return[$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
 			$return[$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
-
+			
 			$return[$i]['subject'] = $this->decode_string($header->fetchsubject);
 
 			$return[$i]['Size'] = $header->Size;
 			$return[$i]['reply_toaddress'] = $header->reply_toaddress;
-
+			
 			$return[$i]['attachment'] = array();
 			$return[$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($this->mbox, $msg_number);
@@ -949,26 +979,26 @@
 	}
 
-	function get_folders_list()
-	{
-		$mbox_stream = $this->open_mbox();
+	function get_folders_list($params = null)
+	{
+		$mbox_stream = $this->open_mbox();		
 		$serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
 		$folders_list = imap_getmailboxes($mbox_stream, $serverString, "*");
 		$tmp = array();
 		$result = array();
-
+		
 		if (is_array($folders_list)) {
   			reset($folders_list);
 		$this->ldap = new ldap_functions();
-
+			
 			$i = 0;
   			while (list($key, $val) = each($folders_list)) {
   				$status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
   				$result[$i]['folder_unseen'] = $status->unseen;
-
+			
   				//$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
   				$tmp_folder_id = explode("}", mb_convert_encoding($val->name, "ISO_8859-1", "UTF7-IMAP" ));
   				$folder_id = $tmp_folder_id[1];
 				$result[$i]['folder_id'] = $folder_id;
-
+				
 				$tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
 				$result[$i]['folder_name'] = array_pop($tmp_folder_parent);
@@ -979,8 +1009,8 @@
 					}
 				}
-
+				
 				$tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
 				$result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
-
+					
 				if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
 					$result[$i]['folder_hasChildren'] = 1;
@@ -988,27 +1018,26 @@
 					$result[$i]['folder_hasChildren'] = 0;
 
-				$i++;
+				$i++;				
   			}
 		}
-
+		
 		foreach ($result as $folder_info)
 		{
 			$array_tmp[] = $folder_info['folder_id'];
 		}
-
+		
 		natcasesort($array_tmp);
-
+		
 		foreach ($array_tmp as $key => $folder_id)
 		{
 			$result2[] = $result[$key];
 		}
-
-		if($mbox_stream && is_resource($mbox_stream)){
-			imap_close($mbox_stream);
-		}
-
-		return array_merge($result2);
-	}
-
+		
+		$current_folder = "INBOX";
+		if($params && $params['folder'])
+			$current_folder = $params['folder'];
+		return array_merge($result2, $this->get_quota(array(folder_id => $current_folder)));
+	}
+	
 	function create_mailbox($arr)
 	{
@@ -1017,18 +1046,18 @@
 		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
 		$namebox =  mb_convert_encoding($namebox, "UTF7-IMAP", "UTF-8");
-
+		
 		$result = "Ok";
 		if(!imap_createmailbox($mbox_stream,"{".$imap_server."}$namebox"))
 		{
 			$result = implode("<br />\n", imap_errors());
-		}
-
+		}	
+		
 		if($mbox_stream)
 			imap_close($mbox_stream);
-
+					
 		return $result;
-
-	}
-
+		
+	}
+	
 	function create_extra_mailbox($arr)
 	{
@@ -1037,10 +1066,10 @@
 		$mbox_stream = $this->open_mbox();
 		$imap_server = $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
-		foreach($nameboxs as $key=>$tmp){
+		foreach($nameboxs as $key=>$tmp){			
 			if($tmp != ""){
 				if(!imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}$tmp"))){
 					$result = implode("<br />\n", imap_errors());
 					if($mbox_stream)
-						imap_close($mbox_stream);
+						imap_close($mbox_stream);					
 					return $result;
 				}
@@ -1051,5 +1080,5 @@
 		return true;
 	}
-
+	
 	function delete_mailbox($arr)
 	{
@@ -1058,5 +1087,5 @@
 		$mbox_stream = $this->open_mbox();
 		//$del_folder = imap_deletemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox");
-
+		
 		$result = "Ok";
 		$namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
@@ -1069,5 +1098,5 @@
 		return $result;
 	}
-
+	
 	function ren_mailbox($arr)
 	{
@@ -1077,19 +1106,19 @@
 		$mbox_stream = $this->open_mbox();
 		//$ren_folder = imap_renamemailbox($mbox_stream,"{".$imap_server."}INBOX.$namebox","{".$imap_server."}INBOX.$new_box");
-
+		
 		$result = "Ok";
 		$namebox = mb_convert_encoding($namebox, "UTF7-IMAP","UTF-8");
 		$new_box = mb_convert_encoding($new_box, "UTF7-IMAP","UTF-8");
-
+		
 		if(!imap_renamemailbox($mbox_stream,"{".$imap_server."}$namebox","{".$imap_server."}$new_box"))
 		{
-			$result = imap_errors();
+			$result = imap_errors();			
 		}
 		if($mbox_stream)
 			imap_close($mbox_stream);
 		return $result;
-
-	}
-
+		
+	}
+	
 	function get_num_msgs($params)
 	{
@@ -1099,12 +1128,12 @@
 			if(!$this->mbox || !is_resource($this->mbox))
 			return imap_last_error();
-		}
+		}		
 		$num_msgs = imap_num_msg($this->mbox);
 		if($this->mbox && is_resource($this->mbox))
 			imap_close($this->mbox);
-
+		
 		return $num_msgs;
 	}
-
+	
 	function send_mail($params)
 	{
@@ -1114,4 +1143,19 @@
 		$db = new db_functions();
 		$fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
+		##
+		# @AUTHOR Rodrigo Souza dos Santos
+		# @DATE 2008/09/17
+		# @BRIEF Checks if the user has permission to send an email with the email address used.
+		##
+		if ( is_array($fromaddress) && ($fromaddress[1] != $_SESSION['phpgw_info']['expressomail']['user']['email']) )
+		{
+			$deny = true;
+			foreach( $_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes'] as $key => $val )
+				if ( array_key_exists('mail', $val) && $val['mail'][0] == $fromaddress[1] )
+					$deny = false and end($_SESSION['phpgw_info']['expressomail']['user']['shared_mailboxes']);
+
+			if ( $deny )
+				return "The server denied your request to send a mail, you cannot use this mail address.";
+		}
 		$toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
 		$ccaddress = implode(',',$db->getAddrs(explode(',',$params['input_cc'])));
@@ -1124,19 +1168,19 @@
 		$attachments = $params['FILES'];
 		$forwarding_attachments = $params['forwarding_attachments'];
-
+		 
 		$folder =$params['folder'];
-		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
-		$folder_name = $params['folder_name'];
+		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");		
+		$folder_name = $params['folder_name'];		
 		// Fix problem with cyrus delimiter changes.
-		// Dots in names: enabled/disabled.
+		// Dots in names: enabled/disabled.				
 		$folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
 		$folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
 		// End Fix.
-		if ($folder != 'null'){
+		if ($folder != 'null'){			
 			$mail->SaveMessageInFolder = $folder;
 		}
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 		$mail->SMTPDebug = false;
-
+				
 		$mail->IsSMTP();
 		$mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
@@ -1150,5 +1194,5 @@
 			$mail->From = $fromaddress[1];
 		}
-
+				
 		$this->add_recipients("to", $toaddress, &$mail);
 		$this->add_recipients("cc", $ccaddress, &$mail);
@@ -1160,20 +1204,20 @@
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 		//	Build CID for embedded Images!!!
-		$pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&amp;msg_num=(.+)?&amp;msg_part=(.+)?)"/isU';
+		$pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
 		$cid_imgs = '';
 		$name_cid_files = array();
 		preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
 		$cid_array = array();
-		foreach($cid_imgs[4] as $j => $val){
-				if ( !array_key_exists($cid_imgs[3][$j].$val, $cid_array) )
+		foreach($cid_imgs[6] as $j => $val){
+				if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
       			{
-                $cid_array[$cid_imgs[3][$j].$val] = base_convert(microtime(), 10, 36);
+                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
 		        }
-		        $cid = $cid_array[$cid_imgs[3][$j].$val];
+		        $cid = $cid_array[$cid_imgs[4][$j].$val]; 
         		$mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
-
-				if ($msg_uid != $cid_imgs[3][$j]) // The image isn't in the same mail?
+        		
+				if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
 				{
-					$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[3][$j], $cid_imgs[4][$j], 'base64');
+					$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
 					$fileName = "image_".($j).".jpg";
 					$fileCode = "base64";
@@ -1182,8 +1226,8 @@
 				else
 				{
-					$attach_img = $forwarding_attachments[$cid_imgs[4][$j]-2];
+					$attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
 					$file_description = unserialize(rawurldecode($attach_img));
 
-					foreach($file_description as $i => $descriptor){
+					foreach($file_description as $i => $descriptor){				
 						$file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
 					}
@@ -1192,8 +1236,8 @@
 					$fileCode = $file_description[4];
 					$fileType = $this->get_file_type($file_description[2]);
-					unset($forwarding_attachments[$cid_imgs[4][$j]-2]);
+					unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
 				}
 				$tempDir = ini_get("session.save_path");
-				$file = "cid_image_".base_convert(microtime(), 10, 36).".dat";
+				$file = "cid_image_".base_convert(microtime(), 10, 36).".dat";					
 				$f = fopen($tempDir.'/'.$file,"w");
 				fputs($f,$fileContent);
@@ -1202,5 +1246,5 @@
 					$mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
 				//else
-				//	return "Error loading image attachment content";
+				//	return "Error loading image attachment content";						
 
 		}
@@ -1217,6 +1261,6 @@
 			}
 			if( $total_uploaded_size > $upload_max_filesize)
-				return 'false';
-		}
+				return 'false';			
+		}			
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 		//	Build Forwarding Attachments!!!
@@ -1227,14 +1271,14 @@
 				$name_cid_files[count($name_cid_files)] = $name_cid_files[0];
 				$name_cid_files[0] = null;
-			}
-
+			}			
+			
 			foreach($forwarding_attachments as $forwarding_attachment)
 			{
 					$file_description = unserialize(rawurldecode($forwarding_attachment));
 					$tmp = array_values($file_description);
-					foreach($file_description as $i => $descriptor){
+					foreach($file_description as $i => $descriptor){				
 						$tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
 					}
-					$file_description = $tmp;
+					$file_description = $tmp;					
 					$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
 					$fileName = $file_description[2];
@@ -1257,5 +1301,5 @@
 		else
 		{
-			if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
+			if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True") 
 			{
 				$userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
@@ -1263,5 +1307,5 @@
 				$now = date("d/m/y H:i:s");
 				$addrs = $toaddress.$ccaddress.$ccoaddress;
-				$sent = trim($sent);
+				$sent = trim($sent);									   			
    				error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
 			}
@@ -1277,11 +1321,11 @@
 	function add_recipients($recipient_type, $full_address, $mail)
 	{
-		$parse_address = imap_rfc822_parse_adrlist($full_address, "");
-		foreach ($parse_address as $val)
+		$parse_address = imap_rfc822_parse_adrlist($full_address, "");		
+		foreach ($parse_address as $val) 
 		{
 			//echo "<script language=\"javascript\">javascript:alert('".$val->mailbox."@".$val->host."');</script>";
 			if ($val->mailbox == "INVALID_ADDRESS")
 				continue;
-
+			
 			if (empty($val->personal))
 			{
@@ -1317,33 +1361,38 @@
 		return true;
 	}
-
+	
 	function get_forwarding_attachment($msg_folder, $msg_number, $msg_part, $encoding)
 	{
-		$mbox_stream = $this->open_mbox($msg_folder);
-		$fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);
+		$mbox_stream = $this->open_mbox($msg_folder);			
+		$fileContent = imap_fetchbody($mbox_stream, $msg_number, $msg_part, FT_UID);		
 		if($encoding == 'base64')
-			$fileContent = imap_base64($fileContent);
+			# The function imap_base64 adds a new line
+			# at ASCII text, with CRLF line terminators.
+			# So is being exchanged for base64_decode.
+			#
+			#$fileContent = imap_base64($fileContent);
+			$fileContent = base64_decode($fileContent);
 		else if($encoding == 'quoted-printable')
-			$fileContent = quoted_printable_decode($fileContent);
+			$fileContent = quoted_printable_decode($fileContent);				
 		return $fileContent;
 	}
-
+	
 	function del_last_caracter($string)
 	{
 		$string = substr($string,0,(strlen($string) - 1));
-		return $string;
-	}
-
+		return $string;	
+	}
+	
 	function del_last_two_caracters($string)
 	{
 		$string = substr($string,0,(strlen($string) - 2));
-		return $string;
-	}
-
+		return $string;	
+	}
+	
 	function imap_sortfrom($sort_box_reverse, $search_box_type)
 	{
 		$sortfrom = array();
 		$sortfrom_uid = array();
-
+		
 		$num_msgs = imap_num_msg($this->mbox);
 		for ($i=1; $i<=$num_msgs; $i++)
@@ -1358,20 +1407,20 @@
 				continue;
 			}
-			// List ANSWERED messages.
+			// List ANSWERED messages.			
 			elseif($search_box_type == "ANSWERED" && !trim($header->Answered)){
-				continue;
-			}
-			// List FLAGGED messages.
+				continue;				
+			}
+			// List FLAGGED messages.			
 			elseif($search_box_type == "FLAGGED" && !trim($header->Flagged)){
 				continue;
 			}
-
-			if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])
+						
+			if (($header->from[0]->mailbox . "@" . $header->from[0]->host) == $_SESSION['phpgw_info']['expressomail']['user']['email'])				
 				$from = $header->to;
 			else
 				$from = $header->from;
-
-			$tmp = imap_mime_header_decode($from[0]->personal);
-
+			
+			$tmp = imap_mime_header_decode($from[0]->personal);			
+			
 			if ($tmp[0]->text != "")
 				$sortfrom[$i] = $tmp[0]->text;
@@ -1379,24 +1428,24 @@
 				$sortfrom[$i] = $from[0]->mailbox . "@" . $from[0]->host;
 		}
-
+		
 		natcasesort($sortfrom);
-
+		
 		foreach($sortfrom as $index => $header_msg)
-		{
+		{	
 			$sortfrom_uid[] = imap_uid($this->mbox, $index);
 		}
-
+		
 		if ($sort_box_reverse)
 			$sortfrom_uid = array_reverse($sortfrom_uid);
-
+		
 		return $sortfrom_uid;
 	}
 
-	function move_search_messages($params){
-		$params['selected_messages'] = urldecode($params['selected_messages']);
+	function move_search_messages($params){		
+		$params['selected_messages'] = urldecode($params['selected_messages']);	
 		$params['new_folder'] = urldecode($params['new_folder']);
 		$params['new_folder_name'] = urldecode($params['new_folder_name']);
 		$sel_msgs = explode(",", $params['selected_messages']);
-		@reset($sel_msgs);
+		@reset($sel_msgs);	
 		$sorted_msgs = array();
 		foreach($sel_msgs as $idx => $sel_msg) {
@@ -1404,5 +1453,5 @@
 			 if(array_key_exists($sel_msg[0], $sorted_msgs)){
 			 	$sorted_msgs[$sel_msg[0]] .= ",".$sel_msg[1];
-			 }
+			 }	
 			 else {
 				$sorted_msgs[$sel_msg[0]] = $sel_msg[1];
@@ -1410,10 +1459,10 @@
 		}
 		@ksort($sorted_msgs);
-		$last_return = false;
-		foreach($sorted_msgs as $folder => $msgs_number) {
+		$last_return = false;		
+		foreach($sorted_msgs as $folder => $msgs_number) {			
 			$params['msgs_number'] = $msgs_number;
-			$params['folder'] = $folder;
+			$params['folder'] = $folder;	
 			if($params['new_folder'] && $folder != $params['new_folder']){
-				$last_return = $this -> move_messages($params);
+				$last_return = $this -> move_messages($params);				
 			}
 			elseif(!$params['new_folder'] || $params['delete'] ){
@@ -1424,9 +1473,9 @@
 		return $last_return;
 	}
-
+	
 	function move_messages($params)
 	{
-		$folder = $params['folder'];
-		$mbox_stream = $this->open_mbox($folder);
+		$folder = $params['folder'];		
+		$mbox_stream = $this->open_mbox($folder);		
 		$newmailbox = ($params['new_folder']);
 		$newmailbox = mb_convert_encoding($newmailbox, "UTF7-IMAP","ISO_8859-1");
@@ -1438,5 +1487,5 @@
 						'border_ID' => $params['border_ID'],
 						'status' => true); //Status foi adicionado para validar as permissoes ACL
-
+		
 		//Este bloco tem a finalidade de averiguar as permissoes para pastas compartilhadas
         if (substr($folder,0,4) == 'user'){
@@ -1467,10 +1516,14 @@
 					$return['new_folder_name'] = $cn;
         }
-
-		// Caso estejamos no box principal, nï¿œo ï¿œ necessï¿œrio pegar a informaï¿œï¿œo da mensagem anterior.
+				
+		// Caso estejamos no box principal, nao eh necessario pegar a informacao da mensagem anterior. 		
 		if (($params['get_previous_msg']) && ($params['border_ID'] != 'null') && ($params['border_ID'] != ''))
+		{
 			$return['previous_msg'] = $this->get_info_previous_msg($params);
-
-		$mbox_stream = $this->open_mbox($folder);
+			// Fix problem in unserialize function JS.
+			$return['previous_msg']['body'] = str_replace(array('{','}'), array('&#123;','&#125;'), $return['previous_msg']['body']);
+		}
+		
+		$mbox_stream = $this->open_mbox($folder);	
 		if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
 			imap_expunge($mbox_stream);
@@ -1479,19 +1532,19 @@
 			return $return;
 		}else {
-			if(strstr(imap_last_error(),'Over quota')) {
+			if(strstr(imap_last_error(),'Over quota')) {				
 				$accountID	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminUsername'];
-				$pass		= $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];
-				$userID 	= $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+				$pass		= $_SESSION['phpgw_info']['expressomail']['email_server']['imapAdminPW'];									
+				$userID 	= $_SESSION['phpgw_info']['expressomail']['user']['userid'];								
 				$server 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapServer'];
 				$mbox		= @imap_open("{".$this->imap_server.":".$this->imap_port.$this->imap_options."}INBOX", $accountID, $pass) or die(serialize(array('imap_error' => imap_last_error())));
 				if(!$mbox)
 					return imap_last_error();
-				$quota 	= imap_get_quotaroot($mbox_stream, "INBOX");
+				$quota 	= imap_get_quotaroot($mbox_stream, "INBOX");				
 				if(! imap_set_quota($mbox, "user".$this->imap_delimiter.$userID, 2.1 * $quota['usage'])) {
 					if($mbox_stream)
 						imap_close($mbox_stream);
-					if($mbox)
+					if($mbox)									
 						imap_close($mbox);
-					return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";
+					return "move_messages(): Error setting quota for MOVE or DELETE!! ". "user".$this->imap_delimiter.$userID." line ".__LINE__."\n";								
 				}
 				if(imap_mail_move($mbox_stream, $msgs_number, $newmailbox, CP_UID)) {
@@ -1503,7 +1556,7 @@
 						if($mbox)
 							imap_close($mbox);
-						return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
+						return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";								
 					}
-					return $return;
+					return $return;													
 				}
 				else {
@@ -1513,9 +1566,9 @@
 						if($mbox)
 							imap_close($mbox);
-						return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";
+						return "move_messages(): Error setting quota for MOVE or DELETE!! line ".__LINE__."\n";								
 					}
-					return imap_last_error();
-				}
-
+					return imap_last_error();				
+				}
+				
 			}
 			else {
@@ -1524,10 +1577,10 @@
 				return "move_messages() line ".__LINE__.": ". imap_last_error()." folder:".$newmailbox;
 			}
-		}
-	}
-
+		}		
+	}
+	
 	function save_msg($params)
 	{
-
+		
 		include_once("class.phpmailer.php");
 		$mail = new PHPMailer();
@@ -1544,16 +1597,16 @@
 		$attachments = $params['FILES'];
 		$return_files = $params['FILES'];
-
+		 
 		$folder = $params['folder'];
-		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");
+		$folder = mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1");		
 		// Fix problem with cyrus delimiter changes.
-		// Dots in names: enabled/disabled.
+		// Dots in names: enabled/disabled.				
 		$folder = @eregi_replace("INBOX/", "INBOX".$this->imap_delimiter, $folder);
 		$folder = @eregi_replace("INBOX.", "INBOX".$this->imap_delimiter, $folder);
 		// End Fix.
-
+					
 		$mail->SaveMessageInFolder = $folder;
 		$mail->SMTPDebug = false;
-
+						
 		$mail->IsSMTP();
 		$mail->Host = $_SESSION['phpgw_info']['expressomail']['email_server']['smtpServer'];
@@ -1561,10 +1614,10 @@
 		$mail->From = $_SESSION['phpgw_info']['expressomail']['user']['email'];
 		$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
-
+		
 		$mail->Sender = $mail->From;
 		$mail->SenderName = $mail->FromName;
 		$mail->FromName = $_SESSION['phpgw_info']['expressomail']['user']['fullname'];
 		$mail->From =  $_SESSION['phpgw_info']['expressomail']['user']['email'];
-
+				
 		$this->add_recipients("to", $toaddress, &$mail);
 		$this->add_recipients("cc", $ccaddress, &$mail);
@@ -1572,31 +1625,39 @@
 		$mail->IsHTML(true);
 		$mail->Body = $body;
-
+		
 		//	Build CID for embedded Images!!!
-		$pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&amp;msg_num=(.+)?&amp;msg_part=(.+)?)"/isU';
+		$pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU';
 		$cid_imgs = '';
 		$name_cid_files = array();
 		preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER);
 		$cid_array = array();
-		foreach($cid_imgs[4] as $j => $val){
-				if ( !array_key_exists($cid_imgs[3][$j].$val, $cid_array) )
+		foreach($cid_imgs[6] as $j => $val){
+				if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
       			{
-                $cid_array[$cid_imgs[3][$j].$val] = base_convert(microtime(), 10, 36);
+                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
 		        }
-		        $cid = $cid_array[$cid_imgs[3][$j].$val];
+		        $cid = $cid_array[$cid_imgs[4][$j].$val]; 
         		$mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
-
-				if ($msg_uid != $cid_imgs[3][$j]) // The image isn't in the same mail?
+        		
+				if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
 				{
-					$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[3][$j], $cid_imgs[4][$j], 'base64');
+					$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
+					//prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
 					$fileName = "image_".($j).".jpg";
 					$fileCode = "base64";
 					$fileType = "image/jpg";
+					$file_attached[0] = $cid_imgs[2][$j];
+					$file_attached[1] = $cid_imgs[4][$j];
+					$file_attached[2] = $fileName;
+					$file_attached[3] = $cid_imgs[6][$j];
+					$file_attached[4] = 'base64';
+					$file_attached[5] = strlen($fileContent); //Size of file
+					$return_forward[] = $file_attached;
 				}
 				else
 				{
-					$attach_img = $forwarding_attachments[$cid_imgs[4][$j]-2];
+					$attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
 					$file_description = unserialize(rawurldecode($attach_img));
-					foreach($file_description as $i => $descriptor){
+					foreach($file_description as $i => $descriptor){				
 						$file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
 					}
@@ -1605,5 +1666,5 @@
 					$fileCode = $file_description[4];
 					$fileType = $this->get_file_type($file_description[2]);
-					unset($forwarding_attachments[$cid_imgs[4][$j]-2]);
+					unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
 					if (!empty($file_description))
 					{
@@ -1613,5 +1674,5 @@
 				}
 				$tempDir = ini_get("session.save_path");
-				$file = "cid_image_".base_convert(microtime(), 10, 36).".dat";
+				$file = "cid_image_".base_convert(microtime(), 10, 36).".dat";					
 				$f = fopen($tempDir.'/'.$file,"w");
 				fputs($f,$fileContent);
@@ -1620,9 +1681,9 @@
 					$mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
 				//else
-				//	return "Error loading image attachment content";
-
-		}
-
-	//	Build Forwarding Attachments!!!
+				//	return "Error loading image attachment content";						
+
+		}
+	
+	//	Build Forwarding Attachments!!!		
 		if (count($forwarding_attachments) > 0)
 		{
@@ -1631,19 +1692,19 @@
 				$file_description = unserialize(rawurldecode($forwarding_attachment));
 				$tmp = array_values($file_description);
-				foreach($file_description as $i => $descriptor){
+				foreach($file_description as $i => $descriptor){				
 					$tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
 				}
 				$file_description = $tmp;
-
+				
 				$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
 				$fileName = $file_description[2];
-
+				
 				$file_description[5] = strlen($fileContent); //Size of file
 				$return_forward[] = $file_description;
-
+			
 					$mail->AddStringAttachment($fileContent, $fileName, $file_description[4], $this->get_file_type($file_description[2]));
 			}
 		}
-
+		
 		if ((count($return_forward) > 0) && (count($return_files) > 0))
 			$return_files = array_merge_recursive($return_forward,$return_files);
@@ -1651,12 +1712,12 @@
 			if (count($return_files) < 1)
 				$return_files = $return_forward;
-
+	
 		//	Build Uploading Attachments!!!
 		if (count($attachments))
 			foreach ($attachments as $attach)
-				$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name
-
-
-
+				$mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $this->get_file_type($attach['name']));  // optional name			
+	
+	
+		
 		if(!empty($mail->AltBody))
             $mail->ContentType = "multipart/alternative";
@@ -1666,5 +1727,5 @@
         $header = $mail->CreateHeader();
         $body = $mail->CreateBody();
-
+        
        	if ($_SESSION['phpgw_info']['expressomail']['email_server']['imapTLSEncryption'] == 'yes')
 		{
@@ -1680,16 +1741,16 @@
 		$imap_port 	= $_SESSION['phpgw_info']['expressomail']['email_server']['imapPort'];
 		$mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
-
+	
 		$new_header = str_replace("\n", "\r\n", $header);
 		$new_body = str_replace("\n", "\r\n", $body);
-
+		
 		$return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $new_header . $new_body, "\\Seen \\Draft");
 		$status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
 		$return['msg_no'] = $status->uidnext - 1;
 		$return['folder_id'] = $folder;
-
+		
 		if($mbox_stream)
 			imap_close($mbox_stream);
-
+				
 		foreach ($return_files as $index => $_attachment) {
 			if (array_key_exists("name",$_attachment)){
@@ -1703,13 +1764,13 @@
 			}
 		}
-
+		
 		$return['files'] = serialize($return_files);
-
+				
 		if (!$return['append'])
 			$return['append'] = imap_last_error();
-
+		
 		return $return;
 	}
-
+	
 	function set_messages_flag($params)
 	{
@@ -1720,8 +1781,8 @@
 		$return["msgs_to_set"] = $msgs_to_set;
 		$return["flag"] = $flag;
-
+		
 		if(!$this->mbox && !is_resource($this->mbox))
 			$this->mbox = $this->open_mbox($folder);
-
+		
 		if ($flag == "unseen")
 			$return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Seen", ST_UID);
@@ -1738,15 +1799,15 @@
 		elseif ($flag == "unflagged")
 			$return["status"] = imap_clearflag_full($this->mbox, $msgs_to_set, "\\Flagged", ST_UID);
-
+		
 		if($this->mbox && is_resource($this->mbox))
 			imap_close($this->mbox);
 		return $return;
 	}
-
+	
 	function get_file_type($file_name)
 	{
 		$file_name = strtolower($file_name);
 	   	$strFileType = strrev(substr(strrev($file_name),0,4));
-	   	if ($strFileType == ".asf")
+	   	if ($strFileType == ".asf") 
    			return "video/x-ms-asf";
 	   	if ($strFileType == ".avi")
@@ -1774,13 +1835,13 @@
 	   	if ($strFileType == ".htm" || $strFileType == "html")
    			return "text/html";
-	   	if ($strFileType == ".xml")
+	   	if ($strFileType == ".xml") 
    			return "text/xml";
-	   	if ($strFileType == ".xsl")
+	   	if ($strFileType == ".xsl") 
    			return "text/xsl";
-	   	if ($strFileType == ".css")
+	   	if ($strFileType == ".css") 
    			return "text/css";
-	   	if ($strFileType == ".php")
+	   	if ($strFileType == ".php") 
    			return "text/php";
-	   	if ($strFileType == ".asp")
+	   	if ($strFileType == ".asp") 
    			return "text/asp";
 	   	if ($strFileType == ".pdf")
@@ -1810,59 +1871,37 @@
 		if ($strFileType == ".stw")
 			return "application/vnd.sun.xml.writer.template";
-
-
-   		return "application/octet-stream";
-	}
-
+   		
+   		
+   		return "application/octet-stream";  		
+	}
+	
 	function htmlspecialchars_encode($str)
 	{
-		/*// replace  '  and  "  with htmlspecialchars */
-		$str = ereg_replace('&', '&amp;', $str);
-		// any ampersand & that ia already in a "&amp;" should NOT be encoded
-		//$str = preg_replace("/&(?![:alnum:]*;)/", "&amp;", $str);
-		$str = ereg_replace('"', '&quot;', $str);
-		$str = ereg_replace('\'', '&#039;', $str);
-
-		$str = ereg_replace('<', '&lt;', $str);
-		$str = ereg_replace('>', '&gt;', $str);
-		// these {  and  }  must be html encoded or else they conflict with the template system
-		$str = str_replace("{", '&#123;', $str);
-		$str = str_replace("}", '&#125;', $str);
-		return $str;
+		return  str_replace( array('&', '"','\'','<','>','{','}'), array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), $str);
 	}
 	function htmlspecialchars_decode($str)
 	{
-		/*// replace  '  and  "  with htmlspecialchars */
-		$str = ereg_replace('&amp;','&',  $str);
-		// any ampersand & that ia already in a "&amp;" should NOT be encoded
-		//$str = preg_replace("/&(?![:alnum:]*;)/", "&amp;", $str);
-		$str = ereg_replace('&quot;', '"', $str);
-		$str = ereg_replace('&#039;', '\'', $str);
-		$str = ereg_replace('&lt;','<', $str);
-		$str = ereg_replace('&gt;', '>', $str);
-		// these {  and  }  must be html encoded or else they conflict with the template system
-		$str = str_replace('&#123;', "{", $str);
-		$str = str_replace( '&#125;',"}", $str);
-		return $str;
-	}
-
+		return  str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&#123;','&#125;'), array('&', '"','\'','<','>','{','}'), $str);
+	}
+	
 	function get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse){
-
+		
 		if(!$this->mbox || !is_resource($this->mbox)){
 			$this->mbox = $this->open_mbox($folder);
+		
 		}
 
 		switch($sort_box_type){
 			case 'SORTFROM':
-				return $this->imap_sortfrom($sort_box_reverse, $search_box_type);
+				return $this->imap_sortfrom($sort_box_reverse, $search_box_type);				
 			case 'SORTSUBJECT':
-				return imap_sort($this->mbox, SORTSUBJECT, $sort_box_reverse, SE_UID, $search_box_type);
+				return imap_sort($this->mbox, SORTSUBJECT, $sort_box_reverse, SE_UID, $search_box_type);				
 			case 'SORTSIZE':
-				return imap_sort($this->mbox, SORTSIZE, $sort_box_reverse, SE_UID, $search_box_type);
+				return imap_sort($this->mbox, SORTSIZE, $sort_box_reverse, SE_UID, $search_box_type);				
 			default:
-				return imap_sort($this->mbox, SORTARRIVAL, $sort_box_reverse, SE_UID, $search_box_type);
-		}
-	}
-
+				return imap_sort($this->mbox, SORTARRIVAL, $sort_box_reverse, SE_UID, $search_box_type);						
+		}		
+	}	
+	
 	function get_info_next_msg($params)
 	{
@@ -1873,6 +1912,6 @@
 		$reuse_border = $params['reuse_border'];
 		$search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
-		$sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
-
+		$sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);				
+		
 		$success = false;
 		if (is_array($sort_array_msg))
@@ -1893,10 +1932,10 @@
 			return $params;
 		}
-
+		
 		$params = array();
 		$params['msg_number'] = $sort_array_msg[($i+1)];
 		$params['msg_folder'] = $folder;
-
-		$return = $this->get_info_msg($params);
+		
+		$return = $this->get_info_msg($params);		
 		$return["reuse_border"] = $reuse_border;
 		return $return;
@@ -1912,5 +1951,5 @@
 		$search_box_type = $params['search_box_type'] != "ALL" && $params['search_box_type'] != "" ? $params['search_box_type'] : false;
 		$sort_array_msg = $this -> get_msgs($folder, $sort_box_type, $search_box_type, $sort_box_reverse);
-
+		
 		$success = false;
 		if (is_array($sort_array_msg))
@@ -1930,30 +1969,38 @@
 			return $params;
 		}
-
+		
 		$params = array();
 		$params['msg_number'] = $sort_array_msg[($i-1)];
 		$params['msg_folder'] = $folder;
-
+		
 		$return = $this->get_info_msg($params);
 		$return["reuse_border"] = $reuse_border;
 		return $return;
 	}
-
+	
 	// This function updates the values: quota, paging and new messages menu.
 	function get_menu_values($params){
 		$return_array = array();
 		$return_array = $this->get_quota($params);
-
+		
 		$mbox_stream = $this->open_mbox($params['folder']);
-		$return_array['num_msgs'] = imap_num_msg($mbox_stream);
+		$return_array['num_msgs'] = imap_num_msg($mbox_stream);		
 		if($mbox_stream)
 			imap_close($mbox_stream);
-
-		return $return_array;
-	}
-
+				
+		return $return_array; 
+	}
+	
 	function get_quota($params){
-		$folder_id = $params['folder_id'];
-		if(!$this->mbox || !is_resource($this->mbox))
+		// folder_id = user/{uid} for shared folders
+		if(substr($params['folder_id'],0,5) != 'INBOX' && preg_match('/user\\'.$this->imap_delimiter.'/i', $params['folder_id'])){
+			$array_folder =  explode($this->imap_delimiter,$params['folder_id']);
+			$folder_id = "user".$this->imap_delimiter.$array_folder[1];		
+		}
+		// folder_id = INBOX for inbox folders
+		else
+			$folder_id = "INBOX";
+		
+		if(!$this->mbox)
 			$this->mbox = $this->open_mbox();
 
@@ -1961,5 +2008,5 @@
 		if($this->mbox && is_resource($this->mbox))
 			imap_close($this->mbox);
-
+			
 		if (!$quota){
 			return array(
@@ -1969,5 +2016,5 @@
 			);
 		}
-
+		
 		if(count($quota) && $quota['limit']) {
 			$quota_limit = (($quota['limit']/1024)* 100 + .5 )* .01;
@@ -1984,15 +2031,15 @@
 			);
 		}
-		else
+		else 
 			return array();
 	}
-
+	
 	function send_notification($params){
 		require_once("class.phpmailer.php");
 		$mail = new PHPMailer();
-
+		 
 		$toaddress = $params['notificationto'];
-
-		$subject = 'Leitura confirmada da mensagem: ' . $params['subject'];
+		
+		$subject = 'Confirmação de leitura: ' . $params['subject'];
 		$body = 'Sua mensagem: ' . $params['subject'] . '<br>';
 		$body .= 'foi lida por: ' . $_SESSION['phpgw_info']['expressomail']['user']['fullname'] . ' &lt;' . $_SESSION['phpgw_info']['expressomail']['user']['email'] . '&gt; em ' . date("d/m/Y H:i");
@@ -2008,5 +2055,5 @@
 		$mail->IsHTML(true);
 		$mail->Body = $body;
-
+		
 		if(!$mail->Send()){
    			return $mail->ErrorInfo;
@@ -2015,8 +2062,8 @@
    			return true;
 	}
-
+	
 	function empty_trash()
 	{
-		$folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
+		$folder = 'INBOX' . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']; 
 		$mbox_stream = $this->open_mbox($folder);
 		$return = imap_delete($mbox_stream,'1:*');
@@ -2025,13 +2072,13 @@
 		return $return;
 	}
-
+	
 	function search($params)
 	{
 		include("class.imap_attachment.inc.php");
-		$imap_attachment = new imap_attachment();
+		$imap_attachment = new imap_attachment();				
 		$criteria = $params['criteria'];
 		$return = array();
 		$folders = $this->get_folders_list();
-
+		
 		$j = 0;
 		foreach($folders as $folder)
@@ -2039,12 +2086,12 @@
 			$mbox_stream = $this->open_mbox($folder);
 			$messages = imap_search($mbox_stream, $criteria, SE_UID);
-
+			
 			if ($messages == '')
 				continue;
-
+		
 			$i = 0;
 			$return[$j] = array();
 			$return[$j]['folder_name'] = $folder['name'];
-
+			
 			foreach($messages as $msg_number)
 			{
@@ -2052,5 +2099,5 @@
 				if (!is_object($header))
 					return false;
-
+				
 				$return[$j][$i]['msg_folder']	= $folder['name'];
 				$return[$j][$i]['msg_number']	= $msg_number;
@@ -2061,5 +2108,5 @@
 				$return[$j][$i]['Draft']		= $header->Draft;
 				$return[$j][$i]['Flagged']		= $header->Flagged;
-
+	
 				$date_msg = date("d/m/Y",$header->udate);
 				if (date("d/m/Y") == $date_msg)
@@ -2067,10 +2114,10 @@
 				else
 					$return[$j][$i]['udate'] = $date_msg;
-
+			
 				$fromaddress = imap_mime_header_decode($header->fromaddress);
 				$return[$j][$i]['fromaddress'] = '';
 				foreach ($fromaddress as $tmp)
 					$return[$j][$i]['fromaddress'] .= $this->replace_maior_menor($tmp->text);
-
+			
 				$from = $header->from;
 				$return[$j][$i]['from'] = array();
@@ -2078,5 +2125,5 @@
 				$return[$j][$i]['from']['name'] = $tmp[0]->text;
 				$return[$j][$i]['from']['email'] = $from[0]->mailbox . "@" . $from[0]->host;
-				$return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>';
+				$return[$j][$i]['from']['full'] ='"' . $return[$j][$i]['from']['name'] . '" ' . '<' . $return[$j][$i]['from']['email'] . '>'; 
 
 				$to = $header->to;
@@ -2085,5 +2132,5 @@
 				$return[$j][$i]['to']['name'] = $tmp[0]->text;
 				$return[$j][$i]['to']['email'] = $to[0]->mailbox . "@" . $to[0]->host;
-				$return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>';
+				$return[$j][$i]['to']['full'] ='"' . $return[$i]['to']['name'] . '" ' . '<' . $return[$i]['to']['email'] . '>'; 
 
 				$subject = imap_mime_header_decode($header->fetchsubject);
@@ -2094,8 +2141,8 @@
 				$return[$j][$i]['Size'] = $header->Size;
 				$return[$j][$i]['reply_toaddress'] = $header->reply_toaddress;
-
+			
 				$return[$j][$i]['attachment'] = array();
 				$return[$j][$i]['attachment'] = $imap_attachment->get_attachment_headerinfo($mbox_stream, $msg_number);
-
+						
 				$i++;
 			}
@@ -2104,23 +2151,23 @@
 				imap_close($mbox_stream);
 		}
-
+	
 		return $return;
 	}
-
+	
 	function delete_and_show_previous_message($params)
 	{
 		$return = $this->get_info_previous_msg($params);
-
+		
 		$params_tmp1 = array();
 		$params_tmp1['msgs_to_delete'] = $params['msg_number'];
 		$params_tmp1['folder'] = $params['msg_folder'];
 		$return_tmp1 = $this->delete_msg($params_tmp1);
-
+		
 		$return['msg_number_deleted'] = $return_tmp1;
-
+		
 		return $return;
 	}
-
-
+		
+	
 	function automatic_trash_cleanness($params)
 	{
@@ -2140,6 +2187,6 @@
 // 	Fix the search problem with special characters!!!!
 	function remove_accents($string) {
-		return strtr($string,
-	 	"?ï¿œ??ï¿œ?ï¿œ?ï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œ?ï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œ?ï¿œï¿œ?ï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œ?ï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œï¿œ?ï¿œï¿œï¿œï¿œ",
+		return strtr($string, 
+	 	"?Ó??ó?Ý?úÁÀÃÂÄÇÉÈÊËÍÌ?ÎÏÑÕÔÓÒÖÚÙ?ÛÜ?áàãâäçéèêëíì?îïñóòõôöúù?ûüýÿ", 
 	 	"SOZsozYYuAAAAACEEEEIIIIINOOOOOUUUUUsaaaaaceeeeiiiiinooooouuuuuyy");
 	}
@@ -2165,6 +2212,6 @@
 						$filter .= '"'.$filter_array[1].'"';
 					}
-				}
-				$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);
 				$folder_name = explode($this->imap_delimiter,$name_box);
@@ -2177,29 +2224,29 @@
 				}
 				$folder_name = implode($this->imap_delimiter,$folder_name);
-
+				
 				if(!is_resource($mbox_stream))
 					$mbox_stream = $this->open_mbox($name_box);
 				else
 					imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
-
-				if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search
-
+			
+				if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search 	
+				
 					$all_criterias = array ("TO","SUBJECT","FROM","CC");
 					foreach($all_criterias as $criteria_fixed)
 					{
 						$_filter = $criteria_fixed . substr($filter,4);
-
+					
 						$search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
-
+						
 						if($search_criteria && count($search_criteria) < 50)
 						{
 							foreach($search_criteria as $new_search){
-								$m_token = trim("##".mb_convert_encoding( $folder_name, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--".$new_search."##"."\n");
+								$m_token = trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--".$new_search."##"."\n");
 								if(!@strstr($retorno,$m_token))
 									$retorno .= $m_token;
 							}
-						}
-						else if(count($search_criteria) >= 50)
-							return "many results";
+						}						
+						else if(count($search_criteria) >= 50)							
+							return "many results";						
 					}
 				}
@@ -2209,5 +2256,5 @@
 					{
 						foreach($search_criteria as $new_search)
-							$retorno .= trim("##".mb_convert_encoding( $folder_name, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
+							$retorno .= trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
 					}
 				}
@@ -2215,26 +2262,26 @@
 		}
 		if($mbox_stream)
-			imap_close($mbox_stream);
-
+			imap_close($mbox_stream);		
+						
 		return $retorno ? $retorno : "none";
 	}
-
+	
 	function get_msg($uid_msg,$name_box, $mbox_stream )
 	{
-		$header = @imap_headerinfo($mbox_stream, imap_msgno($mbox_stream, $uid_msg), 80, 255);
+		$header = @imap_headerinfo($mbox_stream, imap_msgno($mbox_stream, $uid_msg), 80, 255);         
 		$subject = $this->decode_string($header->fetchsubject);
 		$from = $header->from[0]->mailbox;
 		if($header->from[0]->personal != "")
 			$from = $header->from[0]->personal;
-		$ret_msg = $this->decode_string($from) . "--" . $subject . "--". date("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size). "--". $header->Unseen;
-		return $ret_msg;
-	}
-
+		$ret_msg = $this->decode_string($from) . "--" . $subject . "--". date("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size);
+		return $ret_msg;                    
+	}	
+	
 	function size_msg($size){
 		$var = floor($size/1024);
 		if($var >= 1){
-			return $var." kb";
+			return $var." kb";	
 		}else{
-			return $size ." b";
+			return $size ." b";	
 		}
 	}
@@ -2263,13 +2310,13 @@
 	   }
 	}
-
+	
 	function getacl()
 	{
 		$this->ldap = new ldap_functions();
-
+		
 		$return = array();
-		$mbox_stream = $this->open_mbox();
+		$mbox_stream = $this->open_mbox();	
 		$mbox_acl = imap_getacl($mbox_stream, 'INBOX');
-
+		
 		$i = 0;
 		foreach ($mbox_acl as $user => $acl)
@@ -2284,5 +2331,5 @@
 		return $return;
 	}
-
+	
 	function setacl($params)
 	{
@@ -2290,5 +2337,5 @@
 		if (!count($old_users))
 			$old_users = array();
-
+		
 		$tmp_array = array();
 		foreach ($old_users as $index => $user_info)
@@ -2297,9 +2344,9 @@
 		}
 		$old_users = $tmp_array;
-
+		
 		$users = unserialize($params['users']);
 		if (!count($users))
 			$users = array();
-
+		
 		//$add_share = array_diff($users, $old_users);
 		$remove_share = array_diff($old_users, $users);
@@ -2324,5 +2371,5 @@
 			}
 		}*/
-
+		
 		if (count($remove_share))
 		{
@@ -2337,19 +2384,19 @@
                 	}
         		}
-			}
-		}
-
+			}	
+		}
+		
 		return true;
 	}
-
+	
 	function getaclfromuser($params)
 	{
 		$useracl = $params['user'];
-
+		
 		$return = array();
 		$return[$useracl] = 'false';
-		$mbox_stream = $this->open_mbox();
+		$mbox_stream = $this->open_mbox();	
 		$mbox_acl = imap_getacl($mbox_stream, 'INBOX');
-
+		
 		foreach ($mbox_acl as $user => $acl)
 		{
@@ -2370,10 +2417,10 @@
 		//No caso de se tratar da caixa do proprio usuario logado, utiliza a sintaxe abaixo
 		if(substr($user,0,4) != 'user')
-		  $mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
+		$mbox_acl = imap_getacl($mbox_stream, 'user'.$this->imap_delimiter.$user);
 		else
 		  $mbox_acl = imap_getacl($mbox_stream, $user);
 		return $mbox_acl[$this->username];
 	}
-
+	
 
 	function setaclfromuser($params)
@@ -2381,5 +2428,5 @@
 		$user = $params['user'];
 		$acl = $params['acl'];
-
+		
 		$mbox_stream = $this->open_mbox();
 
@@ -2391,22 +2438,25 @@
 			foreach ($mailboxes_list as $key => $val)
 			{
-				$folder = str_replace($serverString, "", imap_utf7_decode($val->name));
+				$folder = str_replace($serverString, "", imap_utf7_encode($val->name));
+				$folder = str_replace("&-", "&", $folder);
 				if (!imap_setacl ($mbox_stream, $folder, $user, $acl))
 				{
-					return imap_last_error();
-				}
-			}
-		}
-
-		return true;
-	}
-
+					$return = imap_last_error();
+				}
+			}
+		}
+		if (isset($return))
+			return $return;
+		else
+			return true;
+	}
+	
 	function download_attachment($msg,$msgno)
 	{
-		$array_parts_attachments = array();
+		$array_parts_attachments = array();		
 		$array_parts_attachments['names'] = '';
 		include("class.imap_attachment.inc.php");
-		$imap_attachment = new imap_attachment();
-
+		$imap_attachment = new imap_attachment();		
+		
 		if (count($msg->fname[$msgno]) > 0)
 		{
@@ -2425,5 +2475,5 @@
 		$array_parts_attachments['names'] = substr($array_parts_attachments['names'],0,(strlen($array_parts_attachments['names']) - 2));
 		return $array_parts_attachments;
-	}
+	}	
 
 	function spam($params)
@@ -2439,24 +2489,26 @@
 			$msg = $header . $body;
 			$email = $_SESSION['phpgw_info']['expressomail']['user']['email'];
-			//$tmp_file = $tmp_dir . "msg." . $email . '.'. $msg_number . time();
-			// maybe we can get it faster with regex, don't know how :'(
-			$signature = trim(substr($header, strpos($header, 'X-DSPAM-Signature:') + 18));
+			$username = $this->username;
 			strtok($email, '@');
 			$domain = strtok('@');
 
+			//Encontrar a assinatura do dspam no cabecalho
+			$v = explode("\r\n", $header);
+			foreach ($v as $linha){
+				if (eregi("^X-DSPAM-Signature", $linha)) {
+					
+					$args = explode(" ",$linha);
+					$signature = $args[1];
+				}
+			}
+
 			// feed dspam
-			if ($is_spam)
- 				$cmd = str_replace(
- 							array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##'),
- 							array($email, $this->username, $domain, $signature), $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']
- 						);
- 			else
- 				$cmd = str_replace(
- 							array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##'),
-	          				array($email, $this->username, $domain, $signature), $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']
-	          			);
-
+			switch($is_spam){
+				case 'true':  $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_spam']; break;
+				case 'false': $cmd = $_SESSION['phpgw_info']['server']['expressomail']['expressoMail_command_for_ham']; break;
+			}
+			$tags = array('##EMAIL##', '##USERNAME##', '##DOMAIN##', '##SIGNATURE##');
+			$cmd = str_replace($tags,array($email,$username,$domain,$signature),$cmd);
  			system($cmd);
-
 		}
 		imap_close($mbox_stream);
