Index: branches/2.2/expressoMail1_2/inc/class.db_functions.inc.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/class.db_functions.inc.php	(revision 1992)
+++ branches/2.2/expressoMail1_2/inc/class.db_functions.inc.php	(revision 3018)
@@ -1,6 +1,17 @@
 <?php
-define('PHPGW_INCLUDE_ROOT','../');	
-define('PHPGW_API_INC','../phpgwapi/inc');	
-include_once(PHPGW_API_INC.'/class.db.inc.php');
+if(!isset($_SESSION['phpgw_info']['expressomail']['server']['db_name'])) { 
+	include_once('../header.inc.php'); 
+	$_SESSION['phpgw_info']['expressomail']['server']['db_name'] = $GLOBALS['phpgw_info']['server']['db_name'];  
+	$_SESSION['phpgw_info']['expressomail']['server']['db_host'] = $GLOBALS['phpgw_info']['server']['db_host']; 
+	$_SESSION['phpgw_info']['expressomail']['server']['db_port'] = $GLOBALS['phpgw_info']['server']['db_port']; 
+	$_SESSION['phpgw_info']['expressomail']['server']['db_user'] = $GLOBALS['phpgw_info']['server']['db_user']; 
+	$_SESSION['phpgw_info']['expressomail']['server']['db_pass'] = $GLOBALS['phpgw_info']['server']['db_pass']; 
+	$_SESSION['phpgw_info']['expressomail']['server']['db_type'] = $GLOBALS['phpgw_info']['server']['db_type']; 
+} 
+else{ 
+	define('PHPGW_INCLUDE_ROOT','../');      
+	define('PHPGW_API_INC','../phpgwapi/inc');       
+	include_once(PHPGW_API_INC.'/class.db.inc.php'); 
+} 
 include_once('class.dynamic_contacts.inc.php');
 	
@@ -214,4 +225,6 @@
 		if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] &&
 			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
+			// Free others requests 
+                        session_write_close(); 
 			$dynamic_contact = new dynamic_contacts();
 			$dynamic = $dynamic_contact->dynamic_contact_toString();
@@ -353,4 +366,6 @@
 				$calendar = $fileContent;
 		}
+		// It's necessary to access calendar method. 
+		include_once(PHPGW_INCLUDE_ROOT.'/header.inc.php'); 
 			
 		$uiicalendar = CreateObject("calendar.uiicalendar");
Index: branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 1969)
+++ branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 3018)
@@ -77,4 +77,6 @@
 	function get_range_msgs2($params)
 	{
+		// Free others requests 
+                session_write_close(); 
 		$folder = $params['folder'];
 		$msg_range_begin = $params['msg_range_begin'];
@@ -335,8 +337,14 @@
 			$head1 = explode(":",$head);
 			if ( (strtoupper($head1[0]) == "TO") ||
-					(strtoupper($head1[0]) == "FROM") ||
-					(strtoupper($head1[0]) == "SUBJECT") ||
-					(strtoupper($head1[0]) == "DATE") )
-				$header .= $head."\r\n";
+				(strtoupper($head1[0]) == "FROM") ||
+				(strtoupper($head1[0]) == "SUBJECT") ||
+				(strtoupper($head1[0]) == "DATE") || 
+				(strtoupper($head1[0]) == "CONTENT-TYPE")) { 
+
+					if(strtoupper($head1[0]) == "CONTENT-TYPE"){ 
+						$head = str_replace("multipart/mixed","text/html",$head);                        
+					} 
+					$header .= $head."\n"; 
+				} 
 		}
 
@@ -474,6 +482,6 @@
 		$body = $return_get_body['body'];
 		//Remoção de tags <span></span> para correção de erro no firefox
-		$body = mb_ereg_replace("<span><span>","",$body);
-		$body = mb_ereg_replace("</span></span>","",$body);
+		$body = mb_eregi_replace("<span><span>","",$body);
+		$body = mb_eregi_replace("</span></span>","",$body);
 
 		if($return_get_body['body']=='isCripted'){
@@ -492,9 +500,10 @@
 		}
 
-		$pattern = '/^[ \t]*Disposition-Notification-To(^:)*:(.+)*@(.+)*$/isUm';
+		$pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm';
 		if (preg_match($pattern, $header_, $fields))
 		{
-			preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches);
-			$return['DispositionNotificationTo'] = "<".$matches[0].">";
+			if(preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches)){ 
+				$return['DispositionNotificationTo'] = "<".$matches[0].">"; 
+			} 
 		}
 
@@ -789,25 +798,40 @@
 		if(!$msg->structure[$msg_number]->parts) //Simple message, only 1 piece
 		{
-            if(strtolower($msg->structure[$msg_number]->subtype) == 'x-pkcs7-mime'){
-                $return['body']='isCripted';
-                return $return;
-            }
+			if(strtolower($msg->structure[$msg_number]->subtype) == 'x-pkcs7-mime'){
+				$return['body']='isCripted';
+				return $return;
+			}
 
 			$attachment = array(); //No attachments
 
-            if(strtolower($msg->structure[$msg_number]->subtype) == 'x-pkcs7-mime'){
-					$return['body']='isCripted';
-					return $return;
-			}
-
-			$content = '';
-			if (strtolower($msg->structure[$msg_number]->subtype) == "plain")
-			{
-				$content .= '<span style="font-family: monospace">' . nl2br($this->decodeBody((imap_body($this->mbox, $msg_number, FT_UID)), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0])) . '</span>';
-			}
-			else if (strtolower($msg->structure[$msg_number]->subtype) == "html")
-			{
-				$content .= $this->decodeBody(imap_body($this->mbox, $msg_number, FT_UID), $msg->encoding[$msg_number][0], $msg->charset[$msg_number][0]);
-			}
+			if(strtolower($msg->structure[$msg_number]->subtype) == 'x-pkcs7-mime'){
+				$return['body']='isCripted';
+				return $return;
+			}
+
+			$content = ''; 
+			// If simple message is subtype 'html' or 'plain', then get content body. 
+			if(strtolower($msg->structure[$msg_number]->subtype) == "html" ||  
+				strtolower( $msg -> structure[ $msg_number ] -> subtype ) == 'plain'){ 
+
+					$content = $this->decodeBody( 
+						imap_body( $this -> mbox, $msg_number, FT_UID ), 
+						$msg -> encoding[ $msg_number ][ 0 ], 
+						$msg -> charset[ $msg_number ][ 0 ] 
+					); 
+
+					if ( strtolower( $msg -> structure[ $msg_number ] -> subtype ) == 'plain' ) 
+					{ 
+						$content = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $content ); 
+						$content = htmlentities( $content ); 
+						$content = $this -> replace_links( $content ); 
+						$content = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $content ); 
+						$content = '<pre style="white-space:pre;word-wrap: break-word;white-space:pre-wrap;font-family: monospace;font-size:12px">' . $content . '</pre>'; 
+
+						$return[ 'body' ] = $content; 
+
+						return $return; 
+					} 
+				}
 		}
 		else
@@ -836,13 +860,18 @@
 
 				$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 == "message/rfc822" || $file_type == "multipart/alternative") 
+				{ 
+					// Show only 'text/html' part, when message/rfc822 format contains 'text/plain' alternative part. 
+					if(array_key_exists($values+1, $msg->file_type[$msg_number]) && 
+						strtolower($msg->file_type[$msg_number][$values+1]) == 'text/plain' && 
+						array_key_exists($values+2, $msg->file_type[$msg_number]) && 
+						strtolower($msg->file_type[$msg_number][$values+2]) == 'text/html') { 
+							$has_multipart = false; 
+						} 
+				} 	
 
 				if(($file_type == "text/plain"
 					|| $file_type == "text/html")
-					&& $file_type != 'attachment')
+						&& $file_type != 'attachment')
 				{
 					if($file_type == "text/plain" && !$show_only_html && $has_multipart)
@@ -850,5 +879,6 @@
 						// 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 .= htmlentities($this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values])); 
+	                                                 $content = '<pre style="white-space:pre;word-wrap: break-word;white-space:pre-wrap;font-family: monospace;font-size:12px">' . $content . '</pre>';    
 						}
 					}
@@ -860,8 +890,8 @@
 					}
 				}
-				else if($file_type == "message/delivery-status"){
+				 else if($file_type == "message/delivery-status" || $file_type == "message/feedback-report"){ 
 					$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 .= $this->decodeBody(imap_fetchbody($this->mbox, $msg_number, $msg_part, FT_UID), $msg->encoding[$msg_number][$values], $msg->charset[$msg_number][$values]); 
+                                        $content = '<pre style="white-space:pre;word-wrap: break-word;white-space:pre-wrap;font-family: monospace;font-size:12px">' . $content . '</pre>'; 
 				}
 				else if($file_type == "message/rfc822" || $file_type == "text/rfc822-headers"){
@@ -870,47 +900,65 @@
 					$att = new imap_attachment();
 					$attachments =  $att -> get_attachment_info($this->mbox,$msg_number);
-					if($attachments['number_attachments'] > 0) {
-						foreach($attachments ['attachment'] as $index => $attachment)
-						{
-							if ( in_array( strtolower( $attachment[ 'type' ] ), array( 'delivery-status', 'rfc822', 'rfc822-headers', 'plain' ) ) )
-							{
-								$obj = imap_rfc822_parse_headers( imap_fetchbody( $this -> mbox, $msg_number, $msg_part, FT_UID ), $msg -> encoding[ $msg_number ][ $values ] );
-
-								$content .= '<hr align="left" width="95%" style="border:1px solid #DCDCDC">';
-								$content .= '<br><table  style="margin:2px;border:1px solid black;background:#EAEAEA">';
-
-								$content .= '<tr><td><b>' . $this->functions->getLang("Subject")
-									. ':</b></td><td>' .$this->decode_string($obj->subject) . '</td></tr>';
-
-								$content .= '<tr><td><b>' . $this -> functions -> getLang( 'From' ) . ':</b></td><td>'
-									. $this -> replace_links( $this -> decode_string( $obj -> from[ 0 ] -> mailbox . '@' . $obj -> from[ 0 ] -> host) )
-									. '</td></tr>';
-
-								$content .= '<tr><td><b>' . $this->functions->getLang("Date") . ':</b></td><td>' . $obj->date . '</td></tr>';
-
-								$content .= '<tr><td><b>' . $this -> functions -> getLang( 'TO' ) . ':</b></td><td>'
-									. $this -> replace_links( $this -> decode_string( $obj -> to[ 0 ] -> mailbox . '@' . $obj -> to[ 0 ] -> host ) )
-									. '</td></tr>';
-
-								if ( $obj->cc )
-									$content .= '<tr><td><b>' . $this -> functions -> getLang( 'CC' ) . ':</b></td><td>'
-										. $this -> replace_links( $this -> decode_string( $obj -> cc[ 0 ] -> mailbox . '@' . $obj -> cc[ 0 ] -> host ) )
-										. '</td></tr>';
-
-								$content .= '</table><br>';
-
-								$content .= $this->decodeBody(
-									imap_fetchbody(
-										$this->mbox,
-										$msg_number,
-										( $attachment['part_in_msg'] + (
-											( strtolower( $attachment[ 'type' ] ) == 'delivery-status' ) ? 0 : 1 )
-										) . ".1",
-										FT_UID
-									),
-									$msg->encoding[ $msg_number ][ $values ],
-									$msg->charset[ $msg_number ][ $values ]
-								);
-								break;
+					if($attachments['number_attachments'] > 0) { 
+						foreach($attachments ['attachment'] as $index => $attachment) 
+						{ 
+							if ( in_array( strtolower( $attachment[ 'type' ] ), array( 'delivery-status', 'rfc822', 'rfc822-headers', 'plain' ) ) ) 
+							{ 
+								$obj = imap_rfc822_parse_headers( imap_fetchbody( $this -> mbox, $msg_number, $msg_part, FT_UID ), $msg -> encoding[ $msg_number ][ $values ] ); 
+
+								$content .= '<hr align="left" width="95%" style="border:1px solid #DCDCDC">'; 
+								$content .= '<br><table  style="margin:2px;border:1px solid black;background:#EAEAEA">'; 
+
+								$content .= '<tr><td><b>' . $this->functions->getLang("Subject") 
+									. ':</b></td><td>' .$this->decode_string($obj->subject) . '</td></tr>'; 
+
+								$content .= '<tr><td><b>' . $this -> functions -> getLang( 'From' ) . ':</b></td><td>' 
+									. $this -> replace_links( $this -> decode_string( $obj -> from[ 0 ] -> mailbox . '@' . $obj -> from[ 0 ] -> host) ) 
+									. '</td></tr>'; 
+
+								$content .= '<tr><td><b>' . $this->functions->getLang("Date") . ':</b></td><td>' . $obj->date . '</td></tr>'; 
+
+								$content .= '<tr><td><b>' . $this -> functions -> getLang( 'TO' ) . ':</b></td><td>' 
+									. $this -> replace_links( $this -> decode_string( $obj -> to[ 0 ] -> mailbox . '@' . $obj -> to[ 0 ] -> host ) ) 
+									. '</td></tr>'; 
+
+								if ( $obj->cc ) 
+									$content .= '<tr><td><b>' . $this -> functions -> getLang( 'CC' ) . ':</b></td><td>' 
+										. $this -> replace_links( $this -> decode_string( $obj -> cc[ 0 ] -> mailbox . '@' . $obj -> cc[ 0 ] -> host ) ) 
+										. '</td></tr>'; 
+
+								$content .= '</table><br>'; 
+
+
+								$id = ( ( strtolower( $attachment[ 'type' ] ) == 'delivery-status' ) ? false : true ); 
+								if ( strtolower( $msg->structure[$msg_number]->parts[1]->parts[0]->subtype ) == 'plain' ) 
+								{ 
+									$id = !$id; 
+									if ( $msg->structure[$msg_number]->parts[1]->parts[0]->encoding == 4 ) 
+										$msg->encoding[ $msg_number ][ $values ] = 'quoted-printable'; 
+								} 
+
+								$body = $this->decodeBody( 
+									imap_fetchbody( 
+										$this->mbox, 
+										$msg_number, 
+										( $attachment['part_in_msg'] + ( ( int ) $id ) ) . ".1", 
+										FT_UID 
+									), 
+									$msg->encoding[ $msg_number ][ $values ], 
+									$msg->charset[ $msg_number ][ $values ] 
+								); 
+
+								if ( strtolower( $msg->structure[$msg_number]->parts[1]->parts[0]->subtype ) == 'plain' ) 
+								{ 
+									$body = str_replace( array( '<', '>' ), array( ' #$<$# ', ' #$>$# ' ), $body ); 
+									$body = htmlentities( $body ); 
+									$body = $this -> replace_links( $body ); 
+									$body = str_replace( array( ' #$&lt;$# ', ' #$&gt;$# ' ), array( '&lt;', '&gt;' ), $body ); 
+									$body = '<pre style="white-space:pre;word-wrap: break-word;white-space:pre-wrap;font-family: monospace;font-size:12px">' . $body . '</pre>'; 
+								} 
+
+								$content .= $body; 
+								break; 
 							}
 						}
@@ -1151,32 +1199,68 @@
 	function replace_links( $body )
 	{
-  		$matches = array( );
-		// Verify exception.
-		@preg_match( "/<a href=\"notes:\/\/\//", $body, $matches );
-
-		// If there is no exception, then open the link in new window.
-		if ( count( $matches ) )
-			return $body;
-
-		// All links should be moderated and they should only have the attribute 'target="blank"'.
-		$pattern = '/<a[^>]+href="([^>"]+)"[^>]*>(.*)<\/a>/im';
-		$replacement = '<a href="$1" target="_blank">$2</a>';
+  		// Domains and IPs addresses found in the text and which is not a link yet should be replaced by one. 
+		// See more informations in www.iana.org 
+		$octets = array( 
+			'first' => '(2[0-3][0-9]|1[0-9]{2}|[1-9][0-9]?)', 
+			'middle' => '(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})', 
+			'last' => '(25[0-4]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)' 
+		); 
+
+		$ip = "\b{$octets[ 'first' ]}\.({$octets[ 'middle' ]}\.){2}{$octets[ 'last' ]}\b"; 
+
+		$top_level_domains = '(\.(ac|ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|as|asia|at|au|aw|ax|az|' 
+			. 'ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bl|bm|bn|bo|br|bs|bt|bv|bw|by|bz|' 
+			. 'ca|cat|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cu|cv|cx|cy|cz|' 
+			. 'de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|' 
+			. 'ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|' 
+			. 'hk|hm|hn|hr|ht|hu|id|ie|il|im|in|info|int|io|iq|ir|is|it|je|jm|jo|jobs|jp|' 
+			. 'ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|' 
+			. 'ma|mc|md|me|mf|mg|mh|mil|mk|ml|mm|mn|mo|mobi|mp|mq|mr|ms|mt|mu|museum|' 
+			. 'mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|' 
+			. 'pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|ps|pt|pw|py|qa|re|ro|rs|ru|rw|' 
+			. 'sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|' 
+			. 'tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|travel|tt|tv|tw|tz|' 
+			. 'ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw))+\b'; 
+
+		$path = '(?>\/[\w\d\/\.\'\(\)\-\+~?!&#@$%|:;,*=_]+)?'; 
+		$port = '(?>:\d{2,5})?'; 
+		$domain = '(?>[\w\d_\-]+)'; 
+		$subdomain = "(?>{$domain}\.)*"; 
+		$protocol = '(?>(http|ftp)(s)?:\/\/)?'; 
+		$url = "(?>{$protocol}((?>{$subdomain}{$domain}{$top_level_domains}|{$ip}){$port}{$path}))"; 
+
+		$pattern = "/(<\w[^>]+|[\/\"'@=])?{$url}/";
+		ini_set( 'pcre.backtrack_limit', 300000 ); 
+
+		/* 
+		// PHP 5.3 
+		$replace = function( $matches ) 
+		{ 
+			if ( $matches[ 1 ] ) 
+				return $matches[ 0 ]; 
+
+			$url = ( $matches[ 2 ] ) ? $matches[ 2 ] : 'http'; 
+			$url .= "{$matches[ 3 ]}://{$matches[ 4 ]}"; 
+			return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>"; 
+		}; 
+		$body = preg_replace_callback( $pattern, $replace, $body ); 
+		 */ 
+
+		// PHP 5.2.x - Remover assim que possível 
+		$body = preg_replace_callback( $pattern, 
+			create_function( 
+				'$matches', 
+				'if ( $matches[ 1 ] ) return $matches[ 0 ];' 
+				. '$url = ( $matches[ 2 ] ) ? $matches[ 2 ] : "http";'
+				. '$url .= "{$matches[ 3 ]}://{$matches[ 4 ]}";'
+				. 'return "<a href=\"{$url}\" target=\"_blank\">{$matches[ 4 ]}</a>";'
+			), $body
+		);
+		ini_set( 'pcre.backtrack_limit', 100000 ); 
+		// E-mail address in the text should create a new e-mail on ExpressoMail
+		$pattern = '/( |<|&lt;|>)([A-Za-z0-9\.~?\/_=#\-]*@[A-Za-z0-9\.~?\/_=#\-]*)( |>|&gt;|<)/im'; 
+		$replacement = '$1<a href="mailto:$2">$2</a>$3';
 		$body = preg_replace( $pattern, $replacement, $body );
 
-		// Url found in the text and which is not a link yet should be replaced by one.
-		$pattern = '/(^|\w>|[ \(\[])((http(s)?:\/\/)?([\w\d_\-@]{2,}(\.[\w\d~?\/_=&#;\-:@$]+)+))/im';
-		$replacement = '$1<a href="http$4://$5" target="_blank">$2</a>';
-		$body = preg_replace( $pattern, $replacement, $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="javascript:new_message_to(\'$2\')">$2</a>$3';
-		$body = preg_replace( $pattern, $replacement, $body );
-
-		// If there is an link with a "mailto:" in href attribute, it will changed to create a new e-mail on ExpressoMail.
-		$pattern = '/<a[^>]+href=["\']mailto:([^"]+)["\'][^>]*>([^<]+)<\/a>/im';
-		$replacement = '<a href="javascript:new_message_to(\'$1\')">$2</a>';
-		$body = preg_replace( $pattern, $replacement, $body );
-
 		return $body;
 	}
@@ -1184,5 +1268,5 @@
 	function get_signature($msg, $msg_number, $msg_folder)
 	{
-        include_once("../security/classes/CertificadoB.php");
+        include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
 		include_once("class.db_functions.inc.php");
 		foreach ($msg->file_type[$msg_number] as $index => $file_type)
@@ -1557,17 +1641,22 @@
 			$this->delete_mailbox(array("del_past" => "INBOX/decifradas"));
 		}
-		$serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}";
-		$folders_list = imap_getmailboxes($mbox_stream, $serverString, ($params && $params['noSharedFolders']) ? "INBOX/*" : "*");
-		$folders_list = array_slice($folders_list,0,$this->foldersLimit);
-
-		$tmp = array();
-		$resultMine = array();
-		$resultDefault = array();
+
 
 		$inbox = 'INBOX';
 		$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'];
+		$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'];
+		$uid2cn = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']; 
+		// Free others requests 
+		session_write_close(); 
+
+		$serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}"; 
+		$folders_list = imap_getmailboxes($mbox_stream, $serverString, ($params && $params['noSharedFolders']) ? "INBOX/*" : "*"); 
+		$folders_list = array_slice($folders_list,0,$this->foldersLimit); 
+
+		$tmp = array(); 
+		$resultMine = array(); 
+		$resultDefault = array(); 
 
 		if (is_array($folders_list)) {
@@ -1593,5 +1682,5 @@
 				$result[$i]['folder_name'] = array_pop($tmp_folder_parent);
 				$result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
-				if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($folder_id,0,4) == 'user') {
+				if ($uid2cn && substr($folder_id,0,4) == 'user') {
 					//$this->ldap = new ldap_functions();
 					if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])) {
@@ -1798,7 +1887,4 @@
 				return "The server denied your request to send a mail, you cannot use this mail address.";
 		}
-
-		//new_message_to backs to mailto: pattern
-		$params['body'] = eregi_replace("<a href=\"javascript:new_message_to\('([^>]+)'\)\">[^>]+</a>","<a href='mailto:\\1'>\\1</a>",$params['body']);
 
 		$toaddress = implode(',',$db->getAddrs(explode(',',$params['input_to'])));
@@ -1997,53 +2083,7 @@
             $mail->Certs_crypt = $aux_mails;
         }
-
-////////////////////////////////////////////////////////////////////////////////////////////////////
-		//	Build CID for embedded Images!!!
-		$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[6] as $j => $val){
-				if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
-      			{
-                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
-		        }
-		        $cid = $cid_array[$cid_imgs[4][$j].$val];
-        		$mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
-
-				if (!$forwarding_attachments[$cid_imgs[6][$j]-2]) // The image isn't in the same mail?
-				{
-					$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
-					$fileName = "image_".($j).".jpg";
-					$fileCode = "base64";
-					$fileType = "image/jpg";
-				}
-				else
-				{
-					$attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
-					$file_description = unserialize(rawurldecode($attach_img));
-
-					foreach($file_description as $i => $descriptor){
-						$file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
-					}
-					$fileContent = $this->get_forwarding_attachment($file_description[0], $cid_imgs[4][$j], $file_description[3], 'base64');
-					$fileName = $file_description[2];
-					$fileCode = $file_description[4];
-					$fileType = $this->get_file_type($file_description[2]);
-					unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
-				}
-				$tempDir = ini_get("session.save_path");
-				$file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";
-				$f = fopen($tempDir.'/'.$file,"w");
-				fputs($f,$fileContent);
-				fclose($f);
-				if ($fileContent)
-					$mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
-				//else
-				//	return "Error loading image attachment content";
-
-		}
-////////////////////////////////////////////////////////////////////////////////////////////////////
+                // Build CID images 
+		$this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments); 
+
 		//	Build Uploading Attachments!!!
 		if ((count($attachments)) && ($params['is_local_forward']!="1")) //Caso seja forward normal...
@@ -2080,4 +2120,5 @@
 		{
 			// Bug fixed for array_search function
+			$name_cid_files = array(); 
 			if(count($name_cid_files) > 0) {
 				$name_cid_files[count($name_cid_files)] = $name_cid_files[0];
@@ -2142,6 +2183,71 @@
 		}
 	}
-
-    function add_recipients_cert($full_address)
+	function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments) 
+	{ 
+		//      Build CID for embedded Images!!! 
+		$pattern = '/src="([^"]*?show_embedded_attach.php\?msg_folder=(.+)?&(amp;)?msg_num=(.+)?&(amp;)?msg_part=(.+)?)"/isU'; 
+		$cid_imgs = ''; 
+		preg_match_all($pattern,$mail->Body,$cid_imgs,PREG_PATTERN_ORDER); 
+		$cid_array = array(); 
+		foreach($cid_imgs[6] as $j => $val){ 
+			if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) ) 
+			{ 
+				$cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36); 
+			} 
+			$cid = $cid_array[$cid_imgs[4][$j].$val];  
+			$mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body); 
+
+			if ($msg_uid != $cid_imgs[4][$j]) // The image is not in the same mail? 
+			{ 
+				$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64'); 
+				//prototype: get_forwarding_attachment ( folder, msg number, part, encoding) 
+				$fileName = "image_".($j).".jpg"; 
+				$fileCode = "base64"; 
+				$fileType = "image/jpg"; 
+				$file_attached[0] = $cid_imgs[2][$j]; 
+				$file_attached[1] = $cid_imgs[4][$j]; 
+				$file_attached[2] = $fileName; 
+				$file_attached[3] = $cid_imgs[6][$j]; 
+				$file_attached[4] = 'base64'; 
+				$file_attached[5] = strlen($fileContent); //Size of file 
+				$return_forward[] = $file_attached; 
+
+				$attachment_ = unserialize(rawurldecode($forwarding_attachments[$cid_imgs[6][$j]-2])); 
+				if ($file_attached[3] == $attachment_[3]) 
+					unset($forwarding_attachments[$cid_imgs[6][$j]-2]); 	
+			} 
+			else 
+			{ 
+				$attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2]; 
+				$file_description = unserialize(rawurldecode($attach_img)); 
+				if (is_array($file_description)) 
+					foreach($file_description as $i => $descriptor){                                 
+						$file_description[$i]  = eregi_replace('\'*\'','',$descriptor); 
+					} 
+				$fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64'); 
+				$fileName = $file_description[2]; 
+				$fileCode = $file_description[4]; 
+				$fileType = $this->get_file_type($file_description[2]); 
+				unset($forwarding_attachments[$cid_imgs[6][$j]-2]); 
+				if (!empty($file_description)) 
+				{ 
+					$file_description[5] = strlen($fileContent); //Size of file 
+					$return_forward[] = $file_description; 
+				} 
+			} 
+			$tempDir = ini_get("session.save_path"); 
+			$file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";                                        
+			$f = fopen($tempDir.'/'.$file,"w"); 
+			fputs($f,$fileContent); 
+			fclose($f); 
+			if ($fileContent) 
+				$mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType); 
+			//else 
+			//      return "Error loading image attachment content";                                                 
+
+		} 
+		return $return_forward; 
+	} 
+	function add_recipients_cert($full_address)
 	{
 		$result = "";
@@ -2512,62 +2618,5 @@
 		$mail->Body = $body;
 
-		//	Build CID for embedded Images!!!
-		$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[6] as $j => $val){
-				if ( !array_key_exists($cid_imgs[4][$j].$val, $cid_array) )
-      			{
-                $cid_array[$cid_imgs[4][$j].$val] = base_convert(microtime(), 10, 36);
-		        }
-		        $cid = $cid_array[$cid_imgs[4][$j].$val];
-        		$mail->Body = str_replace($cid_imgs[1][$j], "cid:".$cid, $mail->Body);
-
-				if ($msg_uid != $cid_imgs[4][$j]) // The image isn't in the same mail?
-				{
-					$fileContent = $this->get_forwarding_attachment($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
-					//prototype: get_forwarding_attachment ( folder, msg number, part, encoding)
-					$fileName = "image_".($j).".jpg";
-					$fileCode = "base64";
-					$fileType = "image/jpg";
-					$file_attached[0] = $cid_imgs[2][$j];
-					$file_attached[1] = $cid_imgs[4][$j];
-					$file_attached[2] = $fileName;
-					$file_attached[3] = $cid_imgs[6][$j];
-					$file_attached[4] = 'base64';
-					$file_attached[5] = strlen($fileContent); //Size of file
-					$return_forward[] = $file_attached;
-				}
-				else
-				{
-					$attach_img = $forwarding_attachments[$cid_imgs[6][$j]-2];
-					$file_description = unserialize(rawurldecode($attach_img));
-					foreach($file_description as $i => $descriptor){
-						$file_description[$i]  = eregi_replace('\'*\'','',$descriptor);
-					}
-					$fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64');
-					$fileName = $file_description[2];
-					$fileCode = $file_description[4];
-					$fileType = $this->get_file_type($file_description[2]);
-					unset($forwarding_attachments[$cid_imgs[6][$j]-2]);
-					if (!empty($file_description))
-					{
-						$file_description[5] = strlen($fileContent); //Size of file
-						$return_forward[] = $file_description;
-					}
-				}
-				$tempDir = ini_get("session.save_path");
-				$file = "cidimage_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].$cid_imgs[6][$j].".dat";
-				$f = fopen($tempDir.'/'.$file,"w");
-				fputs($f,$fileContent);
-				fclose($f);
-				if ($fileContent)
-					$mail->AddEmbeddedImage($tempDir.'/'.$file, $cid, $fileName, $fileCode, $fileType);
-				//else
-				//	return "Error loading image attachment content";
-
-		}
+		$return_forward = $this->buildEmbeddedImages($mail,$msg_uid,$forwarding_attachments); 
 
 	//	Build Forwarding Attachments!!!
@@ -3159,4 +3208,6 @@
 		$criteria =  'BEFORE "'.$before_date.'"';
 		$mbox_stream = $this->open_mbox('INBOX'.$this->imap_delimiter.$_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']);
+		// Free others requests 
+                session_write_close(); 
 		$messages = imap_search($mbox_stream, $criteria, SE_UID);
 		if (is_array($messages)){
@@ -3201,5 +3252,4 @@
 
 	function search_msg($params = ''){
-            $retorno = "";
             $mbox_stream = "";
             if(strpos($params['condition'],"#")===false) { //local messages
@@ -3280,4 +3330,10 @@
                                 foreach($search_criteria as $new_search)
                                 {
+				    $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream); 
+				    $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ); 
+				    $elem['uid'] = $new_search; 
+				    $retorno[] = $elem; 
+
+				    /* NOTE: This code was lost on 2.2 merge 
                                     if ($search_result_number != '65536' && $sum == $search_result_number)
                                     {
@@ -3290,5 +3346,6 @@
                                         $retorno .= $m_token;
                                         $sum ++;
-                                    }
+				    }
+				     */
                                 }
                             }
@@ -3300,11 +3357,16 @@
                         {
                             foreach($search_criteria as $new_search)
-                            {
-                                if ($search_result_number != '65536' && $sum == $search_result_number)
+			    {
+				    $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream); 
+				    $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ); 
+				    $elem['uid'] = $new_search; 
+				    $retorno[] = $elem; 
+		                //  NOTE: This code was lost on 2.2 merge 
+				/*if ($search_result_number != '65536' && $sum == $search_result_number)
                                 {
                                     return $retorno ? $sum . "=sumResults=" . $retorno : "none";
                                 }
                                 $retorno .= trim("##".mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
-                                $sum++;
+				$sum++;*/
                             }
                         }
@@ -3327,8 +3389,8 @@
 	}
 
-	function get_msg($uid_msg,$name_box, $mbox_stream )
+	function get_msg_detail($uid_msg,$name_box, $mbox_stream )
 	{
 		$header = $this->get_header($uid_msg);
-		include_once("class.imap_attachment.inc.php");
+		require_once("class.imap_attachment.inc.php");
 		$imap_attachment = new imap_attachment();
 		$attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
@@ -3347,17 +3409,11 @@
 		if($header->from[0]->personal != "")
 			$from = $header->from[0]->personal;
-		$ret_msg = $this->decode_string($from) . "--" . $subject . "--". gmdate("d/m/Y",$header ->udate)."--". $this->size_msg($header->Size) ."--". $flag;
+		$ret_msg['from'] = $this->decode_string($from); 
+		$ret_msg['subject'] = $subject; 
+		$ret_msg['udate'] = $header ->udate; 
+		$ret_msg['size'] = $header->Size; 
+		$ret_msg['flag'] = $flag; 
 		return $ret_msg;
 	}
-
-	function size_msg($size){
-		$var = floor($size/1024);
-		if($var >= 1){
-			return $var." kb";
-		}else{
-			return $size ." b";
-		}
-	}
-
 	function ob_array($the_object)
 	{
Index: branches/2.2/expressoMail1_2/inc/gotodownload.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/gotodownload.php	(revision 1937)
+++ branches/2.2/expressoMail1_2/inc/gotodownload.php	(revision 3018)
@@ -12,5 +12,5 @@
 	$msg_number = $_GET['msg_number'];
 	$idx_file = $_GET['idx_file'];
-	$newfilename = $_GET['newfilename'];
+	$newfilename = urldecode($_GET['newfilename']);
 	$msg_part = $_GET['msg_part'];
 	$msg_folder = $_GET['msg_folder'];
@@ -171,11 +171,30 @@
 			if (preg_match("#^".ini_get('session.save_path')."/(".$GLOBALS['phpgw']->session->sessionid."/)*[A-z]+_".$GLOBALS['phpgw']->session->sessionid."[A-z0-9]*(\.[A-z]{3,4})?$#",$strFileName))
 			{
-				readfile($strFileName);
-				exec("rm -f ".escapeshellcmd(escapeshellarg($strFileName)));
+				if (preg_match("#^".dirname( __FILE__ ) . '/../tmpLclAtt'."/source_#",$strFileName)) {
+					//avoid stuck request 
+					session_write_close(); 
+
+					//reset time limit for big files 
+					set_time_limit(0); 
+					ob_end_flush(); 
+
+					if ($fp = fopen ($strFileName, 'rb')) 
+					{ 
+						$bufferSize=1024; 
+						for ($i=$bufferSize; $i<=(filesize($strFileName)+$bufferSize); $i+=$bufferSize)  
+						{ 
+							echo fread($fp, $i); 
+							flush(); 
+						} 
+						fclose ($fp); 
+					} 
+					//readfile($strFileName); 	
+
+					exec("rm -f ".escapeshellcmd(escapeshellarg($strFileName)));
+				}
+				else 
+					if (preg_match("#^".dirname( __FILE__ ) . '/../tmpLclAtt'."/source_#",$strFileName)) {
+						readfile($strFileName);
+					}
 			}
-			else 
-				if (preg_match("#^".dirname( __FILE__ ) . '/../tmpLclAtt'."/source_#",$strFileName)) {
-					readfile($strFileName);
-				}
-	}
 ?>
Index: branches/2.2/expressoMail1_2/inc/show_thumbs.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/show_thumbs.php	(revision 1040)
+++ branches/2.2/expressoMail1_2/inc/show_thumbs.php	(revision 3018)
@@ -1,12 +1,5 @@
 <?php
-if(!isset($GLOBALS['phpgw_info'])){
-	$GLOBALS['phpgw_info']['flags'] = array(
-		'currentapp' => 'expressoMail1_2',
-		'nonavbar'   => true,
-		'noheader'   => true
-	);
-}
-require_once '../../header.inc.php';
 
+	require_once '../../header.session.inc.php'; 
 	$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
 	$password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
@@ -31,18 +24,16 @@
 	$image_mail = imap_fetchbody($mb, $msg_num, $msg_part, FT_UID);
 	$image = imap_base64($image_mail);
-	$image = imagecreatefromstring ($image);
-	
-	header("Content-Type: ".$file_type);
-	header("Content-Disposition: inline");
- 
-	$pic = $image;
-    if ($pic) {
-        $width = imagesx($pic);
-        $height = imagesy($pic);
-        $twidth = 160; # width of the thumb 160 pixel
-        $theight = $twidth * $height / $width; # calculate height
-        $thumb = imagecreatetruecolor ($twidth, $theight);
+	$pic = @imagecreatefromstring ($image);
+	if($pic !== FALSE) { 
+		header("Content-Type: ".$file_type); 
+		header("Content-Disposition: inline");
+		$width = imagesx($pic);
+		$height = imagesy($pic);
+		$twidth = 160; # width of the thumb 160 pixel
+		$theight = $twidth * $height / $width; # calculate height
+		$theight =  $theight < 1 ? 1 : $theight; 
+		$thumb = imagecreatetruecolor ($twidth, $theight);
 		imagecopyresized($thumb, $pic, 0, 0, 0, 0,$twidth, $theight, $width, $height); # resize image into thumb
 		imagejpeg($thumb,"",75); # Thumbnail as JPEG
-    }
+	}
 ?>
Index: branches/2.2/expressoMail1_2/inc/class.ScriptS.inc.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/class.ScriptS.inc.php	(revision 1352)
+++ branches/2.2/expressoMail1_2/inc/class.ScriptS.inc.php	(revision 3018)
@@ -62,5 +62,6 @@
 			if(!$aux){
 				// Caso de erro, grava dentro da variável errstr;
-				$this->errstr = "O arquivo não foi criado";
+                                $this->errstr = "Error: file not created"; 
+                                return $this->errstr; 
 			}
 			// Mata a variavel;
@@ -71,5 +72,6 @@
 			if(!$aux){
 				// Caso de erro, grava dentro da variavel errstr;
-				$this->errstr = "O arquivo não foi ativado";
+                                $this->errstr = "Error: error to activate file"; 
+                                return $this->errstr; 
 			}
 			else{
@@ -84,9 +86,6 @@
 		$this->SieveS->close();
 			
-		if($this->rules){		
+		if($this->rules)
 			return $this->rules;
-		}else{
-			return $this->errstr;
-		}
 			
 	}
@@ -99,4 +98,5 @@
 	
 		$var_decode = rawurldecode($params['arfilter']);
+		$var_decode = preg_replace('/\n\./', '.', $var_decode);
 		
 		$narray  = explode("_end_",$var_decode);
Index: branches/2.2/expressoMail1_2/inc/class.message_components.inc.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/class.message_components.inc.php	(revision 1739)
+++ branches/2.2/expressoMail1_2/inc/class.message_components.inc.php	(revision 3018)
@@ -112,11 +112,11 @@
                     $skip_next    = ($ftype == 'message/rfc822')?        true : false;
 
-                    if ($ftype == 'multipart/mixed' || $skip_part == true && $ftype == 'multipart/alternative' || $ftype == 'multipart/related' )
+		    if ($ftype == 'multipart/report' || $ftype == 'multipart/mixed' || $skip_part == true && $ftype == 'multipart/alternative' || ( $ftype == 'multipart/related' && strtolower( $parts[$p]->parts[0]->subtype ) == 'alternative' ) ) 
                     {
                         $n--;
                     }
                     else
-                    {
-                        $this->pid[$mid][$n]       = ($is_sub_part == false)? $i : ($sub_pid == '' ? '1' : $sub_pid).'.'.$i;
+		    {
+			$this->pid[$mid][$n]       = ($is_sub_part == false || $skip_part && $ftype == 'multipart/related' )? $i : ($sub_pid == '' ? '1' : $sub_pid).'.'.$i; 
                         $this->file_type[$mid][$n] = $ftype;
                         $this->encoding[$mid][$n]  = $encoding;
Index: branches/2.2/expressoMail1_2/inc/class.SieveS.inc.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/class.SieveS.inc.php	(revision 1149)
+++ branches/2.2/expressoMail1_2/inc/class.SieveS.inc.php	(revision 3018)
@@ -178,5 +178,5 @@
 
 		//Verifica a conexao
-		if(!$this->socket){
+		if(!is_resource($this->socket)){ 
 			$this->errstr = "listscripts: sem conexão para o servidor $this->host";
 			return false;
@@ -187,5 +187,5 @@
 	
 		$said = $this->read();
-		while (!preg_match("/^OK/",$said) && !preg_match("/^NO/",$said)) {
+		while (is_resource($this->socket) && (!preg_match("/^OK/",$said) && !preg_match("/^NO/",$said))) { 
 	
 		    // Cyrus v1 script lines look like '"script*"' with the 
Index: branches/2.2/expressoMail1_2/inc/show_img.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/show_img.php	(revision 1040)
+++ branches/2.2/expressoMail1_2/inc/show_img.php	(revision 3018)
@@ -1,12 +1,5 @@
 <?php
-if(!isset($GLOBALS['phpgw_info'])){
-        $GLOBALS['phpgw_info']['flags'] = array(
-                'currentapp' => 'expressoMail1_2',
-                'nonavbar'   => true,
-                'noheader'   => true
-        );
-}
-require_once '../../header.inc.php';
 
+	require_once '../../header.session.inc.php'; 
 	header("Content-Type: image/jpeg");
 	if($_GET['msg_num'] && $_GET['msg_part'] && $_GET['msg_folder']) {
Index: branches/2.2/expressoMail1_2/inc/show_embedded_attach.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/show_embedded_attach.php	(revision 1040)
+++ branches/2.2/expressoMail1_2/inc/show_embedded_attach.php	(revision 3018)
@@ -1,11 +1,5 @@
 <?php
-if(!isset($GLOBALS['phpgw_info'])){
-        $GLOBALS['phpgw_info']['flags'] = array(
-                'currentapp' => 'expressoMail1_2',
-                'nonavbar'   => true,
-                'noheader'   => true
-        );
-}
-require_once '../../header.inc.php';
+
+	require_once '../../header.session.inc.php'; 
 
 	$username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
Index: branches/2.2/expressoMail1_2/inc/hook_home.inc.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/hook_home.inc.php	(revision 1402)
+++ branches/2.2/expressoMail1_2/inc/hook_home.inc.php	(revision 3018)
@@ -11,6 +11,8 @@
 	$current_app = 'expressoMail1_2';
 	$current_name	 = 'Expresso Mail';
-	$preferences = $GLOBALS['phpgw']->preferences->read();
-        $_SESSION['phpgw_info']['user']['preferences']['expressoMail'] = $preferences['expressoMail'];
+	if(!$_SESSION['phpgw_info']['user']['preferences']['expressoMail']) { 
+		$preferences = $GLOBALS['phpgw']->preferences->read(); 
+		$_SESSION['phpgw_info']['user']['preferences']['expressoMail'] = $preferences['expressoMail'];
+	}
   	$homedisplay = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['mainscreen_showmail'];
 	if($homedisplay=='True')
Index: branches/2.2/expressoMail1_2/inc/class.functions.inc.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/class.functions.inc.php	(revision 1572)
+++ branches/2.2/expressoMail1_2/inc/class.functions.inc.php	(revision 3018)
@@ -116,6 +116,10 @@
             	$h = ord($c{0});   
 	            if ($h <= 0x7F || $h < 0xC2) {
-	            	$result .= $c;
-	            }
+			    // fixing curly brackets 
+			    if($h == 0x7B || $h == 0x7D) 
+				    $result .= "&#" . $h . ";"; 
+			    else 
+				    $result .= $c;
+		    }
 	           	else if ($h <= 0xDF) {
 	                $h = ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
Index: branches/2.2/expressoMail1_2/inc/class.phpmailer.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/class.phpmailer.php	(revision 1793)
+++ branches/2.2/expressoMail1_2/inc/class.phpmailer.php	(revision 3018)
@@ -525,34 +525,16 @@
         for($i = 0; $i < count($this->to); $i++)
         {
-            if($this->valEm($this->to[$i][0]))
-            {
-                if(!$this->smtp->Recipient($this->to[$i][0]))  $bad_rcpt[] = $this->to[$i][0];
-            }
-            else
-            {
-                $errorx .= $this->to[$i][0] . ', ';
-            }
+		if(!$this->smtp->Recipient($this->to[$i][0]))
+			$bad_rcpt[] = $this->to[$i][0];
         }
         for($i = 0; $i < count($this->cc); $i++)
         {
-            if($this->valEm($this->cc[$i][0]))
-            {
-                if(!$this->smtp->Recipient($this->cc[$i][0])) $bad_rcpt[] = $this->cc[$i][0];
-            }
-			else
-            {
-                $errorx .= $this->cc[$i][0] . ', ';
-            }
+		if(!$this->smtp->Recipient($this->cc[$i][0]))
+			$bad_rcpt[] = $this->cc[$i][0];
         }
         for($i = 0; $i < count($this->bcc); $i++)
         {
-            if($this->valEm($this->bcc[$i][0]))
-            {
-                if(!$this->smtp->Recipient($this->bcc[$i][0])) $bad_rcpt[] = $this->bcc[$i][0];
-            }
-			else
-            {
-                $errorx .= $this->bcc[$i][0] . ', ';
-            }
+                if(!$this->smtp->Recipient($this->bcc[$i][0]))
+			$bad_rcpt[] = $this->bcc[$i][0];      
         }
         if($errorx != '')
@@ -728,31 +710,4 @@
     }
 
-    function valEm($email)
-    {
-        $mail_retorno = FALSE;
-        if ((strlen($email) >= 6) && (substr_count($email,"@") == 1) && (substr($email,0,1) != "@") && (substr($email,strlen($email)-1,1) != "@"))
-        {
-            if ((!strstr($email,"'")) && (!strstr($email,"\"")) && (!strstr($email,"\\")) && (!strstr($email,"\$")) && (!strstr($email," ")))
-            {
-                //testa se tem caracter .
-                if (substr_count($email,".")>= 1)
-                {
-                    //obtem a terminação do dominio
-                    $term_dom = substr(strrchr ($email, '.'),1);
-                    //verifica se terminação do dominio esta correcta
-                    if (strlen($term_dom)>1 && strlen($term_dom)<5 && (!strstr($term_dom,"@")) )
-                    {
-                        $antes_dom = substr($email,0,strlen($email) - strlen($term_dom) - 1);
-                        $caracter_ult = substr($antes_dom,strlen($antes_dom)-1,1);
-                        if ($caracter_ult != "@" && $caracter_ult != ".")
-                        {
-                            $mail_retorno = TRUE;
-                        }
-                    }
-                }
-            }
-        }
-        return $mail_retorno;
-    }
 
     /**
Index: branches/2.2/expressoMail1_2/inc/show_user_photo.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/show_user_photo.php	(revision 1495)
+++ branches/2.2/expressoMail1_2/inc/show_user_photo.php	(revision 3018)
@@ -1,11 +1,5 @@
 <?php
-if(!isset($GLOBALS['phpgw_info'])){
-	$GLOBALS['phpgw_info']['flags'] = array(
-		'currentapp' => 'expressoMail1_2',
-		'nonavbar'   => true,
-		'noheader'   => true
-	);
-}
-require_once '../../header.inc.php';
+
+	require_once '../../header.session.inc.php'; 
 
 
