Index: /trunk/library/ckeditor/plugins/expresso/plugin.js
===================================================================
--- /trunk/library/ckeditor/plugins/expresso/plugin.js	(revision 5081)
+++ /trunk/library/ckeditor/plugins/expresso/plugin.js	(revision 5604)
@@ -9,5 +9,5 @@
             {
                 label: 'Adicionar Imagem',
-                command: 'expAddImageCMD',
+                command: 'imgDialog',
                 icon: CKEDITOR.plugins.getPath('expresso') + 'img/Image.gif'
             });
@@ -43,9 +43,144 @@
         });
         
+        
+        editor.addCommand( 'imgDialog',new CKEDITOR.dialogCommand( 'imgDialog' ) );
+
+		if ( editor.contextMenu )
+		{
+			editor.addMenuGroup( 'mygroup', 10 );
+			editor.addMenuItem( 'My Dialog',
+			{
+				label : 'Open dialog',
+				command : 'imgDialog',
+				group : 'mygroup'
+			});
+			editor.contextMenu.addListener( function( element )
+			{
+ 				return {'My Dialog' : CKEDITOR.TRISTATE_OFF};
+			});
+		}
+                
+		CKEDITOR.dialog.add( 'imgDialog', function( api )
+		{
+                        var ID = currentTab;
+			// CKEDITOR.dialog.definition
+			var dialogDefinition =
+			{
+				
+                                title : 'Inserir Imagem',
+				minWidth : 400,
+				minHeight : 70,
+				contents : [
+					{
+						id : 'tab1',
+						label : 'Label',
+						title : 'Title',
+						expand : true,
+						padding : 0,
+						elements :
+						[
+							{
+								type : 'html',
+								html :  '<form id="fileupload_img'+ID+'" class="fileupload" action="mailAttachment:img" method="POST">    <input type="file" name="files[]" multiple="" onclick="bindFileUpload();" style="margin-left:10px"></form>' 
+							}
+						]
+					}
+				],
+				buttons : [ CKEDITOR.dialog.cancelButton]
+				
+			};
+                        	
+			return dialogDefinition;
+		} );
+	
          
-        var cmd = editor.addCommand('expAddImageCMD',  { exec: showexpIncImageDialog });
+
     }
 });
-function showexpIncImageDialog(e) {
-   RichTextEditor.createImage();
+function bindFileUpload(e) {
+        var ID = currentTab;
+        var newImageId = new Date().getTime();
+        var fileUploadIMG = $('#fileupload_img'+ID);
+        var fileUploadMSG = $('#fileupload_msg'+ID);
+        var maxAttachmentSise = (preferences.max_attachment_size !== "" && preferences.max_attachment_size != 0) ? (parseInt(preferences.max_attachment_size.replace('M', '')) * 1048576 ) : false;
+	fileUploadIMG.fileupload({
+		sequentialUploads: true,
+		add: function (e, data) {
+     
+			if(!maxAttachmentSise || data.files[0].size < maxAttachmentSise) {
+				setTimeout(function() {
+                                        $('#attDisposition'+ID).val('embedded');
+					data.submit();
+				}, 5000);
+			}
+                        
+		},
+		change: function (e, data) {
+			$.each(data.files, function (index, file) {	
+				var attach = {};
+				attach.fullFileName = file.name;
+				attach.fileName = file.name;
+				if(file.name.length > 10)
+					attach.fileName = file.name.substr(0, 18) + "..." + file.name.substr(file.name.length-9, file.name.length);
+				attach.fileSize = formatBytes(file.size);
+				if(maxAttachmentSise && file.size > maxAttachmentSise)
+					attach.error = 'Tamanho de arquivo nao permitido!!'
+								
+				fileUploadMSG.find('.attachments-list').append(DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist.ejs", {file : attach}));
+
+				if(!maxAttachmentSise || file.size < maxAttachmentSise){
+					fileUploadMSG.find(' .fileinput-button.new').append(data.fileInput[0]).removeClass('new');
+					fileUploadMSG.find(' .attachments-list').find('[type=file]').addClass('hidden');
+					
+				}else
+					fileUploadMSG.find(' .fileinput-button.new').removeClass('new');
+				
+				
+				fileUploadMSG.find(' .attachments-list').find('.button.close').button({
+					icons: {
+						primary: "ui-icon-close"
+					},
+					text: false
+				}).click(function(){
+					var idAttach = $(this).parent().find('input[name="fileId[]"]').val();
+			
+                                        var content_body = RichTextEditor.getData('body_'+ID);
+                                        var imagens = content_body.match(/<img[^>]*>/g);
+       
+                                        if(imagens != null)
+                                            for (var x = 0; x < imagens.length; x++)
+                                                if(imagens[x].indexOf('src="../prototype/getArchive.php?mailAttachment='+idAttach+'"') !== -1)
+                                                        content_body = content_body.replace(imagens[x],'');
+         
+                                        RichTextEditor.setData('body_'+ID,content_body);   
+                                       	
+                                        $('.attachments-list').find('input[value="'+idAttach+'"]').remove();
+                                        delAttachment(ID, idAttach);
+					$(this).parent().remove();
+				});
+                                
+                                CKEDITOR.instances['body_'+ID].insertHtml('<img id="'+newImageId+'" src=""/>');
+
+		});
+                
+                    CKEDITOR.dialog.getCurrent().hide();
+                },
+		done: function(e, data){
+			if(!!data.result && data.result != "[]"){
+				var newAttach = jQuery.parseJSON(data.result);
+				fileUploadMSG.find('.in-progress:first').parents('p').append('<input type="hidden" name="fileId[]" value="'+newAttach['mailAttachment'][0][0].id+'"/>');
+                                addAttachment(ID,newAttach['mailAttachment'][0][0].id);
+                                var content_body  = RichTextEditor.getData('body_'+ID);
+                                var rex = new RegExp('<img id="'+newImageId+'" src="" [^\/>]*\/>', 'i'); 
+                                var newImg = '<img src="../prototype/getArchive.php?mailAttachment='+newAttach['mailAttachment'][0][0].id+'" />'; 
+                                content_body = content_body.replace(rex,newImg); 
+                                RichTextEditor.setData('body_'+ID,content_body); 
+      
+			}else {
+				fileUploadMSG.find(' .progress.on-complete:first').removeClass('on-complete').parents('p').find('.status-upload').addClass('ui-icon ui-icon-cancel');
+			}
+			fileUploadMSG.find('.in-progress:first').remove();
+                    
+		}
+	});
 }
Index: /trunk/library/PEAR/PEAR.php
===================================================================
--- /trunk/library/PEAR/PEAR.php	(revision 5146)
+++ /trunk/library/PEAR/PEAR.php	(revision 5604)
@@ -728,5 +728,5 @@
 
 if (PEAR_ZE2) {
-    include_once 'PEAR5.php';
+    include_once dirname(__FILE__).'/PEAR5.php';
 }
 
Index: /trunk/library/mime/mime.php
===================================================================
--- /trunk/library/mime/mime.php	(revision 5316)
+++ /trunk/library/mime/mime.php	(revision 5604)
@@ -873,13 +873,9 @@
                 $rep[] = '\1\2=\3cid:' . $value['cid'] .'\3';
                 $rep[] = 'url(\1cid:' . $value['cid'] . '\1)';
-
+                             
                 $this->_htmlbody = preg_replace($regex, $rep, $this->_htmlbody);
                 $this->_html_images[$key]['name']
                     = $this->_basename($this->_html_images[$key]['name']);
-              
-                //Alteração para o Expresso.
-                //Ver https://dev.prognus.com.br/expresso/ticket/1256
-                $this->_htmlbody = str_replace("src=\"cid:".substr($value['cid'], 0, strpos($value['cid'], '@'))."\"", "src=\"cid:".$value['cid']."\"", $this->_htmlbody);
-
+                            
             }
         }
Index: /trunk/prototype/services/ImapServiceAdapter.php
===================================================================
--- /trunk/prototype/services/ImapServiceAdapter.php	(revision 5586)
+++ /trunk/prototype/services/ImapServiceAdapter.php	(revision 5604)
@@ -333,5 +333,5 @@
 
     public function create( $URI, $data)
-    {
+    {               
 		switch( $URI['concept'] )
 		{
@@ -364,4 +364,90 @@
 				}
 				return array ();
+			}
+                        case 'message':
+			{
+				$GLOBALS['phpgw_info']['flags'] = array( 'noheader' => true, 'nonavbar' => true,'currentapp' => 'expressoMail1_2','enable_nextmatchs_class' => True );
+                                $return = array();
+
+                                require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
+                                $mailService = ServiceLocator::getService('mail');
+
+                                $msg_uid = $data['msg_id'];
+                                $body = $data['body'];
+                                $body = str_replace("%nbsp;","&nbsp;",$body);
+                                $body = preg_replace("/\n/"," ",$body);
+                                $body = preg_replace("/\r/","" ,$body);
+                                $body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );					
+
+                                $folder = mb_convert_encoding($data['folder'], "UTF7-IMAP","ISO-8859-1, UTF-8");
+                                $folder = @eregi_replace("INBOX[/.]", "INBOX".$this->imap_delimiter, $folder);
+
+                                $mailService->addTo($data['input_to']);
+                                $mailService->addCc( $data['input_cc']);
+                                $mailService->addBcc($data['input_cco']);
+                                $mailService->setSubject($data['input_subject']);
+
+                                if(isset($data['input_important_message']))
+                                        $mailService->addHeaderField('Importance','High');
+
+                                if(isset($data['input_return_receipt']))
+                                        $mailService->addHeaderField('Disposition-Notification-To', Config::me('mail'));
+
+                                $isHTML = ( ( array_key_exists( 'type', $data ) && in_array( strtolower( $data[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $data[ 'type' ] ) != 'plain' : true );
+
+                                if (!$body) $body = ' ';
+                                
+
+                                $mbox_stream = $this->open_mbox($folder);
+
+                                $attachment = json_decode($data['attachments'],TRUE);
+                                
+
+                                foreach ($attachment as &$value) 
+                                {
+
+                                    if((int)$value > 0) //BD attachment
+                                    {
+                                         $att = Controller::read(array('id'=> $value , 'concept' => 'mailAttachment'));
+                                         
+                                         if($att['disposition'] == 'embedded')
+                                         {
+                                             $body = str_replace('"../prototype/getArchive.php?mailAttachment='.$att['id'].'"', $att['name'], $body);
+                                             $mailService->addStringImage(base64_decode($att['source']), $att['type'], $att['name']);
+                                         }
+                                         else
+                                             $mailService->addStringAttachment(base64_decode($att['source']), $att['name'], $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] :'attachment' );
+                                         
+                                         unset($att);
+                                    }
+                                    else //message attachment
+                                    {
+                                        $value = json_decode($value, true);
+                                        $sub =  $value['name'] ? $value['name'].'.eml' :'no title.eml';
+                                        $mbox_stream = $this->open_mbox($value['folder']);
+                                        $rawmsg = $this->getRawHeader($value['uid']) . "\r\n\r\n" . $this->getRawBody($value['uid']);
+                                        $mailService->addStringAttachment($rawmsg, $sub, 'message/rfc822', '7bit', 'attachment' );
+                                        unset($rawmsg);
+                                    }
+
+                                }
+                                
+                                if($isHTML) $mailService->setBodyHtml($body); else $mailService->setBodyText($body);
+                                                         
+                                if(imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft"))
+                                {
+                                    $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
+                                    $return['id'] = $status->uidnext - 1;
+                                        
+                                    if($data['uidsSave'] )
+                                        $this->delete_msgs(array('folder'=> $folder , 'msgs_number' => $data['uidsSave']));
+                       
+                                }
+                 
+                                if($mbox_stream) imap_close($mbox_stream);
+                                
+                                
+                                
+                                return $return;
 			}
 		}
Index: /trunk/prototype/config/CalDAV.srv
===================================================================
--- /trunk/prototype/config/CalDAV.srv	(revision 5399)
+++ /trunk/prototype/config/CalDAV.srv	(revision 5604)
Index: /trunk/prototype/config/mailAttachment.ini
===================================================================
--- /trunk/prototype/config/mailAttachment.ini	(revision 5604)
+++ /trunk/prototype/config/mailAttachment.ini	(revision 5604)
@@ -0,0 +1,15 @@
+service = PostgreSQL
+PostgreSQL.concept = mail_attachment
+
+[before.create]
+encodeCreateAttachment = modules/mail/interceptors/Attachments.php
+
+[PostgreSQL.mapping]
+id = "id"
+source = "source"
+type = "type"
+name = "name"
+size = "size"
+owner = "owner"
+disposition = "disposition"
+dtstamp = "dtstamp"
Index: /trunk/prototype/getArchive.php
===================================================================
--- /trunk/prototype/getArchive.php	(revision 5514)
+++ /trunk/prototype/getArchive.php	(revision 5604)
@@ -7,5 +7,5 @@
 
 	foreach($data as $concept => $value){
-	
+                              
 		$arquive = Controller::find( array( 'concept' => $concept ) , false ,array( 'filter' => array('=', 'id' , $data[$concept]) )); 
 				
Index: /trunk/prototype/modules/mail/interceptors/Attachments.php
===================================================================
--- /trunk/prototype/modules/mail/interceptors/Attachments.php	(revision 5604)
+++ /trunk/prototype/modules/mail/interceptors/Attachments.php	(revision 5604)
@@ -0,0 +1,23 @@
+<?php
+
+class Attachments {	
+	
+	public function encodeCreateAttachment( &$uri , &$params , &$criteria , $original ){
+                        
+		if(!isset($params['source'])) return false;
+		
+		if(isset($_FILES[$params['source']]))
+			if(isset($params['id']))
+				$params =  array_merge($_FILES[$params['source']], array('id' => $params['id']));
+			else
+				$params =  $_FILES[$params['source']];
+				
+                  $params['owner'] = Config::me('uidNumber'); 
+                                   
+                  $params['disposition'] = $original['properties']['disposition'];
+                  $params['dtstamp'] = time();
+	}
+  
+}
+
+?>
Index: /trunk/prototype/modules/mail/templates/attachment.ejs
===================================================================
--- /trunk/prototype/modules/mail/templates/attachment.ejs	(revision 5604)
+++ /trunk/prototype/modules/mail/templates/attachment.ejs	(revision 5604)
@@ -0,0 +1,19 @@
+<form id="fileupload_msg<%=data.ID%>" class="fileupload" action="mailAttachment:detail" method="POST">
+  <div class="row fileupload-buttonbar">
+    <div class="button-files-upload">
+      <span class="button small btn-success fileinput-button ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button">
+        <span class="ui-button-text">
+          <span><i class="icon-plus icon-white"></i>Anexar arquivos</span>
+          <input type="file" name="files[]" multiple="">
+        </span>
+      </span>
+    </div>	
+
+     <span tabindex="-1" class="message-attach-link button small ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button"><span class="icon-plus ui-button-text">Anexar mensagens</span></span>
+       <div id="fileupload-progress"></div>
+         <div class="files-list">
+            <ul class="attachments-list"></ul>
+         </div>
+       </div>
+        <br>
+</form>
Index: /trunk/prototype/modules/mail/templates/attachment_add_itemlist.ejs
===================================================================
--- /trunk/prototype/modules/mail/templates/attachment_add_itemlist.ejs	(revision 5604)
+++ /trunk/prototype/modules/mail/templates/attachment_add_itemlist.ejs	(revision 5604)
@@ -0,0 +1,16 @@
+
+	<p class="input-group archive-info" style="margin: 0px 0 !important;">		
+		<a id="<%=data.file.id%>" class="download file"><span title="<%=data.file.fullFileName%>" class="archive-attach name"><%=data.file.fileName%></span></a>
+		<span class="archive-attach size"><%=data.file.fileSize%></span>
+		<button type="button" class="button close tiny upload delete-upload" title="Deletar">Deletar</button>
+		<span class="status-upload"></span>
+		<%if(data.file.error){%>
+			<span class="archive-error error"><%=data.file.error%></span>
+		<%}if(!data.file.error){%>
+			<span style="width: 110px; height: 14px; overflow:hidden">
+				<span class="in-progress"> <img src="../prototype/modules/mail/img/loader.gif" /></span>
+			</span>
+		<%}%>
+		<label class="fileinput-button new"></label>
+		
+    </p>
Index: /trunk/prototype/api/datalayer.js
===================================================================
--- /trunk/prototype/api/datalayer.js	(revision 5601)
+++ /trunk/prototype/api/datalayer.js	(revision 5604)
@@ -19,5 +19,7 @@
 
 	  if( isIframe.test( options.dataType ) || options.data instanceof FormData )
-	  {    
+	  {
+	      options.url = options.fileInput.parents( 'form' ).attr( 'action' );
+	    
 	      res = internalUrl.exec( options.url );
 
Index: /trunk/expressoMail1_2/index.php
===================================================================
--- /trunk/expressoMail1_2/index.php	(revision 5539)
+++ /trunk/expressoMail1_2/index.php	(revision 5604)
@@ -12,5 +12,5 @@
 	$GLOBALS['phpgw_info']['flags'] = array(
 		'noheader' => False,
-		'nonavbar' => False,
+		'nonavbar' => false,
 		'currentapp' => 'expressoMail1_2',
 		'enable_nextmatchs_class' => True
@@ -391,5 +391,7 @@
 <link rel='stylesheet' type='text/css' href='../prototype/modules/calendar/css/layout.css' />
 <link rel='stylesheet' type='text/css' href='../prototype/modules/calendar/css/style.css' />
-
+<link rel='stylesheet' type='text/css' href='../prototype/plugins/fileupload/jquery.fileupload-ui.css' />
+<script src="../prototype/plugins/fileupload/jquery.fileupload.js"></script>
+<script src="../prototype/plugins/fileupload/jquery.iframe-transport.js"></script>
 </body>
 </html>
Index: /trunk/expressoMail1_2/templates/default/expressomail.css
===================================================================
--- /trunk/expressoMail1_2/templates/default/expressomail.css	(revision 5569)
+++ /trunk/expressoMail1_2/templates/default/expressomail.css	(revision 5604)
@@ -136,2 +136,26 @@
 .context-menu-item.icon-empty-trash { background-image: url(images/menu/trash.png); }
 .context-menu-item.icon-queue { background-image: url(images/menu/queue.png); }
+
+form.fileupload { margin: 14px 0 0 -13px; float: left; margin-bottom: -20px; }
+form.fileupload .files-list { margin-left: 5px;}
+ul.attachments-list { padding: 0; }
+.button-files-upload { float:left; }
+
+form.fileupload .ui-button .ui-button-text { line-height: 2; }
+form.fileupload .ui-button { margin-left: 5px; }
+
+.button.add.button-add-attachment{margin: -9px 0 0 8px;}
+.button.upload{margin-bottom: 4px;}
+div.fileupload-buttonbar{padding: 0.2em 0.5em }
+.archive-error{color: #F00;}
+
+.progress.in-progress{width: 100px; height: 12px;}
+
+.row.fileupload-buttonbar{margin-top: -14px; padding: 0.2em 0.7em;}
+
+.archive-attach.name{width: 200px;}
+.archive-attach.name label{display: block; position: absolute; left: 136px; top: 194px;}
+.size{min-width: 60px; max-width: 60px;}
+
+.message-attach.name{width: 200px;}
+.message-attach.size{margin:0 4px 0 4px;}
Index: /trunk/expressoMail1_2/setup/tables_current.inc.php
===================================================================
--- /trunk/expressoMail1_2/setup/tables_current.inc.php	(revision 5603)
+++ /trunk/expressoMail1_2/setup/tables_current.inc.php	(revision 5604)
@@ -77,5 +77,5 @@
 			'ix' => array(),
 			'uc' => array()
-		)
+		
 	);
 ?>
Index: /trunk/expressoMail1_2/setup/tables_update.inc.php
===================================================================
--- /trunk/expressoMail1_2/setup/tables_update.inc.php	(revision 5557)
+++ /trunk/expressoMail1_2/setup/tables_update.inc.php	(revision 5604)
@@ -206,4 +206,27 @@
 		$GLOBALS['setup_info']['expressoMail1_2']['currentver'] = '2.4.1';
         return $GLOBALS['setup_info']['expressoMail1_2']['currentver'];
-	}	
+	}
+        $test[] = '2.4.1';
+	function expressoMail1_2_upgrade2_4_1() {
+            $oProc = $GLOBALS['phpgw_setup']->oProc;            
+            $oProc->CreateTable('mail_attachment',array(
+			'fd' => array(
+				'id' => array('type' => 'auto','nullable' => False),
+				'source' => array('type' => 'blob','nullable' => False),
+				'type' => array('type' => 'varchar','precision' => '50','nullable' => False),
+				'name' => array('type' => 'varchar','precision' => '255','nullable' => False),
+                                'disposition' => array('type' => 'varchar','precision' => '20','nullable' => true),
+				'size' => array('type' => 'int','precision' => '16','nullable' => False),
+                                'dtstamp' => array('type' => 'int','precision' => '16','nullable' => False),
+				'owner' => array('type' => 'int', 'precision' => '8','nullable' => True)
+			),
+			'pk' => array('id'),
+			'fk' => array(),
+			'ix' => array(),
+			'uc' => array()
+		)
+			);						
+		$GLOBALS['setup_info']['expressoMail1_2']['currentver'] = '2.4.2';
+        return $GLOBALS['setup_info']['expressoMail1_2']['currentver'];
+	}
 ?>
Index: /trunk/expressoMail1_2/setup/setup.inc.php
===================================================================
--- /trunk/expressoMail1_2/setup/setup.inc.php	(revision 5547)
+++ /trunk/expressoMail1_2/setup/setup.inc.php	(revision 5604)
@@ -12,10 +12,11 @@
 	$setup_info['expressoMail1_2']['name']      	= 'expressoMail1_2';
 	$setup_info['expressoMail1_2']['title']     	= 'Expresso Mail';
-	$setup_info['expressoMail1_2']['version']   	= '2.4.1';
+	$setup_info['expressoMail1_2']['version']   	= '2.4.2';
 	$setup_info['expressoMail1_2']['app_order'] 	= 2;
 	$setup_info['expressoMail1_2']['tables'][]		= 'phpgw_expressomail_contacts';
     $setup_info['expressoMail1_2']['tables'][]		= 'phpgw_certificados';
 	
-	$setup_info['expressoMail1_2']['tables'][]		= 'expressomail_label';
+	$setup_info['expressoMail1_2']['tables'][]		= 'mail_attachment';
+        $setup_info['expressoMail1_2']['tables'][]		= 'expressomail_label';
 	$setup_info['expressoMail1_2']['tables'][]		= 'expressomail_followupflag';
 	$setup_info['expressoMail1_2']['tables'][]		= 'expressomail_message_followupflag';
Index: /trunk/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- /trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 5548)
+++ /trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 5604)
@@ -2531,717 +2531,500 @@
 	}
 	
-	function send_mail($params)
-	{
-		require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
-		$mailService = ServiceLocator::getService('mail');
-
-		include_once("class.db_functions.inc.php");
-		$db = new db_functions();
-		$fromaddress = $params['input_from'] ? explode(';',$params['input_from']) : "";
-		$message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false; 
-		
-		##
-		# @AUTHOR Rodrigo Souza dos Santos
-		# @DATE 2008/09/17$fileName
-		# @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 = $db->getAddrs(explode(',',$params['input_to']));//implode(',',);
-		$ccaddress = $db->getAddrs(explode(',',$params['input_cc']));//implode(',',);
-		$ccoaddress = $db->getAddrs(explode(',',$params['input_cco']));//implode(',',); 
-
-		if($toaddress["False"] || $ccaddress["False"] || $ccoaddress["False"]){
-			return $this->parse_error("Invalid Mail:", ($toaddress["False"] ? $toaddress["False"] : ($ccaddress["False"] ? $ccaddress["False"] : $ccoaddress["False"])));
-		}
-		
-		$toaddress = implode(',', $toaddress);
-		$ccaddress = implode(',', $ccaddress);
-		$ccoaddress = implode(',', $ccoaddress);
-		
-		if($toaddress == "" && $ccaddress == "" && $ccoaddress == ""){
-			return $this->parse_error("Invalid Mail:", ($params['input_to'] ? $params['input_to'] :($params['input_cc'] ? $params['input_cc'] : $params['input_cco'])) );
-		}
-
-		$toaddress  = preg_replace('/<\s+/', '<', $toaddress);			
-		$toaddress  = preg_replace('/\s+>/', '>', $toaddress);
-			
-		$ccaddress  = preg_replace('/<\s+/', '<', $ccaddress);
-		$ccaddress  = preg_replace('/\s+>/', '>', $ccaddress);
-		
-		$ccoaddress = preg_replace('/<\s+/', '<', $ccoaddress);
-		$ccoaddress = preg_replace('/\s+>/', '>', $ccoaddress);
-		
-		$replytoaddress = $params['input_replyto'];
-		$subject = $params['input_subject'];
-		$msg_uid = $params['msg_id'];
-		$return_receipt = $params['input_return_receipt'];
-		$is_important = $params['input_important_message'];
-        $encrypt = $params['input_return_cripto'];
-		$signed = $params['input_return_digital'];
-
-		$message_attachments = $params['message_attachments'];
-                 
-                if(substr($params['input_to'],-1) == ',')
-                    $params['input_to'] = substr($params['input_to'],0,-1);
-
-                if(substr($params['input_cc'],-1) == ',')
-                    $params['input_cc'] = substr($params['input_cc'],0,-1);
-
-                if(substr($params['input_cco'],-1) == ',')
-                    $params['input_cco'] = substr($params['input_cco'],0,-1);
-
-                // Valida numero Maximo de Destinatarios 
-                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'] > 0) 
-                { 
-                    $sendersNumber = count(explode(',',$params['input_to'])); 
-
-                    if($params['input_cc']) 
-                        $sendersNumber +=  count(explode(',',$params['input_cc'])); 
-                    if($params['input_cco']) 
-                        $sendersNumber +=  count(explode(',',$params['input_cco'])); 
-
-                    $userMaxmimumSenders = $db->getMaximumRecipientsUser($this->username); 
-                    if($userMaxmimumSenders) 
-                    { 
-                        if($sendersNumber > $userMaxmimumSenders) 
-                            return $this->functions->getLang('Number of recipients greater than allowed'); 
-                    } 
-                    else 
-                    { 
-                        $ldap = new ldap_functions(); 
-                        $groupsToUser = $ldap->get_user_groups($this->username); 
-
-                        $groupMaxmimumSenders = $db->getMaximumRecipientsGroup($groupsToUser); 
-
-                        if($groupMaxmimumSenders > 0) 
-                        { 
-                            if($sendersNumber > $groupMaxmimumSenders) 
-                                return $this->functions->getLang('Number of recipients greater than allowed'); 
-                        } 
-                        else 
-                        { 
-                             if($sendersNumber > $_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients']) 
-                             return $this->functions->getLang('Number of recipients greater than allowed'); 
-                        } 
-                    } 
-
-                } 
-                //Fim Valida numero maximo de destinatarios 
-                
-                
-                //Valida envio de email para shared accounts
-                if($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoMail_block_institutional_comunication'] == 'true')
-                {
+	function send_mail($params) {               
+
+            require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
+            require_once dirname(__FILE__) . '/../../prototype/api/controller.php';
+            $mailService = ServiceLocator::getService('mail');
+
+            include_once("class.db_functions.inc.php");
+            $db = new db_functions();
+            $fromaddress = $params['input_from'] ? explode(';', $params['input_from']) : "";
+            $message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false;
+
+            ##
+            # @AUTHOR Rodrigo Souza dos Santos
+            # @DATE 2008/09/17$fileName
+            # @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 = $db->getAddrs(explode(',', $params['input_to'])); //implode(',',);
+            $ccaddress = $db->getAddrs(explode(',', $params['input_cc'])); //implode(',',);
+            $ccoaddress = $db->getAddrs(explode(',', $params['input_cco'])); //implode(',',); 
+
+            if ($toaddress["False"] || $ccaddress["False"] || $ccoaddress["False"]) {
+                return $this->parse_error("Invalid Mail:", ($toaddress["False"] ? $toaddress["False"] : ($ccaddress["False"] ? $ccaddress["False"] : $ccoaddress["False"])));
+            }
+
+            $toaddress = implode(',', $toaddress);
+            $ccaddress = implode(',', $ccaddress);
+            $ccoaddress = implode(',', $ccoaddress);
+
+            if ($toaddress == "" && $ccaddress == "" && $ccoaddress == "") {
+                return $this->parse_error("Invalid Mail:", ($params['input_to'] ? $params['input_to'] : ($params['input_cc'] ? $params['input_cc'] : $params['input_cco'])));
+            }
+
+            $toaddress = preg_replace('/<\s+/', '<', $toaddress);
+            $toaddress = preg_replace('/\s+>/', '>', $toaddress);
+
+            $ccaddress = preg_replace('/<\s+/', '<', $ccaddress);
+            $ccaddress = preg_replace('/\s+>/', '>', $ccaddress);
+
+            $ccoaddress = preg_replace('/<\s+/', '<', $ccoaddress);
+            $ccoaddress = preg_replace('/\s+>/', '>', $ccoaddress);
+
+            $replytoaddress = $params['input_replyto'];
+            $subject = $params['input_subject'];
+            $return_receipt = $params['input_return_receipt'];
+            $is_important = $params['input_important_message'];
+            $encrypt = $params['input_return_cripto'];
+            $signed = $params['input_return_digital'];
+
+            $message_attachments = $params['message_attachments'];
+
+            if (substr($params['input_to'], -1) == ',')
+                $params['input_to'] = substr($params['input_to'], 0, -1);
+
+            if (substr($params['input_cc'], -1) == ',')
+                $params['input_cc'] = substr($params['input_cc'], 0, -1);
+
+            if (substr($params['input_cco'], -1) == ',')
+                $params['input_cco'] = substr($params['input_cco'], 0, -1);
+
+            // Valida numero Maximo de Destinatarios 
+            if ($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'] > 0) {
+                $sendersNumber = count(explode(',', $params['input_to']));
+
+                if ($params['input_cc'])
+                    $sendersNumber += count(explode(',', $params['input_cc']));
+                if ($params['input_cco'])
+                    $sendersNumber += count(explode(',', $params['input_cco']));
+
+                $userMaxmimumSenders = $db->getMaximumRecipientsUser($this->username);
+                if ($userMaxmimumSenders) {
+                    if ($sendersNumber > $userMaxmimumSenders)
+                        return $this->functions->getLang('Number of recipients greater than allowed');
+                }
+                else {
                     $ldap = new ldap_functions();
-                    $arrayF = explode(';', $params['input_from']);
+                    $groupsToUser = $ldap->get_user_groups($this->username);
+
+                    $groupMaxmimumSenders = $db->getMaximumRecipientsGroup($groupsToUser);
+
+                    if ($groupMaxmimumSenders > 0) {
+                        if ($sendersNumber > $groupMaxmimumSenders)
+                            return $this->functions->getLang('Number of recipients greater than allowed');
+                    }
+                    else {
+                        if ($sendersNumber > $_SESSION['phpgw_info']['expresso']['expressoMail']['expressoAdmin_maximum_recipients'])
+                            return $this->functions->getLang('Number of recipients greater than allowed');
+                    }
+                }
+            }
+            //Fim Valida numero maximo de destinatarios 
+            //Valida envio de email para shared accounts
+            if ($_SESSION['phpgw_info']['expresso']['expressoMail']['expressoMail_block_institutional_comunication'] == 'true') {
+                $ldap = new ldap_functions();
+                $arrayF = explode(';', $params['input_from']);
+
+                /*
+                 * Verifica se o remetente n?o ? uma conta compartilhada
+                 */
+                if (!$ldap->isSharedAccountByMail($arrayF[1])) {
+                    $groupsToUser = $ldap->get_user_groups($this->username);
+                    $sharedAccounts = $ldap->returnSharedsAccounts($toaddress, $ccaddress, $ccoaddress);
 
                     /*
-                     * Verifica se o remetente n?o ? uma conta compartilhada
+                     * Pega o UID do remetente
                      */
-                    if(!$ldap->isSharedAccountByMail($arrayF[1]))
-                    {
-                        $groupsToUser = $ldap->get_user_groups($this->username);
-                        $sharedAccounts = $ldap->returnSharedsAccounts($toaddress, $ccaddress, $ccoaddress);
-
-                        /*
-                         * Pega o UID do remetente
-                         */
-                        $uidFrom = $ldap->mail2uid($arrayF[1]);
-
-                         /*
-                         * Remove a conta compartilhada caso o uid do remetente exista na conta compartilhada
-                         */
-                        foreach ($sharedAccounts as $key => $value)
-                        {
-                            if($value)
-                                 $acl = $this->getaclfrombox($value);
-
-                             if (array_key_exists($uidFrom, $acl))
-                                 unset($sharedAccounts[$key]);
-
-                        }
-
-                        /*
-                         * Caso ainda exista contas compartilhadas, verifica se existe alguma exce??o para estas contas
-                         */
-                        if(count($sharedAccounts) > 0)
-                          $accountsBlockeds = $db->validadeSharedAccounts($this->username, $groupsToUser, $sharedAccounts);
-
-                        /*
-                         * Retorna as contas compartilhadas bloqueadas
-                         */
-                        if(count($accountsBlockeds) > 0)
-                        {
-                            $return = '';
-
-                            foreach ($accountsBlockeds as $accountBlocked)
-                                $return.= $accountBlocked.', ';
-
-                             $return = substr($return,0,-2);
-
-                             return $this->functions->getLang('you are blocked  from sending mail to the following addresses').': '.$return;
+                    $uidFrom = $ldap->mail2uid($arrayF[1]);
+
+                    /*
+                     * Remove a conta compartilhada caso o uid do remetente exista na conta compartilhada
+                     */
+                    foreach ($sharedAccounts as $key => $value) {
+                        if ($value)
+                            $acl = $this->getaclfrombox($value);
+
+                        if (array_key_exists($uidFrom, $acl))
+                            unset($sharedAccounts[$key]);
+                    }
+
+                    /*
+                     * Caso ainda exista contas compartilhadas, verifica se existe alguma exce??o para estas contas
+                     */
+                    if (count($sharedAccounts) > 0)
+                        $accountsBlockeds = $db->validadeSharedAccounts($this->username, $groupsToUser, $sharedAccounts);
+
+                    /*
+                     * Retorna as contas compartilhadas bloqueadas
+                     */
+                    if (count($accountsBlockeds) > 0) {
+                        $return = '';
+
+                        foreach ($accountsBlockeds as $accountBlocked)
+                            $return.= $accountBlocked . ', ';
+
+                        $return = substr($return, 0, -2);
+
+                        return $this->functions->getLang('you are blocked  from sending mail to the following addresses') . ': ' . $return;
+                    }
+                }
+            }
+            // Fim Valida envio de email para shared accounts
+    //	    TODO - implementar tratamento SMIME no novo serviço de envio de emails e retirar o AND false abaixo
+            if ($params['smime'] AND false) {
+                $body = $params['smime'];
+                $mail->SMIME = true;
+                // A MSG assinada deve ser testada neste ponto.
+                // Testar o certificado e a integridade da msg....
+                include_once(dirname(__FILE__) . "/../../security/classes/CertificadoB.php");
+                $erros_acumulados = '';
+                $certificado = new certificadoB();
+                $validade = $certificado->verificar($body);
+                if (!$validade) {
+                    foreach ($certificado->erros_ssl as $linha_erro) {
+                        $erros_acumulados .= $linha_erro;
+                    }
+                } else {
+                    // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
+                    if ($certificado->apresentado) {
+                        if ($certificado->dados['EXPIRADO'])
+                            $erros_acumulados .='Certificado expirado.';
+                        $this->cpf = isset($GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']) && $GLOBALS['phpgw_info']['server']['certificado_atributo_cpf'] != '' ? $_SESSION['phpgw_info']['expressomail']['user'][$GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']] : $this->username;
+                        if ($certificado->dados['CPF'] != $this->cpf)
+                            $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
+                        if (!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection']))
+                            $erros_acumulados .=' Certificado nao permite assinar mensagens.';
+                    }
+                    else {
+                        $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
+                    }
+                }
+                if (!$erros_acumulados == '') {
+                    return $erros_acumulados;
+                }
+            } else {
+                //Compatibilização com Outlook, ao encaminhar a mensagem
+                $body = mb_ereg_replace('<!--\[', '<!-- [', $params['body']);
+            }
+
+            $attachments = $_FILES;
+            $forwarding_attachments = $params['forwarding_attachments'];
+            $local_attachments = $params['local_attachments'];
+
+            //Test if must be saved in shared folder and change if necessary
+            if ($fromaddress[2] == 'y') {
+                //build shared folder path
+                $newfolder = "user" . $this->imap_delimiter . $fromaddress[3] . $this->imap_delimiter . $this->imap_sentfolder;
+                if ($this->folder_exists($newfolder))
+                    $folder = $newfolder;
+                else
+                    $folder = $params['folder'];
+            } else {
+                $folder = $params['folder'];
+            }
+
+            $folder = mb_convert_encoding($folder, 'UTF7-IMAP', 'ISO_8859-1');
+            $folder = preg_replace('/INBOX[\/.]/i', 'INBOX' . $this->imap_delimiter, $folder);
+            $folder_name = $params['folder_name'];
+
+    //		TODO - tratar assinatura e remover o AND false
+            if ($signed && !$params['smime'] AND false) {
+                $mail->Mailer = "smime";
+                $mail->SignedBody = true;
+            }
+
+
+            if ($fromaddress)
+                $mailService->setFrom('"' . $fromaddress[0] . '" <' . $fromaddress[1] . '>');
+            else
+                $mailService->setFrom('"' . $_SESSION['phpgw_info']['expressomail']['user']['firstname'] . ' ' . $_SESSION['phpgw_info']['expressomail']['user']['lastname'] . '" <' . $_SESSION['phpgw_info']['expressomail']['user']['email'] . '>');
+
+            $bol = $this->add_recipients('to', $toaddress, $mailService);
+            if (!$bol) {
+                return $this->parse_error("Invalid Mail:", $toaddress);
+            }
+            $bol = $this->add_recipients('cc', $ccaddress, $mailService);
+            if (!$bol) {
+                return $this->parse_error("Invalid Mail:", $ccaddress);
+            }
+            $allow = $_SESSION['phpgw_info']['server']['expressomail']['allow_hidden_copy'];
+
+            if ($allow) {
+                //$mailService->addBcc($ccoaddress);
+                $bol = $this->add_recipients('cco', $ccoaddress, $mailService);
+
+                if (!$bol) {
+                    return $this->parse_error("Invalid Mail:", $ccoaddress);
+                }
+            }
+
+            //Implementação para o In-Reply-To e References				
+            $msg_numb = $params['messageNum'];
+            $msg_folder = $params['messageFolder'];
+            $this->mbox = $this->open_mbox($msg_folder);
+
+            $header = $this->get_header($msg_numb);
+            $header_ = imap_fetchheader($this->mbox, $msg_numb, FT_UID);
+            $pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm';
+            if (preg_match($pattern, $header_, $fields)) {
+                if (preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/', $fields[0], $matches)) {
+                    $return['DispositionNotificationTo'] = "<" . $matches[0] . ">";
+                }
+            }
+
+            $message_id = $header->message_id;
+            $references = array();
+            if ($message_id != "") {
+                $mailService->addHeaderField('In-Reply-To', $message_id);
+
+                if (isset($header->references)) {
+                    array_push($references, $header->references);
+                }
+                array_push($references, $message_id);
+                $mailService->addHeaderField('References', $references);
+            }
+
+
+            $mailService->setSubject($subject);
+            $isHTML = ( (array_key_exists('type', $params) && in_array(strtolower($params['type']), array('html', 'plain')) ) ?
+                            strtolower($params['type']) != 'plain' : true );
+
+
+    //	TODO - tratar mensagem criptografada e remover o AND false abaixo
+            if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed) AND false) { // a msg deve ser enviada cifrada...
+                $email = $this->add_recipients_cert($toaddress . ',' . $ccaddress . ',' . $ccoaddress);
+                $email = explode(",", $email);
+                // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
+                // Deve ser verificado um numero limite de destinatarios.
+                // Deve ser verificado se os certificados sao validos.
+                // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
+                // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
+                $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
+                $erros_acumulados = "";
+                $aux_mails = array();
+                $mail_list = array();
+                if (count($email) > $numero_maximo) {
+                    $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
+                    return $erros_acumulados;
+                }
+                // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
+                $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
+                foreach ($email as $item) {
+                    $certificate = $db->get_certificate(strtolower($item));
+                    if (!$certificate) {
+                        $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
+                        return $erros_acumulados;
+                    }
+
+                    if (array_key_exists("dberr1", $certificate)) {
+
+                        $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
+                        return $erros_acumulados;
+                    }
+                    if (array_key_exists("dberr2", $certificate)) {
+                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
+                        //continue;
+                    }
+                    /*  Retirado este teste para evitar mensagem de erro duplicada.
+                      if (!array_key_exists("certs", $certificate))
+                      {
+                      $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
+                      continue;
+                      }
+                     */
+                    include_once(dirname(__FILE__) . "/../../security/classes/CertificadoB.php");
+
+                    foreach ($certificate['certs'] as $registro) {
+                        $c1 = new certificadoB();
+                        $c1->certificado($registro['chave_publica']);
+                        if ($c1->apresentado) {
+                            $c2 = new Verifica_Certificado($c1->dados, $registro['chave_publica']);
+                            if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status) {
+                                $aux_mails[] = $registro['chave_publica'];
+                                $mail_list[] = strtolower($item);
+                            } else {
+                                if ($c1->dados['EXPIRADO'] || $c2->revogado) {
+                                    $db->update_certificate($c1->dados['SERIALNUMBER'], $c1->dados['EMAIL'], $c1->dados['AUTHORITYKEYIDENTIFIER'], $c1->dados['EXPIRADO'], $c2->revogado);
+                                }
+
+                                $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
+                                foreach ($c2->erros_ssl as $linha) {
+                                    $erros_acumulados .= $linha . chr(0x0A);
+                                }
+                                $erros_acumulados .= 'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
+                                $erros_acumulados .= $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
+                            }
+                        } else {
+                            $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
                         }
                     }
+                    if (!(in_array(strtolower($item), $mail_list)) && !empty($erros_acumulados)) {
+                        return $erros_acumulados;
+                    }
                 }
-                // Fim Valida envio de email para shared accounts
-                
-                
-//	    TODO - implementar tratamento SMIME no novo serviço de envio de emails e retirar o AND false abaixo
-	    if($params['smime'] AND false)
-        {
-            $body = $params['smime'];
-            $mail->SMIME = true;
-            // A MSG assinada deve ser testada neste ponto.
-            // Testar o certificado e a integridade da msg....
-            include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
-            $erros_acumulados = '';
-            $certificado = new certificadoB();
-            $validade = $certificado->verificar($body);
-            if(!$validade)
+
+                $mail->Certs_crypt = $aux_mails;
+            }
+
+            $attachment = json_decode($params['attachments'],TRUE);
+
+            foreach ($attachment as &$value) 
             {
-                foreach($certificado->erros_ssl as $linha_erro)
+                if((int)$value > 0) //BD attachment
                 {
-                    $erros_acumulados .= $linha_erro;
+                     $att = Controller::read(array('id'=> $value , 'concept' => 'mailAttachment'));
+
+                     if($att['disposition'] == 'embedded')
+                     {
+                         $body = str_replace('"../prototype/getArchive.php?mailAttachment='.$att['id'].'"', $att['name'], $body);
+                         $mailService->addStringImage(base64_decode($att['source']), $att['type'], $att['name']);
+                     }
+                     else
+                         $mailService->addStringAttachment(base64_decode($att['source']), $att['name'], $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] :'attachment' );
+
+                     unset($att);
+                }
+                else //message attachment
+                {
+                    $value = json_decode($value, true);
+                    $sub =  $value['name'] ? $value['name'].'.eml' :'no title.eml';
+                    $mbox_stream = $this->open_mbox($value['folder']);
+                    $rawmsg = $this->getRawHeader($value['uid']) . "\r\n\r\n" . $this->getRawBody($value['uid']);
+                    $mailService->addStringAttachment($rawmsg, $sub, 'message/rfc822', '7bit', 'attachment' );
+                    $message_size_total += mb_strlen($rawmsg); //Adiciona o tamanho do anexo a variavel que controlao tamanho da msg.
+                    unset($rawmsg);
+                }
+
+            }
+
+            $message_size_total += strlen($params['body']);   /* Tamanho do corpo da mensagem. */        
+
+            ////////////////////////////////////////////////////////////////////////////////////////////////////	
+            /**
+             * Faz a validação pelo tamanho máximo de mensagem permitido para o usuário. Se o usuário não estiver em nenhuma regra, usa o tamanho padrão.
+             */
+            $default_max_size_rule = $db->get_default_max_size_rule();
+            if (!$default_max_size_rule) {
+                $default_max_size_rule = str_replace("M", "", ini_get('upload_max_filesize')) * 1024 * 1024; /* hack para não bloquear o envio de email quando não for configurado um tamanho padrão */
+            } else {
+                foreach ($default_max_size_rule as $i => $value) {
+                    $default_max_size_rule = $value['config_value'];
                 }
             }
-            else
-            {
-                // Testa o CERTIFICADO: se o CPF  he o do usuario logado, se  pode assinar msgs e se  nao esta expirado...
-                if ($certificado->apresentado)
-                {
-                    if($certificado->dados['EXPIRADO']) $erros_acumulados .='Certificado expirado.';
-                    $this->cpf = isset($GLOBALS['phpgw_info']['server']['certificado_atributo_cpf'])&&$GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']!=''?$_SESSION['phpgw_info']['expressomail']['user'][$GLOBALS['phpgw_info']['server']['certificado_atributo_cpf']]:$this->username;
-                    if($certificado->dados['CPF'] != $this->cpf) $erros_acumulados .=' CPF no certificado diferente do logado no expresso.';
-                    if(!($certificado->dados['KEYUSAGE']['digitalSignature'] && $certificado->dados['EXTKEYUSAGE']['emailProtection'])) $erros_acumulados .=' Certificado nao permite assinar mensagens.';
-                }
-                else
-                {
-                    $$erros_acumulados .= 'Nao foi possivel usar o certificado para assinar a msg';
+
+            $default_max_size_rule = $default_max_size_rule * 1024 * 1024;    /* Tamanho da regra padrão, em bytes */
+            $id_user = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+
+
+            $ldap = new ldap_functions();
+            $groups_user = $ldap->get_user_groups($id_user);
+
+            $size_rule_by_group = array();
+            foreach ($groups_user as $k => $value_) {
+                $rule_in_group = $db->get_rule_by_user_in_groups($k);
+                if ($rule_in_group != "")
+                    array_push($size_rule_by_group, $rule_in_group);
+            }
+
+            $n_rule_groups = 0;
+            $maior_valor_regra_grupo = 0;
+            foreach ($size_rule_by_group as $i => $value) {
+                if (is_array($value[0])) {
+                    $n_rule_groups++;
+                    if ($value[0]['email_max_recipient'] > $maior_valor_regra_grupo)
+                        $maior_valor_regra_grupo = $value[0]['email_max_recipient'];
                 }
             }
-            if(!$erros_acumulados =='')
-            {
-                return $erros_acumulados;
-            }
-        }
-        else
-        {
-	    //Compatibilização com Outlook, ao encaminhar a mensagem
-			$body = mb_ereg_replace('<!--\[', '<!-- [', $params['body']);
-        }
-
-		$attachments = $_FILES;
-		$forwarding_attachments = $params['forwarding_attachments'];
-		$local_attachments = $params['local_attachments'];
-
-		//Test if must be saved in shared folder and change if necessary
-		if( $fromaddress[2] == 'y' ){
-			//build shared folder path
-			$newfolder = "user".$this->imap_delimiter.$fromaddress[3].$this->imap_delimiter.$this->imap_sentfolder;
-			if($this->folder_exists($newfolder)) 
-				$folder = $newfolder;
-			else 
-				$folder = $params['folder'];
-			
-		} else	{
-			$folder = $params['folder'];			
-		}
-		
-		$folder = mb_convert_encoding($folder, 'UTF7-IMAP','ISO_8859-1');
-		$folder = preg_replace('/INBOX[\/.]/i', 'INBOX'.$this->imap_delimiter, $folder);
-		$folder_name = $params['folder_name'];
-
-//		TODO - tratar assinatura e remover o AND false
-		if($signed && !$params['smime'] AND false)
-		{
-            $mail->Mailer = "smime";
-			$mail->SignedBody = true;
-		}
-
-
-		if($fromaddress)
-                	$mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
-               else
-                	$mailService->setFrom ('"'.$_SESSION['phpgw_info']['expressomail']['user']['firstname'].' '.$_SESSION['phpgw_info']['expressomail']['user']['lastname'].'" <'.$_SESSION['phpgw_info']['expressomail']['user']['email'].'>');
-		//$mailService->addTo($toaddress);
-		//$mailService->addCc($ccaddress);
-		$bol = $this->add_recipients('to', $toaddress, $mailService);
-		if(!$bol){
-			return $this->parse_error("Invalid Mail:", $toaddress);
-		}
-		$bol = $this->add_recipients('cc', $ccaddress, $mailService);
-		if(!$bol){
-			return $this->parse_error("Invalid Mail:", $ccaddress);
-		}
-		$allow = $_SESSION['phpgw_info']['server']['expressomail']['allow_hidden_copy']; 
- 		 
-		if($allow) 
- 		                { 
-			//$mailService->addBcc($ccoaddress);
-			$bol = $this->add_recipients('cco', $ccoaddress, $mailService);
-
-			if(!$bol){
-				return $this->parse_error("Invalid Mail:", $ccoaddress);
-			}
-		}
-
-		//Implementação para o In-Reply-To e References				
-		$msg_numb = $params['messageNum'];
-		$msg_folder = $params['messageFolder'];
-		$this->mbox = $this->open_mbox($msg_folder);		
-	
-		$header = $this->get_header($msg_numb);
-		$header_ = imap_fetchheader($this->mbox, $msg_numb, FT_UID);
-		$pattern = '/^[ \t]*Disposition-Notification-To:[ ]*<?[[:alnum:]\._-]+@[[:alnum:]_-]+[\.[:alnum:]]+>?/sm';
-		if (preg_match($pattern, $header_, $fields))
-		{
-			if(preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$fields[0], $matches)){
-				$return['DispositionNotificationTo'] = "<".$matches[0].">";
-			}
-		}
-		
-		$message_id = $header->message_id;
-		$references = array();
-		if($message_id != "")
-		{
-                   $mailService->addHeaderField('In-Reply-To',$message_id);
-
-		   if(isset($header->references)){
-			array_push($references, $header->references);
-		   }		
-			array_push($references, $message_id);
-			$mailService->addHeaderField('References',$references);
-
-		}
-	
-
-		$mailService->setSubject($subject);
-		$isHTML = ( (array_key_exists('type', $params) && in_array(strtolower($params['type']), array('html', 'plain')) ) ? 
-						strtolower($params['type']) != 'plain' : true );
-	
-
-//		TODO - tratar mensagem criptografada e remover o AND false abaixo
-        if (($encrypt && $signed && $params['smime']) || ($encrypt && !$signed) AND false)	// a msg deve ser enviada cifrada...
-		{
-			$email = $this->add_recipients_cert($toaddress . ',' . $ccaddress. ',' .$ccoaddress);
-            $email = explode(",",$email);
-            // Deve ser testado se foram obtidos os certificados de todos os destinatarios.
-            // Deve ser verificado um numero limite de destinatarios.
-            // Deve ser verificado se os certificados sao validos.
-            // Se uma das verificacoes falhar, nao enviar o e-mail e avisar o usuario.
-            // O array $mail->Certs_crypt soh deve ser preenchido se os certificados passarem nas verificacoes.
-            $numero_maximo = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['num_max_certs_to_cipher'];  // Este valor dever ser configurado pelo administrador do site ....
-            $erros_acumulados = "";
-            $aux_mails = array();
-            $mail_list = array();
-            if(count($email) > $numero_maximo)
-            {
-                $erros_acumulados .= "Excedido o numero maximo (" . $numero_maximo . ") de destinatarios para uma msg cifrada...." . chr(0x0A);
-                return $erros_acumulados;
-            }
-            // adiciona o email do remetente. eh para cifrar a msg para ele tambem. Assim vai poder visualizar a msg na pasta enviados..
-            $email[] = $_SESSION['phpgw_info']['expressomail']['user']['email'];
-            foreach($email as $item)
-            {
-                $certificate = $db->get_certificate(strtolower($item));
-                if(!$certificate)
-                {
-                    $erros_acumulados .= "Chamada com parametro invalido.  e-Mail nao pode ser vazio." . chr(0x0A);
-                    return $erros_acumulados;
+
+            if ($default_max_size_rule) {
+                $size_rule = $db->get_rule_by_user($_SESSION['phpgw_info']['expressomail']['user']['userid']);
+
+                if (!$size_rule && $n_rule_groups == 0) /* O usuário não está em nenhuma regra por usuário nem por grupo. Vai usar a regra padrão. */ {
+                    if ($message_size_total > $default_max_size_rule)
+                        return $this->functions->getLang("Message size greateruler than allowed (Default rule)");
                 }
 
-                if (array_key_exists("dberr1", $certificate))
-                {
-
-                    $erros_acumulados .= "Ocorreu um erro quando pesquisava certificados dos destinatarios para cifrar a msg." . chr(0x0A);
-                    return $erros_acumulados;
-				}
-                if (array_key_exists("dberr2", $certificate))
-                {
-                    $erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
-                    //continue;
-                }
-			/*  Retirado este teste para evitar mensagem de erro duplicada.
-                if (!array_key_exists("certs", $certificate))
-              	{
-               		$erros_acumulados .=  $item . ' : Nao  pode cifrar a msg. Certificado nao localizado.' . chr(0x0A);
-                    continue;
-                }
-            */
-                include_once(dirname( __FILE__ ) ."/../../security/classes/CertificadoB.php");
-
-                foreach ($certificate['certs'] as $registro)
-                {
-                    $c1 = new certificadoB();
-                    $c1->certificado($registro['chave_publica']);
-                    if ($c1->apresentado)
-                    {
-                        $c2 = new Verifica_Certificado($c1->dados,$registro['chave_publica']);
-                        if (!$c1->dados['EXPIRADO'] && !$c2->revogado && $c2->status)
-                        {
-                            $aux_mails[] = $registro['chave_publica'];
-                            $mail_list[] = strtolower($item);
+                else {
+                    if (count($size_rule) > 0) /* Verifica se existe regra por usuário. Se houver, ela vai se sobresair das regras por grupo. */ {
+                        $regra_mais_permissiva = 0;
+                        foreach ($size_rule as $i => $value) {
+                            if ($regra_mais_permissiva < $value['email_max_recipient'])
+                                $regra_mais_permissiva = $value['email_max_recipient'];
                         }
-                        else
-                        {
-                            if ($c1->dados['EXPIRADO'] || $c2->revogado)
-                            {
-                                $db->update_certificate($c1->dados['SERIALNUMBER'],$c1->dados['EMAIL'],$c1->dados['AUTHORITYKEYIDENTIFIER'],
-                                    $c1->dados['EXPIRADO'],$c2->revogado);
-                            }
-
-                            $erros_acumulados .= $item . ':  ' . $c2->msgerro . chr(0x0A);
-                            foreach($c2->erros_ssl as $linha)
-                            {
-                                $erros_acumulados .=  $linha . chr(0x0A);
-                            }
-                            $erros_acumulados .=  'Emissor: ' . $c1->dados['EMISSOR'] . chr(0x0A);
-                            $erros_acumulados .=  $c1->dados['CRLDISTRIBUTIONPOINTS'] . chr(0x0A);
-                        }
+                        $regra_mais_permissiva = $regra_mais_permissiva * 1024 * 1024;
+                        if ($message_size_total > $regra_mais_permissiva)
+                            return $this->functions->getLang("Message size greater than allowed (Rule By User)");
                     }
-                    else
-                    {
-                        $erros_acumulados .= $item . ' : Nao  pode cifrar a msg. Certificado invalido.' . chr(0x0A);
+                    else /* Regra por grupo */ {
+                        $maior_valor_regra_grupo = $maior_valor_regra_grupo * 1024 * 1024;
+                        if ($message_size_total > $maior_valor_regra_grupo)
+                            return $this->functions->getLang("Message size greater than allowed (Rule By Group)");
                     }
                 }
-            	if(!(in_array(strtolower($item),$mail_list)) && !empty($erros_acumulados))
-				{
-					return $erros_acumulados;
-        		}
             }
-
-            $mail->Certs_crypt = $aux_mails;
-        }
-						
-		if( count($forwarding_attachments) > 0 )// Build CID images 
-			$this->buildEmbeddedImages($mailService,$msg_uid,$forwarding_attachments, $body); 
-
-		//	Build Uploading Attachments!!!
-		if (count($attachments)>0) //Caso seja forward normal...
-		{
-			$total_uploaded_size = 0;
-			foreach ($attachments as $attach)
-			{
-                                if($attach['error'] == UPLOAD_ERR_INI_SIZE)
-                                    return $this->parse_error("message file too big");
-				if($attach['name']=='Unknown')
-					continue;
-				$mailService->addFileAttachment($attach['tmp_name'], $attach['name'], $this->get_file_type($attach['name']), 'base64', 'attachment');
-				$total_uploaded_size = $total_uploaded_size + $attach['size'];
-			}
-                        if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
-                        {
-         
-                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
-                            if( $total_uploaded_size > $upload_max_filesize)
-				return $this->parse_error("message file too big");
-			}
-		}
-		if(count($local_attachments)>0) { //Caso seja forward de mensagens locais
-
-			$total_uploaded_size = 0;
-			
-			foreach($local_attachments as $local_attachment) {
-				$file_description = unserialize(rawurldecode($local_attachment));
-				$tmp = array_values($file_description);
-				foreach($file_description as $i => $descriptor){
-					$tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
-				}
-				$mailService->addFileAttachment($_FILES[$tmp[1]]['tmp_name'], $tmp[2], $this->get_file_type($tmp[2]), 'base64', 'attachment');
-				$total_uploaded_size = $total_uploaded_size + $_FILES[$tmp[1]]['size'];
-			}
-			if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'])
-                        {
-                            $upload_max_filesize = str_replace('M','',$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size']) * 1024 * 1024;
-                            if( $total_uploaded_size > $upload_max_filesize)
-                                   return $this->parse_error("message file too big");
-                        }
-		}
-
-		//	Build Forwarding Attachments!!!
-		if (count($forwarding_attachments) > 0)
-		{
-			// 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];
-				$name_cid_files[0] = null;
-			}
-
-			foreach($forwarding_attachments as $forwarding_attachment)
-			{
-				$file_description = unserialize(rawurldecode($forwarding_attachment));
-				
-				foreach($file_description as $i => $item)
-					$file_description[$i] = urldecode($item);
-				
-				$tmp = array_values($file_description);
-				foreach($file_description as $i => $descriptor){
-					$tmp[$i]  = eregi_replace('\'*\'','',$descriptor);
-				}
-				$file_description = $tmp;
-				$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
-				$fileName = $file_description[2];
-				if(!array_search(trim($fileName),$name_cid_files)) {
-					$filename_dec = html_entity_decode(rawurldecode($fileName));
-					$mailService->addStringAttachment($fileContent, $filename_dec, $this->get_file_type($file_description[2]), $file_description[4] );
-
-				}
-			}
-		}
-		
-		//Build Message Attachments!!!
-		if(count($message_attachments) > 0 ) 
-		{
-			foreach($message_attachments as $folder_name => $messages)
-			{
-				foreach ($messages as $message_number => $message_subject) 
-				{
-					if (!$message_subject)
-						$message_subject  = 'no title.eml';
-					else 
-						$message_subject .= '.eml';
-					
-					if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
-						$rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
-					else{
-						$mbox_stream = $this->open_mbox($folder_name);
-						$rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
-					}
-							
-					$return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
-					$mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
-				}
-			}
-		}
-		
-		$message_size_total += strlen($params['body']);   /* Tamanho do corpo da mensagem. */
-		$message_size_total += $total_uploaded_size;      /* Incrementa com os anexos da nova mensagem, se houver. */
-		
-		////////////////////////////////////////////////////////////////////////////////////////////////////	
-		/** 
-		* Faz a validação pelo tamanho máximo de mensagem permitido para o usuário. Se o usuário não estiver em nenhuma regra, usa o tamanho padrão.
-		 */
-		$default_max_size_rule = $db->get_default_max_size_rule();	
-		if(!$default_max_size_rule)
-		{
-			$default_max_size_rule = str_replace("M","",ini_get('upload_max_filesize')) * 1024 * 1024; /* hack para não bloquear o envio de email quando não for configurado um tamanho padrão */
-		}
-		else
-		{
-			foreach($default_max_size_rule as $i=>$value)
-			{		
-				$default_max_size_rule = $value['config_value'];
-			}				
-		}
-		
-		$default_max_size_rule = $default_max_size_rule * 1024 * 1024;		  /* Tamanho da regra padrão, em bytes */
-		$id_user = $_SESSION['phpgw_info']['expressomail']['user']['userid'];	
-		
-		
-		$ldap = new ldap_functions();
-		$groups_user = $ldap->get_user_groups($id_user);
-
-		$size_rule_by_group = array();	
-		foreach($groups_user as $k=>$value_)
-		{	
-			$rule_in_group = $db->get_rule_by_user_in_groups($k);
-			if ($rule_in_group != "")
-				array_push($size_rule_by_group, $rule_in_group);
-		}	
-		
-		$n_rule_groups = 0;
-		$maior_valor_regra_grupo = 0;
-		foreach($size_rule_by_group as $i=>$value)
-		{
-			if(is_array($value[0]))
-			{
-				$n_rule_groups++;
-				if($value[0]['email_max_recipient'] > $maior_valor_regra_grupo)
-					$maior_valor_regra_grupo = $value[0]['email_max_recipient'];
-			}
-		}
-		
-		if($default_max_size_rule)
-		{
-			$size_rule = $db->get_rule_by_user($_SESSION['phpgw_info']['expressomail']['user']['userid']);
-
-			if(!$size_rule && $n_rule_groups == 0) /* O usuário não está em nenhuma regra por usuário nem por grupo. Vai usar a regra padrão. */
-			{
-				if($message_size_total > $default_max_size_rule)
-					return $this->functions->getLang("Message size greateruler than allowed (Default rule)");
-			}
-
-			else 
-			{
-				if(count($size_rule) > 0) /* Verifica se existe regra por usuário. Se houver, ela vai se sobresair das regras por grupo. */
-				{
-					$regra_mais_permissiva = 0;
-					foreach($size_rule as $i=>$value)
-					{	
-						if($regra_mais_permissiva < $value['email_max_recipient'])
-							$regra_mais_permissiva = $value['email_max_recipient'];
-					}
-					$regra_mais_permissiva = $regra_mais_permissiva * 1024 * 1024;			
-					if($message_size_total > $regra_mais_permissiva)
-						return $this->functions->getLang("Message size greater than allowed (Rule By User)");
-				}
-				else /* Regra por grupo */
-				{		
-					$maior_valor_regra_grupo = $maior_valor_regra_grupo * 1024 * 1024;			
-					if($message_size_total > $maior_valor_regra_grupo)
-						return $this->functions->getLang("Message size greater than allowed (Rule By Group)");	
-				
-				
-				}
-			}
-		}
-		/** 
-         * Fim da validação do tamanho da regra do tamanho de mensagem.
-		 */
-		 ////////////////////////////////////////////////////////////////////////////////////////////////////
-		
-		
-		
-		
-		
-		if($isHTML)
-			$mailService->setBodyHtml($body);
-		else
-			$mailService->setBodyText($body);
-
-		if($is_important)
-			$mailService->addHeaderField('Importance','High');
-
-		if($return_receipt)
-			$mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
-
-
-		if ($folder != 'null'){
-			$mbox_stream = $this->open_mbox($folder);
-			@imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen");
-		}
-
-		$sent = $mailService->send();
-
-		if($sent !== true)
-		{
-   			return $this->parse_error($sent);
-		}
-		else
-		{
-            if ($signed && !$params['smime'])
-			{
-				return $sent;
-			}
-			if($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True")
-			{
-				$userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
-				$userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
-				$now = date("d/m/y H:i:s");
-				$addrs = $toaddress.$ccaddress.$ccoaddress;
-				$sent = trim($sent);
-   				error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
-			}
-			if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
-				$contacts = new dynamic_contacts();
-				$new_contacts = $contacts->add_dynamic_contacts($toaddress.",".$ccaddress.",".$ccoaddress);
-				return array("success" => true, "new_contacts" => $new_contacts);
-			}
-   			return array("success" => true);
-		}
-	}
+            /**
+             * Fim da validação do tamanho da regra do tamanho de mensagem.
+             */
+            ////////////////////////////////////////////////////////////////////////////////////////////////////
+
+            if ($isHTML)
+                $mailService->setBodyHtml($body);
+            else
+                $mailService->setBodyText($body);
+
+            if ($is_important)
+                $mailService->addHeaderField('Importance', 'High');
+
+            if ($return_receipt)
+                $mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
+
+
+            if ($folder != 'null') {
+                $mbox_stream = $this->open_mbox($folder);
+                @imap_append($mbox_stream, "{" . $this->imap_server . ":" . $this->imap_port . "}" . $folder, $mailService->getMessage(), "\\Seen");
+            }
+
+            $sent = $mailService->send();
+
+            if ($sent !== true) {
+                return $this->parse_error($sent);
+            } else {
+                if ($signed && !$params['smime']) {
+                    return $sent;
+                }
+                if ($_SESSION['phpgw_info']['server']['expressomail']['expressoMail_enable_log_messages'] == "True") {
+                    $userid = $_SESSION['phpgw_info']['expressomail']['user']['userid'];
+                    $userip = $_SESSION['phpgw_info']['expressomail']['user']['session_ip'];
+                    $now = date("d/m/y H:i:s");
+                    $addrs = $toaddress . $ccaddress . $ccoaddress;
+                    $sent = trim($sent);
+                    error_log("$now - $userip - $sent [$subject] - $userid => $addrs\r\n", 3, "/home/expressolivre/mail_senders.log");
+                }
+                if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_dynamic_contacts']) {
+                    $contacts = new dynamic_contacts();
+                    $new_contacts = $contacts->add_dynamic_contacts($toaddress . "," . $ccaddress . "," . $ccoaddress);
+                    return array("success" => true, "new_contacts" => $new_contacts);
+                }
+                
+                   if($params['uids_save'] )
+                        $this->delete_msgs(array('folder'=> $params['save_folder'] , 'msgs_number' => $params['uids_save']));
+                       
+                
+                return array("success" => true);
+                
+            }
+    }
 	
 	
-	/**
-	* @license   http://www.gnu.org/copyleft/gpl.html GPL
-	* @author    Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
-	* @param     $mail email
-	* @param     $msg_uid uid da mensagem
-	* @param     $forwarding_attachments anexos
-	*/
-
-	function buildEmbeddedImages(&$mail,$msg_uid,&$forwarding_attachments ,&$body)
-	{ 
-		//Procura e retorna em $cids_imgs imagens embarcadas no corpo do e-mail
-		$pattern = '/src=("[^"]*?get_archive.php\?msgFolder=(.+)?&(amp;)?msgNumber=(.+)?&(amp;)?indexPart=(.+)?")/isU';
-		$cid_imgs = ''; 
-		preg_match_all( $pattern , $body , $cid_imgs , PREG_PATTERN_ORDER );
-		//-------------------------------------------------------------------//
-
-		$attPostions = array(); //Array que linka a possição da imagem com o indice que esta se encontra no array $forwarding_attachments
-
-		foreach ($forwarding_attachments as $i => $v){ // Monta o  array de link
-			$desc = unserialize(rawurldecode($v));
-			$attPostions[$desc[3]] = $i;
-		}
-
-		//Intera as imagens encontradas
-		foreach($cid_imgs[6] as $j => $val)
-        {		
-			$cid = base_convert(microtime().$j, 10, 36); //Gera um cid
-			$body = str_replace($cid_imgs[1][$j], '"cid:'.$cid.'"', $body ); //tira o src da imagem e coloca o cid.
-			$count    = strlen($cid_imgs[6][$j]);
-					
-			$attach_img = $forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']];
-			$file_description = unserialize(rawurldecode($attach_img));
-			
-			if (is_array($file_description))
-				foreach($file_description as $i => $descriptor)				
-                      $file_description[$i] = mb_ereg_replace('\'*\'','',$descriptor);
-
-			// The image is not in the same mail?
-			if ($msg_uid != $cid_imgs[4][$j]) 
-			{ 
-                $fa = $this->get_forwarding_attachment2($cid_imgs[2][$j], $cid_imgs[4][$j], $cid_imgs[6][$j], 'base64');
-                $fileContent = &$fa['binary'];
-				$fileName = $fa['name'];
-				$fileCode = $fa['encoding'];
-				$fileType =  $fa['type'];
-				$file_attached[0] = $cid_imgs[2][$j]; 
-				$file_attached[1] = $cid_imgs[4][$j]; 
-				$file_attached[2] = $fileName; 
-				$file_attached[3] = '0.'.(string)($j+1);
-				$file_attached[4] = 'base64'; 
-				$file_attached[5] = strlen($fileContent); //Size of file 
-				$file_attached[6] = $cid_imgs[6][$j];
-				$return_forward[] = $file_attached; 
-
- 				if ($file_attached[3] == $file_description[3] || $msg_uid == 'undefined')
-					unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
-				
-			} 
-			else 
-			{ 
-				$fileContent = $this->get_forwarding_attachment($file_description[0], $msg_uid, $file_description[3], 'base64'); 
-				$fileName = $file_description[2]; 
-				$fileCode = $file_description[4]; 
-				$file_description[3] = '0.'.(string)($j+1);
-				$file_description[6] = $cid_imgs[6][$j];
-				$fileType = $this->get_file_type($file_description[2]); 
-				unset($forwarding_attachments[$attPostions['\''.$cid_imgs[6][$j].'\'']]);
-				if (!empty($file_description)) 
-				{ 
-					$file_description[5] = strlen($fileContent); //Size of file 
-					$return_forward[] = $file_description; 
-				} 
-			} 
-
-			if ($fileContent) 
-				$mail->addStringImage($fileContent,$fileType,$fileName, $cid);					
-		}
-
-		return $return_forward; 
-	} 
 	function add_recipients_cert($full_address)
 	{
@@ -3664,172 +3447,4 @@
 		}
 	}
-
-
-	function save_msg($params)
-	{
-	
-		require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
-		$mailService = ServiceLocator::getService('mail');
-
-		$return_receipt = $params['input_return_receipt'];
-		$is_important = $params['input_important_message'];
-		
-		$msg_uid = $params['msg_id'];
-		$body = $params['body'];
-		$body = str_replace("%nbsp;","&nbsp;",$body);
-		$body = preg_replace("/\n/"," ",$body);
-		$body = preg_replace("/\r/","" ,$body);
-		$body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );					
-		$forwarding_attachments = $params['forwarding_attachments'];
-		$message_attachments    = $params['message_attachments'];
-		$attachments = $params['FILES'];
-		$return_files = $params['FILES'];
-		$message_attachments_contents = (isset($params['message_attachments_content'])) ? $params['message_attachments_content'] : false; 
-
-                if(is_array($params['local_attachments'])){
-                    foreach ($params['local_attachments'] as $key => $local_attach) {
-                       $tmp = unserialize(urldecode($local_attach));
-			   $attachments[$key]['name'] = urldecode($tmp[2]);
-			   $return_files[$key]['name'] = urldecode($tmp[2]);
-                    }
-                }
-
-		$folder = mb_convert_encoding($params['folder'], "UTF7-IMAP","ISO-8859-1, UTF-8");
-		$folder = @eregi_replace("INBOX[/.]", "INBOX".$this->imap_delimiter, $folder);
-
-		$mailService->setFrom ('"'.$fromaddress[0].'" <'.$fromaddress[1].'>');
-		$mailService->addTo($params['input_to']);
-		$mailService->addCc( $params['input_cc']);
-		$mailService->addBcc($params['input_cco']);
-		$mailService->setSubject($params['input_subject']);
-
-		if($is_important){
-			$mailService->addHeaderField('Importance','High');
-		}
-
-		if($return_receipt)
-			$mailService->addHeaderField('Disposition-Notification-To', $_SESSION['phpgw_info']['expressomail']['user']['email']);
-
-		$isHTML = ( ( array_key_exists( 'type', $params ) && in_array( strtolower( $params[ 'type' ] ), array( 'html', 'plain' ) ) ) ? strtolower( $params[ 'type' ] ) != 'plain' : true );
-
-		
-		if( count($forwarding_attachments) > 0 )
-			$return_forward = $this->buildEmbeddedImages($mailService, $msg_uid, $forwarding_attachments , $body);
-			
-		//Build Message Attachments!!!
-		if(count($message_attachments) > 0 ) 
-		{
-			foreach($message_attachments as $folder_name => $messages)
-			{
-				foreach ($messages as $message_number => $message_subject) 
-				{
-					if (!$message_subject)
-						$message_subject  = 'no title.eml';
-					else 
-						$message_subject .= '.eml';
-					
-					if( $message_attachments_contents &&  isset($message_attachments_contents[$folder_name]) )
-						$rawmsg = base64_decode( $message_attachments_contents[$folder_name][$message_number] );
-					else{
-						$mbox_stream = $this->open_mbox($folder_name);$mbox_stream = $this->open_mbox($folder_name);
-						$rawmsg = $this->getRawHeader($message_number) . "\r\n\r\n" . $this->getRawBody($message_number);
-					}
-											
-					$return_forward[] = array( 'name' => $message_subject, 'size' => mb_strlen($rawmsg));
-					$mailService->addStringAttachment($rawmsg, $message_subject, 'message/rfc822', '7bit', 'attachment' );
-				}
-			}
-		}
-		
-		$imagesParts = array(); 
-
-		if(count($return_forward) > 0 )
-		foreach ($return_forward as $value)
-			$imagesParts[$value[6]] = $value[3]; 	
-
-		//Build Forwarding Attachments!!!
-		if(count($forwarding_attachments) > 0 ) 
-		{
-			foreach($forwarding_attachments as $forwarding_attachment)
-			{
-
-				$file_description = unserialize(rawurldecode($forwarding_attachment));
-				foreach($file_description as $i => $item)
-					$file_description[$i] = urldecode($item);				
-			
-				$file_description = array_values($file_description); 
- 	                          	
-				foreach($file_description as $i => $descriptor)
-  	  	 	                                $file_description[$i] = eregi_replace('\'*\'','',$descriptor); 
-				
-				$fileContent = $this->get_forwarding_attachment($file_description[0], $file_description[1], $file_description[3],$file_description[4]);
-				$file_description[2] = html_entity_decode($file_description[2]);
-
-				$file_description[5] = strlen($fileContent); //Size of file
-				$return_forward[] = $file_description;
-				$mailService->addStringAttachment($fileContent, $file_description[2], $this->get_file_type($file_description[2]), $file_description[4] );
-			}
-			}
-
-		if ((count($return_forward) > 0) && (count($return_files) > 0))
-			$return_files = array_merge_recursive($return_forward,$return_files);
-		else if (count($return_files) < 1)
-				$return_files = $return_forward;
-
-		//Build Uploading Attachments!!!
-		$sizeof_attachments = count($attachments);	
-		if ($sizeof_attachments)
-			foreach ($attachments as $numb => $attach)
-				$mailService->addFileAttachment($attach['tmp_name'],  $attach['name'],$attach['type'],  'base64', 'attachment');
-
-
-		if (!$body)
-			$body = ' ';
-		
-		if($isHTML)
-			$mailService->setBodyHtml($body);
-		else
-			$mailService->setBodyText($body);
-
-
-		$mbox_stream = $this->open_mbox($folder);
-		$return['append'] = imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft");
-
-		$status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
-		$return['msg_no'] = $status->uidnext - 1;
-		$return['folder_id'] = $folder;
-		$return['imagesParts'] = $imagesParts; 
-
-		if($mbox_stream)
-			imap_close($mbox_stream);
-			
-		$returnFiles = array();                  
-		$ii = 0;
-                		
-		if(count($return_files) > 0)
-		{
-			foreach ($return_files as $index => $_attachment) 
-			{
-				if (array_key_exists("name", $_attachment))
-				{
-					$returnFiles[$ii]['name'] = base64_encode(mb_convert_encoding( $_attachment['name'], 'UTF-8', 'UTF-8, ISO-8859-1') );
-					$returnFiles[$ii]['size'] = $_attachment['size'];
-					$ii++;
-			}
-				else if($_attachment[2])
-			{
-					$returnFiles[$ii]['name'] = base64_encode(mb_convert_encoding( $_attachment[2], 'UTF-8', 'UTF-8, ISO-8859-1')); 
-					$returnFiles[$ii]['size'] = $_attachment[5];         
-					$ii++;
-			}
-		}
-		}
-		$return['files'] = serialize($returnFiles);
-		$return["subject"] = $params['input_subject'];
-		if (!$return['append'])	$return['append'] = imap_last_error();
-			
-		return $return;
-	}
-
 	
 	function set_messages_flag_from_search($params){		
Index: /trunk/expressoMail1_2/js/abas.js
===================================================================
--- /trunk/expressoMail1_2/js/abas.js	(revision 5602)
+++ /trunk/expressoMail1_2/js/abas.js	(revision 5604)
@@ -3,5 +3,7 @@
 var countBorders = 0; 
 var partMsgs = new Array(); 
-
+var msgAttachments = new Array();
+var imgAttachmentFlag = new Array(); 
+var uidsSave = new Array(); 
 
 function setBorderAttributes(ID)
@@ -151,5 +153,5 @@
 			
 	borderTitle = ( ( borderTitle && borderTitle.constructor == String && borderTitle.length > 0 ) ? borderTitle : '&nbsp;' );
-
+        
 	var resize = false;
         resize = resize_borders();
@@ -335,4 +337,5 @@
 	Element("exmail_main_body").insertBefore(div,Element("footer_menu"));       
 	alternate_border(ID);
+        uidsSave[ID] = [];
 	return ID;
 }
@@ -498,6 +501,4 @@
 {
 	openTab.toPreserve[ID] = false;
-	openTab.imapUid[ID] = 0;
-
         // Limpa o autosave
             if (preferences.auto_save_draft == 1 && autoSaveControl.timer[ID] !== null )
@@ -579,2 +580,31 @@
 	}
 }
+
+function addAttachment(ID, att)
+{
+    if(typeof(msgAttachments[ID]) == 'undefined')
+            msgAttachments[ID] = [];
+
+        msgAttachments[ID].push(att);
+}
+
+function delAttachment(ID, att)
+{
+    
+    if(msgAttachments[ID] == undefined) return;
+    var len = msgAttachments[ID].length;
+    for(var i = 0; i < len; i++)
+    {
+        if(msgAttachments[ID][i] == att)
+        {
+            msgAttachments[ID].splice(i,1);
+            break;
+        }
+    }  
+}
+
+function listAttachment(ID)
+{
+   return (typeof(msgAttachments[ID]) == 'undefined') ? '' : JSON.stringify(msgAttachments[ID]); 
+}
+
Index: /trunk/expressoMail1_2/js/main.js
===================================================================
--- /trunk/expressoMail1_2/js/main.js	(revision 5588)
+++ /trunk/expressoMail1_2/js/main.js	(revision 5604)
@@ -277,5 +277,5 @@
 			var save_link = Element("save_message_options_"+border_id);
 			save_link.onclick = function onclick(event) {openTab.toPreserve[border_id] = true;save_msg(border_id);} ;
-			$("#save_message_options_"+border_id).button({ disabled: false });
+			$("#save_message_options_"+border_id).button({disabled: false});
 			$(".header-button").button();
 		};
@@ -580,5 +580,5 @@
 								return $(DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : $(this).find(".td_msg_subject").text(), type: "messages"}));
 						},
-						cursorAt: { cursor: "move", top: 5, left: 56 },
+						cursorAt: {cursor: "move", top: 5, left: 56},
 						refreshPositions: true ,
 						scroll: true, 
@@ -1805,6 +1805,4 @@
 		case "edit":
 			openTab.imapBox[new_border_ID] = folder_message.value;
-			//openTab.toPreserve[new_border_ID] = true;
-			openTab.imapUid[new_border_ID] = parseInt(border_ID.substr(0,border_ID.indexOf("_")));
 			document.getElementById('font_border_id_'+new_border_ID).innerHTML = data.subject;
 			title = "Edição: "+data.subject;
@@ -2073,7 +2071,5 @@
 			}
 		}
-		if ((! openTab.toPreserve[ID]) && (openTab.imapUid[ID] != 0))
-			cExecute ("$this.imap_functions.delete_msgs&folder="+openTab.imapBox[ID]+"&msgs_number="+openTab.imapUid[ID],function(data){return});
-		delete_border(ID,'true'); // Becarefull: email saved automatically should be deleted. delete_border erase information about openTab
+		delete_border(ID,'true'); 
  	}
 	else{
@@ -2087,5 +2083,5 @@
 		var save_link = Element("save_message_options_"+ID);
 		save_link.onclick = function onclick(event) {openTab.toPreserve[ID] = true;save_msg(ID);} ;
-		$("#save_message_options_"+ID).button({ disabled: false });
+		$("#save_message_options_"+ID).button({disabled: false});
 		//save_link.className = 'message_options';
 	}
@@ -2173,5 +2169,4 @@
 	save_link.onclick = '';
 	$("#save_message_options_"+ID).button({ disabled: true });
-	//save_link.className = 'message_options_inactive';
 
 	ID_tmp = ID;
@@ -2184,22 +2179,5 @@
 	mail_as_plain = ( mail_as_plain ) ? mail_as_plain.checked : false;
 
-       var content_body  = RichTextEditor.getData('body_'+ID);
-       //Remove imagens do corpo que estao com o checkbox desmarcados
-       var files_checkbox =  $("#divFiles_"+ID+" input:checkbox");
-       var files_unchecked = new Array();
-       for (var i = 0; i < files_checkbox.length; i++)
-            if(files_checkbox[i].checked !== true)
-                files_unchecked.push(connector.unserialize(unescape(trim(files_checkbox[i].value))));
-
-       var imagens = content_body.match(/<img[^>]*>/g);
-       
-       if(imagens != null)
-            for (var x = 0; x < imagens.length; x++)
-                for (var xx = 0; xx < files_unchecked.length; xx++)
-                    if(imagens[x].indexOf('indexPart='+files_unchecked[xx][3].replace(/'/g,'')) !== -1)
-                         content_body = content_body.replace(imagens[x],'');
-                
-        //--------------------------------------------------------------------------//
-        
+       var content_body  = RichTextEditor.getData('body_'+ID);        
 	var textArea = document.createElement("TEXTAREA");
 	textArea.style.display='none';
@@ -2210,9 +2188,20 @@
 	input_folder.style.display='none';
 	input_folder.name = "folder";
-	input_folder.value = folder;
-	var msg_id = document.createElement("INPUT");
-	msg_id.style.display='none';
-	msg_id.name = "msg_id";
-	msg_id.value = openTab.imapUid[ID];
+	input_folder.value = folder;      
+        
+        var uids = document.createElement("INPUT");
+	uids.style.display='none';
+	uids.name = "uids_save";
+	uids.value = uidsSave[ID].toString();
+        
+        var save_folder = document.createElement("INPUT");
+	save_folder.style.display='none';
+	save_folder.name = "save_folder";
+	save_folder.value = (openTab.imapBox[ID] && openTab.type[ID] < 6) ? openTab.imapBox[ID]: "INBOX" + cyrus_delimiter + draftsfolder;
+        
+        var msg_attachments = document.createElement("INPUT");
+	msg_attachments.style.display='none';
+	msg_attachments.name = "attachments";
+	msg_attachments.value = listAttachment(ID);
 
 	if (is_ie){
@@ -2239,6 +2228,4 @@
 	form.appendChild(textArea);
 	form.appendChild(input_folder);
-	form.appendChild(msg_id);
-
 
 	// Implementação do In_Reply_To e References
@@ -2248,13 +2235,10 @@
 	msgId.value = currentTab;
 
-	var msgFolder = document.createElement("INPUT");
-	msgFolder.style.display = 'none';
-	msgFolder.name = 'messageFolder';
-	msgFolder.value = openTab.imapBox[currentTab];
+
 
 	form.appendChild(msgId);
-	form.appendChild(msgFolder);
-
-
+        form.appendChild(save_folder);
+        form.appendChild(uids);
+	form.appendChild(msg_attachments);
 
     var mail_type = document.createElement('input');
@@ -2350,164 +2334,4 @@
 }
 
-function return_save(data,border_id,folder_name,folder_id,message_id)
-{
-	Element("send_button_"+border_id).style.visibility="visible";
-	var handler_delete_msg = function(data){refresh(preferences.alert_new_msg);RichTextEditor.execPosInstance('body_'+border_id);};
-	
-	
-        if(data === null)
-	{
-            write_msg(get_lang('ERROR saving your message.'));
-            return null;
-        }
-	if(typeof(data.append)  == 'undefined')
-		data.append = false;
-		
-	if(data.append === "Over quota"){
-		write_msg(get_lang('ERROR saving your message over quota.'));
-		return;
-	}
-	else if ( data.append !== true )
-	{
-		if (data.append == null)
-                    write_msg(get_lang('ERROR saving your message.'));
-		else
-		{
-			if (data.append.match(/^(.*)TRYCREATE(.*)$/))
-			{
-				connector.loadScript('TreeS');
-				alert(get_lang('There is not %1 folder, Expresso is creating it for you... Please, repeat your request later.',draftsfolder));
-				connector.loadScript('TreeShow');
-				ttree.FOLDER = 'root';
-				ttreeBox.new_past(draftsfolder);
-				setTimeout('save_msg('+border_id+')',3000);
-			}
-			else
-				write_msg(data.append);
-		}
-	}
-	else
-	{
-		var newImage = false;
-		RichTextEditor.saveFlag = 1;
-		openTab.imapUid[border_id] = data.msg_no;
-		openTab.imapBox[border_id] = data.folder_id;
-
-		var newTitle = document.getElementById('subject_'+border_id).value;
-		if (newTitle.length > 18)
-                    newTitle = newTitle.substr(18) + '...';
-                else if (newTitle == '')
-                    newTitle = get_lang("No subject");
-		document.getElementById('font_border_id_'+border_id).innerHTML = newTitle;                 
-                Element('border_id_'+border_id).title = newTitle; 
-
-		// Replace the embedded images for new uids
-		var content_body  = RichTextEditor.getData('body_'+border_id);
-		var body_images   = content_body.match(/msgNumber=\d*/g);
-		var folder_images = content_body.match(/msgFolder=[^&]*&/g); 		
-
-                if (body_images != null)
-                {
-                    for (var i=0; i<body_images.length; i++)
-                    {
-                        if( folder_images != null)
-                          content_body = content_body.replace(folder_images[i], "msgFolder=INBOX" + cyrus_delimiter + draftsfolder +"&");
-
-
-                            
-                        
-                        content_body = content_body.replace(body_images[i],"msgNumber="+openTab.imapUid[border_id]);
-                    }
-
-                    var images_part   = content_body.match(/indexPart=[0-9.]*/g);
-
-                    if(images_part != null)
-                                {
-                        for (var x = 0; x < images_part.length; x++)
-                                {
-                            var position = images_part[x].substr(10,images_part[x].length);
-                            content_body = content_body.replace(images_part[x],'indexPart(||.|||.||)='+data.imagesParts[position]);
-                                }
-
-                        }
-               	    content_body = content_body.replace(/indexPart\(\|\|\.\|\|\|\.\|\|\)=/g,'indexPart=');             
-                    }
-
-                   
-
-		//Replace all files to new files
-		var divFiles = Element("divFiles_"+border_id);
-		divFiles.innerHTML = '';
-
-
-		var attach_files = connector.unserialize(data.files);
-		if (attach_files != null) {
-                    openTab.countFile[border_id] = attach_files.length;
-                    for (var att_index = 0; att_index < attach_files.length; att_index++){
-
-                        var link_attachment = document.createElement("a");
-
-                        var fileName = Base64.decode(attach_files[att_index].name);
-                        var fileSize = attach_files[att_index].size / 1024;
-                        
-                        
-                        link_attachment.innerHTML = fileName + " ("+parseInt(fileSize)+" kb)";
-						
-						var encoding = /\.eml$/.exec(fileName)? '7bit' : 'base64';
-                        var href = "'"+folder_id+"','"+data.msg_no+"','"+(att_index)+"','0."+(att_index+1)+"','"+encoding+"'";
-
-                        link_attachment.setAttribute("href", "javascript:download_attachments("+href+")");
-
-                        var a_tmp = href.split(',');
-                        a_tmp[2] = fileName;
-                        s_tmp = escape(connector.serialize(a_tmp));
-
-                        var check_attachment = document.createElement("input");
-			check_attachment.type = 'CHECKBOX';
-			check_attachment.name = 'forwarding_attachments[]';
-                        check_attachment.value = s_tmp;
-
-
-
-                        divFiles.appendChild(check_attachment);
-                        divFiles.appendChild(link_attachment);
-
-                        divFiles.appendChild(document.createElement("br"));
-						
-						check_attachment.checked = true;
-                        check_attachment.setAttribute("checked", "checked");
-                    }
-					} 
- 		                 
- 		                if(RichTextEditor.newImageId !== false) 
- 		                { 
- 		                    var rex = new RegExp('<img id="'+RichTextEditor.newImageId+'" src="" [^\/>]*\/>', 'i'); 
- 		                    var newImg = '<img src="./inc/get_archive.php?msgFolder=INBOX'+cyrus_delimiter+draftsfolder+'&msgNumber='+openTab.imapUid[border_id]+'&indexPart=0.'+(openTab.countFile[border_id])+'" />'; 
- 		                    content_body = content_body.replace(rex,newImg); 
- 		 
- 		                    RichTextEditor.newImageID = false;                     
- 		                    newImage = true; 
- 		                } 
- 		                 
- 		                if(body_images != null || newImage === true) 
- 		                {  
- 		                     RichTextEditor.setData('body_'+border_id,content_body); 
-                }
-
-		if (message_id)
-		{
-                    cExecute ("$this.imap_functions.delete_msgs&folder="+openTab.imapBox[border_id]+"&msgs_number="+message_id,handler_delete_msg);
-                    if (openTab.imapBox[0] == "INBOX" + cyrus_delimiter + draftsfolder)
-                    {
-                        //Update mailbox
-                        var tr_msg = document.getElementById(message_id);
-                        change_tr_properties(tr_msg, data.msg_no, data.subject);
-                    }
-
-	}
-                setTimeout( function(){RichTextEditor.saveFlag = 1;RichTextEditor.execPosInstance('body_'+border_id);}, 1000 );
-	}
-        return null;
-}
 
 function autoSave( ID )
@@ -2517,198 +2341,23 @@
 }
 
-function save_msg(border_id,withImage, out){
+function save_msg(border_id){
        
-       //seta o status do auto_save = true
-        if (preferences.auto_save_draft == 1)
-            autoSaveControl.status[border_id] = true;
-       ///////////////////////////////////////////
-      
-	if (typeof(withImage) == 'undefined')
-		withImage = false;
-
-	var sendButton = Element("send_button_"+border_id);
-	if (sendButton)
-		sendButton.style.visibility="hidden";
-
-	if (openTab.imapBox[border_id] && openTab.type[border_id] < 6) //Gets the imap folder
-		var folder_id = openTab.imapBox[border_id];
-	else
-		var folder_id = "INBOX" + cyrus_delimiter + draftsfolder;
-
-	if (folder_id == 'INBOX') // and folder name from border
-		var folder_name = get_lang(folder_id);
-	else
-		var folder_name = folder_id.substr(6);
-
-	// hack to avoid form connector bug,  escapes quotation. Please see #179
-	tmp_border_id=border_id;
-	tmp_folder_name=folder_name;
-	tmp_folder_id=folder_id;
-	message_id = openTab.imapUid[border_id];
-	var handler_save_msg = function(data){
-		if(typeof(out) == 'undefined'){
-			return_save(data,this.tmp_border_id,this.tmp_folder_name,this.tmp_folder_id,this.message_id);
-			var save_link = Element("save_message_options_"+border_id);
-			if(!withImage){
-				if(data.append === true){
-					$("#save_message_options_"+border_id).button();
-					$("#save_message_options_"+border_id).button({ disabled: true });
-					watch_changes_in_msg(border_id);	
-					write_msg(get_lang('Your message was save as draft in folder %1.', lang_folder(folder_name)));
-				}
-				if(auto){
-					auto = false;
-				}
-			}
-			else{
-				write_msg(get_lang('Wait a moment, your image is uploading ...'));
-				var auto = true;
-				setTimeout( function(){save_msg(border_id)}, 1000 );
-			}
-		}else{
-			if(data.append === true){
-				write_msg(get_lang('Your message was save as draft in folder %1.', lang_folder(folder_name)));
-			}else if(data.append == null){
-				write_msg(get_lang('ERROR saving your message.'));
-			}if(data.append === "Over quota"){
-				write_msg(get_lang('ERROR saving your message over quota.'));
-			}
-		}
-		
-	}
-
-        var mail_as_plain = document.getElementById( 'textplain_rt_checkbox_' + border_id );
-	mail_as_plain = ( mail_as_plain ) ? mail_as_plain.checked : false;
-
-       var content_body  = RichTextEditor.getData("body_"+border_id);
-       //Remove imagens do corpo que estao com o checkbox desmarcados
-       var files_checkbox =  $("#divFiles_"+border_id+" input:checkbox");
-       var files_unchecked = new Array();
-       for (var i = 0; i < files_checkbox.length; i++)
-            if(files_checkbox[i].checked !== true)
-                files_unchecked.push(connector.unserialize(unescape(trim(files_checkbox[i].value))));
-
-       var imagens = content_body.match(/<img[^>]*>/g);
-       if(imagens != null)
-            for (var x = 0; x < imagens.length; x++)
-                for (var xx = 0; xx < files_unchecked.length; xx++)
-                    if(imagens[x].indexOf('indexPart='+files_unchecked[xx][3].replace(/'/g,'')) !== -1)
-                         content_body = content_body.replace(imagens[x],'');
-        
-        if(files_unchecked.length > 0)
-            RichTextEditor.setData("body_"+border_id,content_body);
-            
-        
-	var textArea = document.createElement("TEXTAREA");
-	textArea.style.display='none';
-	textArea.name = "body";
-	textArea.value = content_body;
-	var input_folder = document.createElement("INPUT");
-	input_folder.style.display='none';
-	input_folder.name = "folder";
-	input_folder.value = folder_id;
-	var input_msgid = document.createElement("INPUT");
-	input_msgid.style.display='none';
-	input_msgid.name = "msg_id";
-	input_msgid.value = message_id;
-	var input_insertImg = document.createElement("INPUT");
-	input_insertImg.style.display='none';
-	input_insertImg.name = "insertImg";
-	input_insertImg.value = withImage;
-
-
-	if (is_ie)
+     //seta o status do auto_save = true
+    if (preferences.auto_save_draft == 1)
+        autoSaveControl.status[border_id] = true;
+    ///////////////////////////////////////////
+    
+    var idJavascript = DataLayer.put('message',DataLayer.form("#form_message_"+border_id));    
+    uidsSave[border_id] = [];
+    DataLayer.commit(false,false,function(data){
+        if(data != null && data['message://'+idJavascript].id !== undefined )
         {
-		var i = 0;
-		while (document.forms(i).name != "form_message_"+border_id){i++}
-		form = document.forms(i);
-	}
-	else
-        {
-		form = document.forms["form_message_"+border_id];
-        }
-        
-	form.appendChild(textArea);
-	form.appendChild(input_folder);
-	form.appendChild(input_msgid);
-	form.appendChild(input_insertImg);
-
-        var mail_type;
-        
-        if (is_ie)
-        {
-            mail_type = document.createElement('<input type="hidden" />');
+            uidsSave[border_id].push(data['message://'+idJavascript].id);
+             write_msg('Mensagem salva com sucesso!');
         }
         else
-            {
-                mail_type = document.createElement('input');
-                mail_type.setAttribute('type', 'hidden');
-            }
-        mail_type.setAttribute('name', 'type');
-        var mail_type_value = ( mail_as_plain ) ? 'plain' : 'html';
-	mail_type.setAttribute("value", mail_type_value);
-
-	form.parentNode.appendChild(mail_type);
-
-	cExecuteForm ("$this.imap_functions.save_msg", form, handler_save_msg,border_id);
-}
-
-function return_saveas(data,border_id,folder_name)
-{
-	if(!verify_session(data))
-		return;
-	if (data.append)
-	{
-		delete_border(border_id,null);
-		write_msg(get_lang('Your message was save as draft in folder %1.', folder_name));
-	}
-	else
-		write_msg(get_lang('ERROR saving your message.'));
-}
-
-
-function save_as_msg(border_id, folder_id, folder_name){
-	// hack to avoid form connector bug,  escapes quotation. Please see #179
-	tmp_border_id=border_id;
-	tmp_folder_name=folder_name;
-	var handler_save_msg = function(data){return_saveas(data,this.tmp_border_id,this.tmp_folder_name);}
-        
-       var content_body  = RichTextEditor.getData("body_"+border_id);
-       //Remove imagens do corpo que estao com o checkbox desmarcados
-       var files_checkbox =  $("#divFiles_"+border_id+" input:checkbox");
-       var files_unchecked = new Array();
-       for (var i = 0; i < files_checkbox.length; i++)
-            if(files_checkbox[i].checked !== true)
-                files_unchecked.push(connector.unserialize(unescape(trim(files_checkbox[i].value))));
-
-       var imagens = content_body.match(/<img[^>]*>/g);
-       
-       if(imagens != null)
-            for (var x = 0; x < imagens.length; x++)
-                for (var xx = 0; xx < files_unchecked.length; xx++)
-                    if(imagens[x].indexOf('indexPart='+files_unchecked[xx][3].replace(/'/g,'')) !== -1)
-                         content_body = content_body.replace(imagens[x],'');
-        
-	var textArea = document.createElement("TEXTAREA");
-	textArea.style.display='none';
-	textArea.name = "body";
-	textArea.value = content_body;
-
-	var input_folder = document.createElement("INPUT");
-	input_folder.style.display='none';
-	input_folder.name = "folder";
-	input_folder.value = folder_id;
-
-	if (is_ie){
-		var i = 0;
-		while (document.forms(i).name != "form_message_"+border_id){i++}
-		form = document.forms(i);
-	}
-	else
-		form = document.forms["form_message_"+border_id];
-	form.appendChild(textArea);
-	form.appendChild(input_folder);
-
-	cExecuteForm ("$this.imap_functions.save_msg", form, handler_save_msg,border_id);
+            write_msg('Erro ao salvar sua menssagem!');
+    });
+
 }
 
@@ -3874,2 +3523,43 @@
 		} 
 
+
+DataLayer.codec( "message", "detail", {
+  
+	decoder:function( form ){
+            var border_id = form.abaID;  
+            ///Dfininindo pasta a ser salva mensagem
+            var folder_id = (openTab.imapBox[border_id] && openTab.type[border_id] < 6) ? openTab.imapBox[border_id]: "INBOX" + cyrus_delimiter + draftsfolder;
+            form.folder = folder_id;
+            form.body = RichTextEditor.getData("body_"+border_id);
+            form.attachments = listAttachment(border_id);
+            form.uidsSave = uidsSave[border_id].toString();
+            return( form );
+      
+	},
+
+	encoder:function( pref ){
+              
+		return( pref );
+	}
+
+});
+
+DataLayer.codec( "mailAttachment", "detail", {
+  
+	decoder: function(evtObj){
+	
+		if( notArray = $.type(evtObj) !== "array" )
+			evtObj = [ evtObj ];
+
+		var res = $.map(evtObj, function( form){
+			return [$.map(form.files , function( files){
+					return { source: files , disposition : form['attDisposition'+form.abaID]};
+				})];
+		});
+	return notArray ? res[0] : res;
+	},
+      
+	encoder: function(){}
+
+      
+});
Index: /trunk/expressoMail1_2/js/draw_api.js
===================================================================
--- /trunk/expressoMail1_2/js/draw_api.js	(revision 5600)
+++ /trunk/expressoMail1_2/js/draw_api.js	(revision 5604)
@@ -1341,5 +1341,5 @@
 						return $(DataLayer.render('../prototype/modules/mail/templates/draggin_box.ejs', {texto : $(this).find(".td_msg_subject").text(), type: "messages"}));
 				},
-				cursorAt: { cursor: "move", top: 5, left: 56 },
+				cursorAt: {cursor: "move", top: 5, left: 56},
 				refreshPositions: true ,
 				scroll: true, 
@@ -2966,5 +2966,5 @@
 				['=', 'folderName', current_folder], 
 				['=','messageNumber',folder_id]], 
-			criteria : { deepness: 2}}  );
+			criteria : {deepness: 2}} );
 	
 	if(labels.length != 0){
@@ -3421,5 +3421,7 @@
 	var form = document.createElement("FORM");
 	form.name = "form_message_"+ID;
+        form.id = "form_message_"+ID;
 	form.method = "POST";
+        form.action = "message:detail";
 	form.onsubmit = function(){return false;}
 	if(!is_ie)
@@ -3427,4 +3429,10 @@
 	else
 		form.encoding="multipart/form-data";
+       
+        var aba_id = document.createElement("INPUT");
+        aba_id.style.display='none';
+        aba_id.name = "abaID";
+        aba_id.value = ID;
+        form.appendChild(aba_id);        
 /////////////////////////////////////////////////////////////////////////////////////////////////////////
 	//ConstructMenuNewMessage(ID);
@@ -4007,28 +4015,228 @@
 	};
 
-	var add_files = document.createElement("A");
-	add_files.setAttribute("href", "javascript:void(0)");
-	add_files.onclick = function () {
-		var obj = addFile(ID);
-		if (preferences.auto_save_draft == 1 && obj) {
-			if ( obj.addEventListener ){
-				obj.addEventListener('click', save_onchange_attachment_handler, false);
-			}
-		}
-		return false;
- 	};
-	
-	add_files.innerHTML =  get_lang("Attachments: add+");
-	add_files.setAttribute("tabIndex","-1");
-	
-	var add_msgs = document.createElement("A");
-	add_msgs.setAttribute("href", "javascript:void(0)");
-	add_msgs.setAttribute("tabIndex","-1");
-	is_ie ? add_msgs.setAttribute("className", 'message-attach-link') : add_msgs.setAttribute("class", 'message-attach-link');
-	add_msgs.innerHTML =  get_lang("Messages: add+");
-	var divfiles = document.createElement("DIV");
-	divfiles.id = "divFiles_"+ID;
-
-	jQuery(add_msgs).click(function(event){
+
+	var tr5 = document.createElement("TR");
+	var td5_link = document.createElement("TD");
+	var td5_input = document.createElement("TD");
+	td5_input.innerHTML = "&nbsp;"
+	td5_link.setAttribute("valign","top");
+	$(td5_link).append('<div id="message-attach-dialog" title="'+get_lang('Select messages to attach...')+'"> </div>');
+        $(td5_link).prepend(DataLayer.render("../prototype/modules/mail/templates/attachment.ejs", {ID:ID}));
+	tr5.appendChild(td5_input);
+	tr5.appendChild(td5_link);
+        
+	tbody_message.appendChild(tr5);
+	var tr6 = document.createElement("TR");
+	var td6_link  = document.createElement("TD");
+	var td6_input = document.createElement("TD");
+	tr6.appendChild(td6_link);
+	
+	tr6.appendChild(td6_input);
+	tbody_message.appendChild(tr6);
+
+	var tr7 = document.createElement("TR");
+	//var td5 = document.createElement("TD");
+	//td5.innerHTML = "&nbsp;";
+	var td_body = document.createElement("TD");
+	td_body.setAttribute("colSpan","2");
+	var div_body_position = document.createElement("DIV");
+	div_body_position.id = "body_position_" + ID;
+	td_body.appendChild(div_body_position);
+	//tr5.appendChild(td5);
+	tr7.appendChild(td_body);
+	tbody_message.appendChild(tr7);
+   	var _div = document.createElement("DIV");
+	_div.id = "div_message_scroll_"+ID;
+	_div.style.overflow = "auto";
+	_div.style.width = "100%";
+
+	// Hide the contac tips and re-position the pallete color.
+	_div.onscroll = function() {
+		var intElemScrollTop = Element("div_message_scroll_"+ID).scrollTop;
+		if (!is_ie)
+			ColorPalette.repos(intElemScrollTop);
+		Tooltip.scrollChanged();
+	};
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+	_div.appendChild(form);
+	content.appendChild(_div);
+	table_message.appendChild(tbody_message);
+	form.appendChild(table_message);
+                
+        var attDisposition = document.createElement("INPUT");
+	attDisposition.style.display='none';
+        attDisposition.id = 'attDisposition'+ID;
+	attDisposition.name = 'attDisposition'+ID;
+	attDisposition.value = 'attachment';
+        form.appendChild(attDisposition);
+        
+	RichTextEditor.loadEditor(ID);
+	
+	var rich_button = document.createElement("button");
+	
+	if(preferences.plain_text_editor == 1){
+		var texto = get_lang("Rich Text");
+	}else{
+		var texto = get_lang("Simple Text");
+	}
+		
+	rich_button.innerHTML = texto;
+	rich_button.className = "button small rich-button";
+	rich_button.name = "textplain_rt_checkbox_"+ID;
+	
+//////////////////////////////////////////////////////////////////////////////////////////////////////
+	if(!expresso_offline)
+		draw_from_field(sel_from,tr1_1);
+		
+	resizeWindow();
+
+	if ( ! expresso_offline )
+	{
+			if ( mobile_device )
+			{
+					text_plain.click( );
+					text_plain.parentNode.style.display = 'none';
+			}
+	}
+	//var a_cc_link2 = document.createElement("button");
+	
+	$("#another_adress_"+ID).append(a_cc_link);
+	
+	if(a_cco_link != undefined)
+		$("#another_adress_"+ID).append(a_cco_link);
+		
+	$("#another_adress_"+ID).append(rich_button);
+	
+	$("#to_"+ID).elastic().unbind('blur');	
+	$(".another_adress").button();
+	$(".rich-button").button();
+	$(".rich-button").click(function(){
+		//TO-DO : Se o usuário clicar varias vezes no botão, a função de iniciar o ckeditor se perde e morre.
+		$(this).button({disabled: true});
+		if($(this).find("span:first-child").html() == get_lang("Rich text")){
+			$(this).find("span:first-child").html(get_lang("Simple Text"));
+		}else{
+			$(this).find("span:first-child").html(get_lang("Rich Text"));
+		}
+		
+		var check = $("#"+$(this).attr("name")).attr("checked");
+		$("#"+$(this).attr("name")).attr("checked", (!check ? true : false));
+		$("#"+$(this).attr("name")).trigger('click');
+		$("#"+$(this).attr("name")).attr("checked", (!check ? true : false));
+		//$(this).button({ disabled: false });
+		if (RichTextEditor.plain[id] != true) 
+			setTimeout("RichTextEditor.focus("+ID+")",100);                  
+		else  
+			$('#body_'+ID).focus();
+	});
+	
+	if($("#send_and_custom_save_"+ID)[0])
+		$("#send_and_custom_save_"+ID).button({
+			icons : {
+				primary :"expressomail-icon-save_and_send"
+			}
+		})
+	$("#content_id_"+ID).find(".adress_button").button().click(function(){
+		emQuickSearch($("#"+($(this).attr("name"))+"_"+ID).val(), $(this).attr("name"), ID, undefined, true);
+	});
+	
+	$("#send_button_"+ID).button({
+		icons : {
+			primary : "expressomail-icon-send"
+		}
+	}).next().button({
+		icons : {
+			primary : "expressomail-icon-save"
+		}
+	});
+	$("#content_id_"+ID).find("[name=return_receipt_"+ID+"]").button({
+		icons : {
+			primary : "expressomail-icon-read-confirmation"
+		}
+	});
+	$("#important_message_options_"+ID).button({
+		icons : {
+			primary : "expressomail-icon-important"
+		}
+	});
+	$("#return_digital_options_"+ID).button({
+		icons : {
+			primary : "expressomail-icon-signature"
+		}
+	});
+	$("#return_cripto_options_"+ID).button({
+		icons : {
+			primary : "expressomail-icon-encryption"
+		}
+	});
+	
+	$("#content_id_"+ID).find(".send_option").click(function(){
+		var check = $("#"+$(this).attr("name")).attr("checked");
+		$("#"+$(this).attr("name")).attr("checked", (!check ? true : false));
+		$(this).toggleClass("expressomail-button-icon-ative");
+	});
+        
+        var fileUploadMSG = $('#fileupload_msg'+ID);
+        var maxAttachmentSise = (preferences.max_attachment_size !== "" && preferences.max_attachment_size != 0) ? (parseInt(preferences.max_attachment_size.replace('M', '')) * 1048576 ) : false;
+
+	fileUploadMSG.fileupload({
+		sequentialUploads: true,
+		add: function (e, data) {
+			if(!maxAttachmentSise || data.files[0].size < maxAttachmentSise) {
+				setTimeout(function() {
+                                        $('#attDisposition'+ID).val('attachment');
+					data.submit();
+				}, 5000);
+			}
+		},
+		change: function (e, data) {
+			$.each(data.files, function (index, file) {
+				var attach = {};
+				attach.fullFileName = file.name;
+				attach.fileName = file.name;
+				if(file.name.length > 10)
+					attach.fileName = file.name.substr(0, 18) + "..." + file.name.substr(file.name.length-9, file.name.length);
+				attach.fileSize = formatBytes(file.size);
+				if(maxAttachmentSise && file.size > maxAttachmentSise)
+					attach.error = 'Tamanho de arquivo nao permitido!!'
+								
+				fileUploadMSG.find('.attachments-list').append(DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist.ejs", {file : attach}));
+
+				if(!maxAttachmentSise || file.size < maxAttachmentSise){
+					fileUploadMSG.find('.fileinput-button.new').append(data.fileInput[0]).removeClass('new');
+					fileUploadMSG.find('.attachments-list').find('[type=file]').addClass('hidden');	
+				}else
+					fileUploadMSG.find(' .fileinput-button.new').removeClass('new');
+				
+				fileUploadMSG.find(' .attachments-list').find('.button.close').button({
+					icons: {
+						primary: "ui-icon-close"
+					},
+					text: false
+				}).click(function(){
+					var idAttach = $(this).parent().find('input[name="fileId[]"]').val();
+					fileUploadMSG.find(' .attachments-list').find('input[value="'+idAttach+'"]').remove();
+                                        delAttachment(ID, idAttach)
+					$(this).parent().remove();
+				});
+
+		})},
+
+		done: function(e, data){
+			if(!!data.result && data.result != "[]"){
+				var newAttach = jQuery.parseJSON(data.result);
+				fileUploadMSG.find('.in-progress:first').parents('p').append('<input type="hidden" name="fileId[]" value="'+newAttach['mailAttachment'][0][0].id+'"/>');
+                                addAttachment(ID,newAttach['mailAttachment'][0][0].id);
+                                
+			}else {
+				fileUploadMSG.find(' .progress.on-complete:first').removeClass('on-complete').parents('p').find('.status-upload').addClass('ui-icon ui-icon-cancel');
+			}
+                        fileUploadMSG.find(' .in-progress:first').remove();
+				
+                    
+		}
+	});
+
+       fileUploadMSG.find("span.message-attach-link").click(function(event){
 		jQuery('#message-attach-dialog').html(DataLayer.render("../prototype/modules/attach_message/attach_message.ejs", {}));
 		jQuery('#message-attach-dialog').dialog({
@@ -4043,19 +4251,23 @@
 		jQuery.getScript("../prototype/modules/attach_message/attach_message.js", function(){
 			jQuery('#message-attach-dialog').dialog('open');
-			
 			jQuery('#message-attach-attach-btn').click(function(event){
-				//alert(dump(selectedMessages));../
 				jQuery.each(selectedMessages, function(folder_name, messages) {
-				  
-					var isOffline = /^local_messages/.test(folder_name);
-
 					jQuery.each(selectedMessages[folder_name], function(message_number, message) { 
 						if (message) {
-							var subject = onceOpenedMessages[folder_name][message_number].subject;
-							var text_input  = '<input type="text" name="message_attachments['+folder_name+']['+message_number+']" value="'+subject+'"/>';
-							text_input += '<a href="javascript:void(0)" onclick="javascript:this.parentNode.parentNode.removeChild(this.parentNode);">' + get_lang("Remove")+'</a>';
-							if( isOffline )
-								text_input += '<input type="hidden" name="message_attachments_content['+folder_name+']['+message_number+']" value="'+Base64.encode( onceOpenedMessages[folder_name][message_number].eml )+'"/>';
-							jQuery(divfiles).append('<div>'+text_input+'</div>');
+                                                        var att = new Object();
+                                                        att.foder = folder_name;
+                                                        att.uid = message_number;
+                                                        att.name = onceOpenedMessages[folder_name][message_number].subject + '.eml';
+                                                        var idATT = JSON.stringify(att);
+                                                        addAttachment( ID , idATT);                        
+                                                        var attach = {};
+                                                        attach.fileName = att.name
+                                                        attach.fileSize = formatBytes(onceOpenedMessages[folder_name][message_number].size);
+                                                        var upload = $(DataLayer.render("../prototype/modules/mail/templates/attachment_add_itemlist.ejs", {file : attach}));
+                                                        upload.find('.status-upload').remove();
+                                                        upload.find('.in-progress').remove(); 
+                                                        upload.find('p').append('<input type="hidden" name="fileId[]" value=\''+idATT+'\'/>');
+                                                        fileUploadMSG.find('.attachments-list').append(upload);
+                                                        
 						}
 
@@ -4064,169 +4276,26 @@
 				
 				jQuery('#message-attach-dialog').dialog('close');
+				
+				//botao fechar
+				$('.attachments-list').find('.button.close').button({
+					icons: {
+						primary: "ui-icon-close"
+					},
+					text: false
+				}).click(function(){
+					var idAttach = $(this).parent().find('input[name="fileId[]"]').val();
+					fileUploadMSG.find(' .attachments-list').find('input[value="'+idAttach+'"]');
+                                        delAttachment(ID,idAttach); 
+					$(this).parent().remove();
+				});	
+				
 			});
 			jQuery('#message-attach-cancel-btn').click(function(event){
 				jQuery('#message-attach-dialog').dialog('close');
-			});
+			});			
 		});
+
 	});
-	var tr5 = document.createElement("TR");
-	var td5_link = document.createElement("TD");
-	var td5_input = document.createElement("TD");
-	td5_input.innerHTML = "&nbsp;"
-	//td5_input.style.width = "1%";
-	td5_link.setAttribute("valign","top");
-	//td5_link.setAttribute("colSpan","2");
-	td5_link.appendChild(add_files);
-	td5_link.appendChild(add_msgs);
-	$(td5_link).append('<div id="message-attach-dialog" title="'+get_lang('Select messages to attach...')+'"> </div>');
-	tr5.appendChild(td5_input);
-	tr5.appendChild(td5_link);
-	tbody_message.appendChild(tr5);
-	var tr6 = document.createElement("TR");
-	var td6_link  = document.createElement("TD");
-	var td6_input = document.createElement("TD");
-	//td6_link.style.width = "1%";
-	tr6.appendChild(td6_link);
-	td6_input.appendChild(divfiles);
-	tr6.appendChild(td6_input);
-	tbody_message.appendChild(tr6);
-//////////////////////////////////////////////////////////////////////////////////////////////////////
-	var tr5 = document.createElement("TR");
-	//var td5 = document.createElement("TD");
-	//td5.innerHTML = "&nbsp;";
-	var td_body = document.createElement("TD");
-	td_body.setAttribute("colSpan","2");
-	var div_body_position = document.createElement("DIV");
-	div_body_position.id = "body_position_" + ID;
-	td_body.appendChild(div_body_position);
-	//tr5.appendChild(td5);
-	tr5.appendChild(td_body);
-	tbody_message.appendChild(tr5);
-   	var _div = document.createElement("DIV");
-	_div.id = "div_message_scroll_"+ID;
-	_div.style.overflow = "auto";
-	_div.style.width = "100%";
-
-	// Hide the contac tips and re-position the pallete color.
-	_div.onscroll = function() {
-		var intElemScrollTop = Element("div_message_scroll_"+ID).scrollTop;
-		if (!is_ie)
-			ColorPalette.repos(intElemScrollTop);
-		Tooltip.scrollChanged();
-	};
-//////////////////////////////////////////////////////////////////////////////////////////////////////
-	_div.appendChild(form);
-	content.appendChild(_div);
-	table_message.appendChild(tbody_message);
-	form.appendChild(table_message);
-	RichTextEditor.loadEditor(ID);
-	
-	var rich_button = document.createElement("button");
-	
-	if(preferences.plain_text_editor == 1){
-		var texto = get_lang("Rich Text");
-	}else{
-		var texto = get_lang("Simple Text");
-	}
-		
-	rich_button.innerHTML = texto;
-	rich_button.className = "button small rich-button";
-	rich_button.name = "textplain_rt_checkbox_"+ID;
-	
-//////////////////////////////////////////////////////////////////////////////////////////////////////
-	if(!expresso_offline)
-		draw_from_field(sel_from,tr1_1);
-		
-	resizeWindow();
-
-	if ( ! expresso_offline )
-	{
-			if ( mobile_device )
-			{
-					text_plain.click( );
-					text_plain.parentNode.style.display = 'none';
-			}
-	}
-	//var a_cc_link2 = document.createElement("button");
-	
-	$("#another_adress_"+ID).append(a_cc_link);
-	
-	if(a_cco_link != undefined)
-		$("#another_adress_"+ID).append(a_cco_link);
-		
-	$("#another_adress_"+ID).append(rich_button);
-	
-	$("#to_"+ID).elastic().unbind('blur');
-	//$(".mail_fields");
-	//$(".mail_fields").css("width","100%");
-	
-	$(".another_adress").button();
-	$(".rich-button").button();
-	$(".rich-button").click(function(){
-		//TO-DO : Se o usuário clicar varias vezes no botão, a função de iniciar o ckeditor se perde e morre.
-		$(this).button({disabled: true});
-		if($(this).find("span:first-child").html() == get_lang("Rich text")){
-			$(this).find("span:first-child").html(get_lang("Simple Text"));
-		}else{
-			$(this).find("span:first-child").html(get_lang("Rich Text"));
-		}
-		
-		var check = $("#"+$(this).attr("name")).attr("checked");
-		$("#"+$(this).attr("name")).attr("checked", (!check ? true : false));
-		$("#"+$(this).attr("name")).trigger('click');
-		$("#"+$(this).attr("name")).attr("checked", (!check ? true : false));
-		//$(this).button({ disabled: false });
-		if (RichTextEditor.plain[id] != true) 
-			setTimeout("RichTextEditor.focus("+ID+")",100);                  
-		else  
-			$('#body_'+ID).focus();
-	});
-	
-	if($("#send_and_custom_save_"+ID)[0])
-		$("#send_and_custom_save_"+ID).button({
-			icons : {
-				primary :"expressomail-icon-save_and_send"
-			}
-		})
-	$("#content_id_"+ID).find(".adress_button").button().click(function(){
-		emQuickSearch($("#"+($(this).attr("name"))+"_"+ID).val(), $(this).attr("name"), ID, undefined, true);
-	});
-	
-	$("#send_button_"+ID).button({
-		icons : {
-			primary : "expressomail-icon-send"
-		}
-	}).next().button({
-		icons : {
-			primary : "expressomail-icon-save"
-		}
-	});
-	$("#content_id_"+ID).find("[name=return_receipt_"+ID+"]").button({
-		icons : {
-			primary : "expressomail-icon-read-confirmation"
-		}
-	});
-	$("#important_message_options_"+ID).button({
-		icons : {
-			primary : "expressomail-icon-important"
-		}
-	});
-	$("#return_digital_options_"+ID).button({
-		icons : {
-			primary : "expressomail-icon-signature"
-		}
-	});
-	$("#return_cripto_options_"+ID).button({
-		icons : {
-			primary : "expressomail-icon-encryption"
-		}
-	});
-
-	$("#content_id_"+ID).find(".send_option").click(function(){
-		var check = $("#"+$(this).attr("name")).attr("checked");
-		$("#"+$(this).attr("name")).attr("checked", (!check ? true : false));
-		$(this).toggleClass("expressomail-button-icon-ative");
-	});
-	
+//        
 	return ID;
 }
Index: /trunk/expressoMail1_2/js/rich_text_editor.js
===================================================================
--- /trunk/expressoMail1_2/js/rich_text_editor.js	(revision 5496)
+++ /trunk/expressoMail1_2/js/rich_text_editor.js	(revision 5604)
@@ -145,116 +145,5 @@
 }
 
-cRichTextEditor.prototype.createImage = function(){
-                
-	var form = document.getElementById("attachment_window");
-        
-	if (form == null){
-		form = document.createElement("DIV");
-		form.id  = "attachment_window";
-		form.style.visibility = "hidden";
-		form.style.position = "absolute";
-		form.style.background = "#eeeeee";
-		form.style.left = "0px";
-		form.style.top  = "0px"; 
-		form.style.width = "0px";
-		form.style.height = "0px";
-		document.body.appendChild(form);
-	}
-		var form_upload = Element('form_upload');
-		if (form_upload == null)
-			form_upload = document.createElement("DIV");
-		form_upload.id = "form_upload";
-		form_upload.style.position = "absolute";
-		form_upload.style.top = "5px";
-		form_upload.style.left = "5px";
-		form_upload.name = get_lang("Upload File");
-		form_upload.style.width = "450px";
-		form_upload.style.height = "75px";
-		form_upload.innerHTML = get_lang('Select the desired image file')+':<br>'+
-		'<input name="image_at" maxlength="255" size="40" id="inputFile_img" type="file"><br>' +
-		'<input title="' + get_lang('Include') + '"  value="' + get_lang('Include') + '"' + 
-                'type="button" onclick="RichTextEditor.addInputFile();">&nbsp;' +
-		'<input title="' + get_lang('Close') + '"  value="' + get_lang('Close') + '"' +
-		' type="button" onclick="win.close()">';
-		form.appendChild(form_upload);
-		
-		this.showWindow(form);
-}
-cRichTextEditor.prototype.showWindow = function (div){
-
-		if(! div) {
-			return;
-		}
-		
-		if(! this.emwindow[div.id]) {
-			div.style.width  =  div.firstChild.style.width;
-			div.style.height = div.firstChild.style.height;
-			div.style.zIndex = "10000";			
-			var title = div.firstChild.name;
-			var wHeight = div.offsetHeight + "px";
-			var wWidth =  div.offsetWidth   + "px";
-			div.style.width = div.offsetWidth - 5;
-
-			win = new dJSWin({
-				id: 'win_'+div.id,
-				content_id: div.id,
-				width: wWidth,
-				height: wHeight,
-				title_color: '#3978d6',
-				bg_color: '#eee',
-				title: title,
-				title_text_color: 'white',
-				button_x_img: '../phpgwapi/images/winclose.gif',
-				border: true});
-			
-			this.emwindow[div.id] = win;
-			win.draw();
-		}
-		else
-			win = this.emwindow[div.id];
-		win.open();	
-}
-cRichTextEditor.prototype.addInputFile = function()
-{
-	//Begin: Verify if the image extension is allowed.
-	var imgExtensions = new Array("jpeg", "jpg", "gif", "png", "bmp", "xbm", "tiff", "pcx");
-	var inputFile = document.getElementById('inputFile_img');	
-	if(!inputFile.value) return false;
-	var fileExtension = inputFile.value.split(".");
-	fileExtension = fileExtension[(fileExtension.length-1)];
-	var deniedExtension = true;
-	for(var i=0; i<imgExtensions.length; i++) {
-		if(imgExtensions[i].toUpperCase() == fileExtension.toUpperCase()) {
-			deniedExtension = false;
-			break;
-		}
-	}
-	if(deniedExtension) {
-		alert(get_lang('File extension forbidden or invalid file') + '.');
-		return false;
-	}
-	// End: Verify image extension.
-        var id =  currentTab;
-	divFiles = document.getElementById("divFiles_"+id);
-	var countDivFiles = divFiles.childNodes.length + 1;
-
-	var divFiles = document.getElementById('divFiles_'+id);
-	inputFile.id = 'inputFile_'+id +"_"+countDivFiles;
-	inputFile.name = 'file_'+countDivFiles;
-	divFile = document.createElement('DIV');
-	divFile.appendChild(inputFile);
-	divFiles.appendChild(divFile);
-
-	var form_upload = document.getElementById('form_upload');
-	form_upload.parentNode.removeChild(form_upload);
-	win.close();
-
-	RichTextEditor.saveFlag = 0; // See if save function finished
-	var save_link = document.getElementById("save_message_options_"+id);
-	save_link.onclick = function () {};
-        this.newImageId = new Date().getTime();
-        CKEDITOR.instances['body_'+id].insertHtml('<img id="'+this.newImageId+'" src=""/>');
-	save_msg(id,true);
-}
+
 
 cRichTextEditor.prototype.execPosInstance = function(inst) {
