Index: trunk/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 7413)
+++ trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 7414)
@@ -3163,4 +3163,5 @@
                 $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
 
+            $mailService->addHeaderField('Date', date("r"));
 
             if ($folder != 'null') {
@@ -4660,5 +4661,5 @@
 
     function insert_email($source,$folder,$timestamp,$flags){
-		
+
         $username = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
         $password = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
@@ -4667,46 +4668,63 @@
         $imap_options = '/notls/novalidate-cert';
 
-	
         $folder = mb_convert_encoding( $folder, "UTF7-IMAP","ISO-8859-1");
-
         $mbox_stream = imap_open("{".$imap_server.":".$imap_port.$imap_options."}".$folder, $username, $password);
         
         if(imap_last_error() === 'Mailbox already exists')
             imap_createmailbox($mbox_stream,imap_utf7_encode("{".$imap_server."}".$folder));
+
         if($timestamp){
-			$pdate = date_parse(date('r')); // pega a data atual do servidor (TODO: pegar a data da mensagem local) 
-			$timestamp += $pdate['zone']*(60); //converte a data da mensagem para o fuso horário GMT 0. Isto é feito devido ao Expresso Mail armazenar a data no fuso horário GMT 0 e para exibi-la converte ela para o fuso horário local. 
-			/* TODO: o diretorio /tmp deve ser substituido pelo diretorio temporario configurado no setup */ 
-			$file = "/tmp/sess_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]; 
-		
-    		$f = fopen($file,"w");
-        	fputs($f,base64_encode($source));
-            fclose($f);
-            $command = "python ".dirname(__FILE__)."/../imap.py \"$imap_server\" \"$imap_port\" \"$username\" \"$password\" \"$timestamp\" \"$folder\" \"$file\"";
-            $return['command']= exec($command);
+            if(version_compare(PHP_VERSION, '5.3.2', '>=')){
+                $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".mb_convert_encoding($folder, "UTF7-IMAP","ISO_8859-1"), $source,'',date('d-M-Y H:i:s O',$timestamp));
+            }else{
+				$pdate = date_parse(date('r')); // pega a data atual do servidor (TODO: pegar a data da mensagem local) 
+				$timestamp += $pdate['zone']*(60); //converte a data da mensagem para o fuso horário GMT 0. Isto é feito devido ao Expresso Mail armazenar a data no fuso horário GMT 0 e para exibi-la converte ela para o fuso horário local. 
+				/* TODO: o diretorio /tmp deve ser substituido pelo diretorio temporario configurado no setup */ 
+				$file = "/tmp/sess_".$_SESSION[ 'phpgw_session' ][ 'session_id' ]; 
+			
+	    		$f = fopen($file,"w");
+	        	fputs($f,base64_encode($source));
+	            fclose($f);
+	            $command = "python ".dirname(__FILE__)."/../imap.py \"$imap_server\" \"$imap_port\" \"$username\" \"$password\" \"$timestamp\" \"$folder\" \"$file\"";
+	            $return['command']= exec($command);
+	        }
         }else{
             $return['append'] = imap_append($mbox_stream, "{".$imap_server.":".$imap_port."}".$folder, $source, "\\Seen");
         }
+
+        if (!empty($return['command']))
+        {
+            list ($result, $msg) = explode(':',$return['command']);
+            if (strtoupper($result) === 'NO')
+            {
+                $return['error'] = $msg;
+                return $return;
+            }
+        }
+
         $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
 			
         $return['msg_no'] = $status->uidnext - 1;
-	$return['error'] = imap_last_error();
-	if(!$return['error'] && $flags != '' ){
-
-                  $flags_array=explode(':',$flags);
-                  //"Answered","Draft","Flagged","Unseen"
-                  $flags_fixed = "";
-                  if($flags_array[0] == 'A')
-                        $flags_fixed.="\\Answered ";
-                  if($flags_array[1] == 'X')
-                        $flags_fixed.="\\Draft ";
-                  if($flags_array[2] == 'F')
-                        $flags_fixed.="\\Flagged ";
-                  if($flags_array[3] != 'U')
-                        $flags_fixed.="\\Seen ";
-                  if($flags_array[4] == 'F')
-                        $flags_fixed.="\\Answered \\Draft ";
-                  imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
-                }
+		
+        $return['error'] = '';
+		if(imap_last_error() && imap_last_error() != "SECURITY PROBLEM: insecure server advertised AUTH=PLAIN")
+            $return['error'] = imap_last_error();
+
+		if(!$return['error'] && $flags != '' ){
+			$flags_array=explode(':',$flags);
+			//"Answered","Draft","Flagged","Unseen"
+			$flags_fixed = "";
+			if($flags_array[0] == 'A')
+			    $flags_fixed.="\\Answered ";
+			if($flags_array[1] == 'X')
+			    $flags_fixed.="\\Draft ";
+			if($flags_array[2] == 'F')
+			    $flags_fixed.="\\Flagged ";
+			if($flags_array[3] != 'U')
+			    $flags_fixed.="\\Seen ";
+			if($flags_array[4] == 'F')
+			    $flags_fixed.="\\Answered \\Draft ";
+			imap_setflag_full($mbox_stream, $return['msg_no'], $flags_fixed, ST_UID);
+		}
 	
         //Ignorando erro de AUTH=Plain
@@ -4773,47 +4791,80 @@
 
     function treat_base64_from_post($source){
-            $offset = 0;
-            do
+    	$source = preg_replace('/(?<!\r)\n/', "\r\n", $source);
+
+        $offset = 0;
+        do
+        {
+            if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
             {
-                    if($inicio = strpos($source, 'Content-Transfer-Encoding: base64', $offset))
-                    {
-                            $inicio = strpos($source, "\n\r", $inicio);
-                            $fim = strpos($source, '--', $inicio);
-                            if(!$fim)
-                                    $fim = strpos($source,"\n\r", $inicio);
-                            $length = $fim-$inicio;
-                            $parte = substr( $source,$inicio,$length-1);
-                            $parte = str_replace(" ", "+", $parte);
-                            $source = substr_replace($source, $parte, $inicio, $length-1);
-                    }
-                    if($offset > $inicio)
-                    $offset=FALSE;
-                    else
-                    $offset = $inicio;
+                    $inicio = strpos($source, "\n\r", $inicio);
+                    $fim = strpos($source, '--', $inicio);
+                    if(!$fim)
+                            $fim = strpos($source,"\n\r", $inicio);
+                    $length = $fim-$inicio;
+                    $parte = substr( $source,$inicio,$length-1);
+                    $parte = str_replace(" ", "+", $parte);
+                    $source = substr_replace($source, $parte, $inicio, $length-1);
             }
-            while($offset);
-            return $source;
+            if($offset > $inicio)
+            $offset=FALSE;
+            else
+            $offset = $inicio;
+        }
+        while($offset);
+        return $source;
     }
 
-//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Recebe os fontes dos emails a serem desarquivados, separa e envia cada um para função insert_mail.
+	//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Recebe os fontes dos emails a serem desarquivados, separa e envia cada um para função insert_mail.
 
     function unarchive_mail($params)
-    {		
-        $dest_folder = $params['folder'];
+    {	
+        $dest_folder = urldecode($params['folder']);
         $sources = explode("#@#@#@",$params['source']);
-        //Add user timeszone
         $timestamps = explode("#@#@#@",$params['timestamp']);
-
-
         $flags = explode("#@#@#@",$params['flags']);
-		
-		foreach($sources as $index=>$src) {
-			if($src!=""){
-		$source = $this->treat_base64_from_post($src);
-		$timestampsactual = $timestamps[$index] + $this->functions->CalculateDateOffset(); 
- 		        $insert = $this->insert_email($source, mb_convert_encoding( $dest_folder,"ISO-8859-1","UTF-8"), $timestampsactual,$flags[$index]); 
+        $ids = explode("#@#@#@",$params['id']);
+        $return = array();
+        $archived = array();
+        $error = array();
+
+        foreach($sources as $index=>$src)
+        {
+            if($src!="")
+            {
+                //If it is a MailArchiver incomming data
+                if($params['madata'])
+                    $sourcedec = utf8_decode($src);
+                //Default data
+                else
+                    $sourcedec = $src;
+
+		 		$source = $this->treat_base64_from_post($sourcedec);
+
+				$insert = $this->insert_email($source,$dest_folder,$timestamps[$index],$flags[$index]);
+
+                if($insert['error'])
+                {
+                    $error[] = $ids[$index];
+                }
+                else 
+                {
+                    $archived[] = $ids[$index];
+                }
+            }else{
+                $error[] = $ids[$index];
             }
-	}
-        return $insert;
+		}
+        
+        if (!empty($error))
+        {
+            $return['error'] = $error;
+        }
+        if (!empty($archived))
+        {
+            $return['archived'] = $archived;
+        }
+        
+        return $return;
     }
 
@@ -5484,4 +5535,45 @@
 	}
 
+	//MailArchiver -> get offsettogmt as a global javascript variable, invoked at "main.js", init()
+    function get_offset_gmt(){
+        return($this->functions->CalculateDateOffset());
+    }
+
+    //MailArchiver -> get message flags only, invoked at archive operation
+    function get_msg_flags($args){  
+        $msg_folder = $args['folder'];
+        $msg_n = $args['msg_number'];
+        $arr_msg = explode(",", $msg_n);
+       
+        for($i=0; $i<count($arr_msg); $i++){
+                        
+            if(!$this->mbox || !is_resource($this->mbox))
+                $this->mbox = $this->open_mbox($msg_folder);
+        
+            if(!is_resource($this->mbox))
+                return(false);
+                       
+            $msgno_imap = imap_msgno($this->mbox, $msg_n);          
+        	$header = @imap_headerinfo($this->mbox, $msgno_imap, 80, 255);
+                
+            if (!is_object($header))
+                return false;
+
+            $taglist[$i]["msgid"] = $msg_n;
+            $taglist[$i]["unseen"] = $header->Unseen;
+            $taglist[$i]["recent"] = $header->Recent;
+            $taglist[$i]["flagged"] = $header->Flagged;
+            $taglist[$i]["draft"] = $header->Draft;
+            $taglist[$i]["answered"] = $header->Answered;
+            $taglist[$i]["deleted"] = $header->Deleted;
+        
+            if($header->Answered =='A' && $header->Draft == 'X')
+                $taglist[$i]['forwarded'] = 'F';
+            else
+                $taglist[$i]['forwarded'] = ' ';
+        }
+
+		return $taglist;        
+    }    
 }
 ?>
Index: trunk/expressoMail1_2/inc/class.user.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.user.inc.php	(revision 5509)
+++ trunk/expressoMail1_2/inc/class.user.inc.php	(revision 7414)
@@ -50,5 +50,28 @@
 			return $_SESSION['phpgw_info']['expressomail']['user']['email'];	
 		}
-		
+
+        //MailArchiver login validate operations
+        function get_mailarchiver_authid(){
+            if((isset($_COOKIE["BALANCEID"])) && ($_COOKIE["BALANCEID"] != null) && ($_COOKIE["BALANCEID"] != " "))
+                $cookie_balancer = $_COOKIE["BALANCEID"];
+            else
+                $cookie_balancer = "";
+            if((isset($_COOKIE["sessionid"])) && ($_COOKIE["sessionid"] != null) && ($_COOKIE["sessionid"] != " "))
+                $cookie_session = $_COOKIE["sessionid"];
+            else
+                $cookie_session = "";
+            if(isset($_SESSION['phpgw_info']['expressomail']['user']['userid']) && ($_SESSION['phpgw_info']['expressomail']['user']['userid'] != null) && ($_SESSION['phpgw_info']['expressomail']['user']['userid'] != " "))
+                $cookie_user = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+            else
+                $cookie_user = "";
+            
+            if(isset($_SESSION['phpgw_info']['expressomail']['user']['passwd']) && ($_SESSION['phpgw_info']['expressomail']['user']['passwd'] != null) && ($_SESSION['phpgw_info']['expressomail']['user']['passwd'] != " "))
+                $cookie_pass = $_SESSION['phpgw_info']['expressomail']['user']['passwd'];
+            else
+                $cookie_pass = "";
+            
+            return(array($cookie_balancer, $cookie_session, $cookie_user, $cookie_pass));                    
+        }
+
 	}
 ?>
Index: trunk/expressoMail1_2/inc/class.exporteml.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.exporteml.inc.php	(revision 7040)
+++ trunk/expressoMail1_2/inc/class.exporteml.inc.php	(revision 7414)
@@ -56,4 +56,19 @@
 	// Rommel Cysne (rommel.cysne@serpro.gov.br)
 	// em 17/12/2008.
+
+    function createFileEml_by_localFolder($sEMLData, $tempDir, $file){ 
+
+        $file = "{$file}.eml";
+
+        $f = fopen($tempDir.'/'.$file,"w");
+        if(!$f)
+            return False;
+
+        fputs($f,$sEMLData);
+        fclose($f);
+        
+        return $file;
+    }
+
 	function createFileEml($sEMLData, $tempDir, $id, $subject=false, $i=false)
     {
@@ -101,7 +116,7 @@
     } 
 
-	function createFileZip($files, $tempDir){		
+	function createFileZip($files, $tempDir){	
+
 		$tmp_zip_filename = "email_".$_SESSION[ 'phpgw_session' ][ 'session_id' ].".zip";
-		
                 if (!empty($files))
                 {
@@ -119,6 +134,9 @@
                     }
                 }
-                
-		$command = "cd " . escapeshellarg($tempDir) . " && nice zip -m9 " . escapeshellarg($tmp_zip_filename) . " " .  $files;
+
+
+$command = "cd " . escapeshellarg($tempDir) . " && nice zip -m9 " . escapeshellarg($tmp_zip_filename) . " " .  $files;
+
+
 		if(!exec($command)) {
 			$command = "cd " .  escapeshellarg($tempDir) . " && rm ".$files." ". escapeshellarg($tmp_zip_filename);
@@ -126,11 +144,63 @@
 			return null;
 		}
-		
+
 		return $tmp_zip_filename;
 				
 	}
 
-	function export_all($params){
-		
+function export_all_byLocalFolder($params){
+        $error = false;
+
+        if(empty($params['messages'])){
+            $file["empty_folder"] = true;
+        } else {
+            foreach($params['messages'] as $eachMsg){
+               $header = "";
+               $body = "";
+               $tempDir = $this->tempDir;
+
+               $this->get_header_byLocalFolder($eachMsg, $header);
+               $this->get_body_byLocalFolder($eachMsg, $body);
+               $sEMLData    = $this->parseEml($header, $body);
+               $fileName   = $this->createFileEml_by_localFolder($sEMLData, $tempDir,$eachMsg['msg_number']);
+
+               if(!$fileName){
+                   $error = true;
+                   break;
+               } else 
+                   $fileNames .= "\"".$fileName."\" ";
+            }
+
+            $nameFileZip = 'False';         
+            if($fileNames && !$error) {         
+                $nameFileZip = $this->createFileZip($fileNames, $tempDir);
+                ($nameFileZip) ? ($file = $tempDir.'/'.$nameFileZip) : ($file = false);
+            } else 
+                $file = false;
+        }
+       
+       return $file;
+
+}
+
+function get_header_byLocalFolder($eachMsg, &$header){
+    $header = <<<header
+        MIME-Version: 1.0
+        Content-Type: text/html; charset=ISO-8859-1
+        Content-Transfer-Encoding: quoted-printable
+        From: "{$eachMsg['from']['name']}" <{$eachMsg['from']['email']}>
+        To: {$eachMsg['to']['email']}
+        Subject: {$eachMsg['subject']}
+        Message-Id: {$eachMsg['msg_number']}
+        Date: {$eachMsg['date']}
+header;
+}
+
+function get_body_byLocalFolder($eachMsg, &$body){
+    $body = $eachMsg['msg_sample']['body'];
+}
+
+function export_all($params){
+
 		$this->folder = $params['folder'];
 		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","UTF-8");
@@ -140,8 +210,11 @@
 		
 		$msgs = imap_search($this->mbox_stream,"ALL",SE_UID);
+
 		if($msgs){
 			foreach($msgs as $nMsgs){
-				$header	 	= $this-> getHeader($nMsgs);									
-				$body		= $this-> getBody($nMsgs);			
+
+				$header	 	= $this-> getHeader($nMsgs);								 
+				$body		= $this-> getBody($nMsgs);		
+
 				$sEMLData 	= $this -> parseEml($header, $body);
 				$fileName 	= $this -> CreateFileEml($sEMLData, $tempDir,$nMsgs);
@@ -478,4 +551,34 @@
 	}
 
+	//MAILARCHIVER 
+	function js_source_var($params) {
+		$this-> folder = $params['folder'];
+		if(!$this->folder){
+		   $aux = explode(';',$params['msgs_to_export']);
+		   $this->folder = $aux[0];
+		   $id_number = $aux[1];
+		}
+		else{
+			$id_number = $params['msgs_to_export'];
+		}
+		$this->folder = mb_convert_encoding($this->folder, "UTF7-IMAP","ISO_8859-1");
+		$tempDir = ini_get("session.save_path");
+
+		$this->connectImap();
+		$header	 	= $this-> getHeader($id_number);
+		$body		= $this-> getBody($id_number);
+		
+		if(!strpos($header,"Date: ")){
+			$header = "Date: " . $this->getHeaderInfo($id_number)->Date . "\r\n" .$header ;
+		}
+
+		imap_close($this->mbox_stream);
+
+		$input = $header . "\r\n\r\n" . $body;
+		$input = preg_replace('/\x1d/', '', $input); //remove special char control detected (hex 1D)
+		
+		return($input);
+	} 
+	
     function export_msg_data($id_msg,$folder) {
 		$this->folder = $folder;
@@ -752,4 +855,9 @@
 		return imap_fetchheader($this->mbox_stream, $msg_number, FT_UID);
 	}
+
+	function getHeaderInfo($msg_number){			
+		$header = imap_headerinfo($this->mbox_stream, imap_msgno($this->mbox_stream, $msg_number), 80, 255);
+		return $header;
+	}
 	
 	function getBody($msg_number){
