<?php

if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * 
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 * *******************************************************************************/
/*********************************************************************************

 * Description:
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
 * Reserved. Contributor(s): ______________________________________..
 *********************************************************************************/
ob_start();
$_REQUEST['description']=$_REQUEST['description_html'];
$temp_desc=$_REQUEST['description'];
//print_r($_REQUEST);
$assigned_ids = array();
if(isset($_REQUEST['assigned_ids']) && is_array($_REQUEST['assigned_ids'])) {
	foreach($_REQUEST['assigned_ids'] as $value) $assigned_ids[] = explode(":|:", $value);
}

$data = array();
if(isset($_REQUEST['data']) && $_REQUEST['data'] != '') {
	$data = unserialize(base64_decode($_REQUEST['data']));
}
require_once('modules/EcmEmails/EcmEmailsDataFormatter.php');
$eedf = new EcmEmailsDataFormatter($data);

if(isset($_REQUEST['description']) && $_REQUEST['description'] != '') {

	$mfp = $eedf->loadMFP();
	if($mfp != null) {
		$_REQUEST['description'] = $mfp->parseText($_REQUEST['description']);
		$_REQUEST['name'] = $mfp->parseText($_REQUEST['name']);
		$_POST['description'] = $_REQUEST['description'];
		$_POST['name'] = $_REQUEST['name'];
	}
}


$user_attachment = array();
if(isset($_REQUEST['user_attachment']) && is_array($_REQUEST['user_attachment'])) {
	
	$user_attachment_tmp = $_REQUEST['user_attachment'];
	if(isset($_REQUEST['user_remove_attachment']) && is_array($_REQUEST['user_remove_attachment']))
		$user_attachment_tmp = array_diff($user_attachment_tmp, $_REQUEST['user_remove_attachment']);
		
	$user_attachment = $user_attachment_tmp;
}

require_once('modules/Emails/Email.php');


///////////////////////////////////////////////////////////////////////////////
////	EMAIL SEND/SAVE SETUP
$focus = new Email();

if(!isset($prefix)) {
	$prefix = '';
}
if(isset($_POST[$prefix.'meridiem']) && !empty($_POST[$prefix.'meridiem'])) {
	$_POST[$prefix.'time_start'] = $timedate->merge_time_meridiem($_POST[$prefix.'time_start'], $timedate->get_time_format(true), $_POST[$prefix.'meridiem']);
}
//retrieve the record
if(isset($_POST['record']) && !empty($_POST['record'])) {
	$focus->retrieve($_POST['record']);

}
if(isset($_REQUEST['user_id'])) {
	$focus->assigned_user_id = $_REQUEST['user_id'];	
}
if(!$focus->ACLAccess('Save')){
		ACLController::displayNoAccess(true);
		sugar_cleanup(true);
}
if(!empty($_POST['assigned_user_id']) && ($focus->assigned_user_id != $_POST['assigned_user_id']) && ($_POST['assigned_user_id'] != $current_user->id)) {
	$check_notify = TRUE;
}
//populate the fields of this Email
$allfields = array_merge($focus->column_fields, $focus->additional_column_fields);
foreach($allfields as $field) {
	if(isset($_POST[$field])) {
		$value = $_POST[$field];
		$focus->$field = $value;
	}
}
if (!isset($_REQUEST['to_addrs'])) {
	$_REQUEST['to_addrs'] = "";
}
if (!isset($_REQUEST['to_addrs_ids'])) {
	$_REQUEST['to_addrs_ids'] = "";
}
if (!isset($_REQUEST['to_addrs_names'])) {
	$_REQUEST['to_addrs_names'] = "";
}
if (!isset($_REQUEST['to_addrs_emails'])) {
	$_REQUEST['to_addrs_emails'] = "";
}






//GROUP ACCOUNTS SENDING//
$cacc=$_REQUEST['accounts_count'];
//if($cacc>0){
$i=0;
	while($i!=$cacc){
		$i++;
		//account
		$acc_id=$_REQUEST['account_id_'.$i];
		if($_REQUEST['account_name_'.$i])$acc[$acc_id]['name']=$_REQUEST['account_name_'.$i];
		else continue;
		
		$j=-1;
		while($j!=100){
			$j++;
			if($_REQUEST['account_email_check_'.$i.'_'.$j]){
				$acc[$acc_id]['addrs'][]=$_REQUEST['account_email_check_'.$i.'_'.$j];
				$em.=$_REQUEST['account_email_check_'.$i.'_'.$j]."; ";
			}
		}
		//cnt
		$j=-1;
		while($j!=100){
			$j++;
			$cnt_id=$_REQUEST['contact_id_'.$i.'_'.$j];
			if($_REQUEST['contact_name_'.$i.'_'.$j] && $_REQUEST['contact_id_'.$i.'_'.$j]){
				$cnt[$cnt_id]['name']=$_REQUEST['contact_name_'.$i.'_'.$j];
				$n=1;
				while($n!=100){
					$n++;
					if($_REQUEST['contact_email_check_'.$i.'_'.$j.'_'.$n]){
						$cnt[$cnt_id]['addrs'][]=$_REQUEST['contact_email_check_'.$i.'_'.$j.'_'.$n];
						$em.=$_REQUEST['contact_email_check_'.$i.'_'.$j.'_'.$n]."; ";
					}			
				}
			}
		}
		//acc
		$j=-1;
		while($j!=100){
			$j++;
			$ac_id=$_REQUEST['acc_id_'.$i.'_'.$j];
			if($_REQUEST['acc_name_'.$i.'_'.$j] && $_REQUEST['acc_id_'.$i.'_'.$j]){
				$ac[$ac_id]['name']=$_REQUEST['acc_name_'.$i.'_'.$j];
				$n=1;
				while($n!=100){
					$n++;
					if($_REQUEST['acc_email_check_'.$i.'_'.$j.'_'.$n]){
						$ac[$ac_id]['addrs'][]=$_REQUEST['acc_email_check_'.$i.'_'.$j.'_'.$n];
						$em.=$_REQUEST['acc_email_check_'.$i.'_'.$j.'_'.$n]."; ";
					}		
				}
			}
		}		
		$acc[$acc_id]['contacts']=$cnt;
		$acc[$acc_id]['accounts']=$ac;
	}

//}
/*print_r($_REQUEST);
print '<br>'.'acc_email_'.$i.'_'.$j.'_'.$n;
print_r($acc);
print $em."<br>";
die();*/
$_REQUEST['to_addrs'].="; ".$em;
$_REQUEST['to_addrs_emails'].="; ".$em;
$_REQUEST['to_addrs_ids'].="; ".$emids;
$_REQUEST['to_addrs_namess'].="; ".$emids;

//////////////////////////



if($_REQUEST['group']){
	//foreach($_REQUEST['group'] as $gr){
		$w=$GLOBALS['db']->query("select account_id from ecmemailgroups_accounts where ecmemailgroup_id='".$_REQUEST['group']."' and deleted='0'");
		while($r=$GLOBALS['db']->fetchByAssoc($w)){
			$rr=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query(
			"select email_addresses.email_address as addr
			from 
			email_addr_bean_rel 
			inner join email_addresses 
			on email_addresses.id=email_addr_bean_rel.email_address_id 
			where 
			email_addr_bean_rel.bean_module='Accounts' and 
			email_addr_bean_rel.bean_id='".$r['account_id']."' and 
			email_addr_bean_rel.deleted='0' and 
			email_addresses.deleted='0'"));
			if($rr['addr']){
				$em.=$rr['addr']."; ";
				$emids.=$r['account_id']."; ";
				$rrr=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select name from accounts where id='".$r['account_id']."'"));
				$emnames.=$rrr['name']."; ";
			}
		}
		
		$w=$GLOBALS['db']->query("select contact_id from ecmemailgroups_contacts where ecmemailgroup_id='".$_REQUEST['group']."' and deleted='0'");
		while($r=$GLOBALS['db']->fetchByAssoc($w)){
			$rr=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query(
			"select email_addresses.email_address as addr
			from 
			email_addr_bean_rel 
			inner join email_addresses 
			on email_addresses.id=email_addr_bean_rel.email_address_id 
			where 
			email_addr_bean_rel.bean_module='Contacts' and 
			email_addr_bean_rel.bean_id='".$r['contact_id']."' and 
			email_addr_bean_rel.deleted='0' and 
			email_addresses.deleted='0'"));
			if($rr['addr']){
				$em.=$rr['addr']."; ";
				$emids.=$r['contact_id']."; ";
				$rrr=$GLOBALS['db']->fetchByAssoc($GLOBALS['db']->query("select first_name,last_name from contacts where id='".$r['contact_id']."'"));
				$emnames.=$rrr['first_name']." ".$rrr['last_name']."; ";
			}
		}
	//}
$_REQUEST['to_addrs'].="; ".$em;
$_REQUEST['to_addrs_emails'].="; ".$em;
$_REQUEST['to_addrs_ids'].="; ".$emids;
$_REQUEST['to_addrs_namess'].="; ".$emids;
}

//compare the 3 fields and return list of contact_ids to link:
$focus->to_addrs_arr = $focus->parse_addrs($_REQUEST['to_addrs'], $_REQUEST['to_addrs_ids'], $_REQUEST['to_addrs_names'], $_REQUEST['to_addrs_emails']);

// make sure the cc_* and bcc_* fields are at least empty if not set
$fields_to_check = array(
	'cc_addrs',
	'cc_addrs_ids',
	'bcc_addrs',
	'bcc_addrs_ids',
	'cc_addrs_names',
	'cc_addrs_emails',
	'bcc_addrs_emails',
);
foreach ($fields_to_check as $field_to_check) {
	if (!isset($_REQUEST[$field_to_check])) {
		$_REQUEST[$field_to_check] = '';
	}
}

$focus->cc_addrs_arr = $focus->parse_addrs($_REQUEST['cc_addrs'], $_REQUEST['cc_addrs_ids'], $_REQUEST['cc_addrs_names'], $_REQUEST['cc_addrs_emails']);
$focus->bcc_addrs_arr = $focus->parse_addrs($_REQUEST['bcc_addrs'], $_REQUEST['bcc_addrs_ids'], $_REQUEST['to_addrs_names'], $_REQUEST['bcc_addrs_emails']);


if(!empty($_REQUEST['type'])) {
	$focus->type = $_REQUEST['type'];
} elseif(empty($focus->type)) { // cn: from drafts/quotes
	$focus->type = 'archived';
}

///////////////////////////////////////////////////////////////////////////////
////	TEMPLATE PARSING
// cn: bug 7244 - need to pass an empty bean to parse email templates
$object_arr = array();
if(!empty($focus->parent_id)) {
	$object_arr[$focus->parent_type] = $focus->parent_id;
}
if(isset($focus->to_addrs_arr[0]['contact_id'])) {
	$object_arr['Contacts'] = $focus->to_addrs_arr[0]['contact_id'];
}
if(empty($object_arr)) {
	$object_arr = array('Contacts' => '123');
}

// do not parse email templates if the email is being saved as draft....

if($focus->type != 'draft' && count($object_arr) > 0) {
	require_once($beanFiles['EmailTemplate']);
	$focus->name = EmailTemplate::parse_template($focus->name, $object_arr);
	$focus->description = EmailTemplate::parse_template($focus->description, $object_arr);
	$focus->description_html = EmailTemplate::parse_template($focus->description_html, $object_arr);
}
//if(!$focus->description)$focus->description=$temp_desc;
//if(!$focus->description_html)$focus->description_html=$temp_desc;
//echo $focus->description_html." ".$focus->description;die();
////	END TEMPLATE PARSING
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
////	PREP FOR ATTACHMENTS
if(empty($focus->id)){
    $focus->id = create_guid();
    $focus->new_with_id = true;
}
//print_r($_POST);die();
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
////	ATTACHMENT HANDLING
$focus->handleAttachments();
/*
var_dump($focus->parent_id);
var_dump($focus->saved_attachments[0]->name);
var_dump($focus->saved_attachments[0]->parent_name);
*/
//var_dump($focus->saved_attachments[0]->file);
//die();

	//foreach($user_attachment as $att) {
		
		$user_notes = $eedf->getAttachmentsNotes($user_attachment, $focus->name, $focus->module_dir, $focus->id);	
		if(is_array($user_notes) && count($user_notes) > 0) 
			foreach($user_notes as $un) 
				$focus->saved_attachments[] = $un;
/*
		require_once('modules/Notes/Note.php');
		$n = new Note();
		$n->name = $mod_strings['LBL_EMAIL_ATTACHMENT'].': '.$att[0];
		$n->filename = $att[0];
		$n->file_mime_type = 'application/pdf';
		$n->parent_id = $focus->id;
		$n->parent_type = $focus->module_dir;
		$n->parent_name = $focus->name;
		$nid = $n->save();		
		
		var_dump($att[1]); die();
		if(!copy($att[1], $sugar_config['upload_dir'].$nid)) {
			//$errors= error_get_last(); echo "COPY ERROR: ".$errors['type']; echo "<br />\n".$errors['message'];
		}
*/
		//$focus->saved_attachments[] = $n;
//	}
 
 /*
 	foreach($user_attachment as $att) {
		
		$user_notes = $eedf->getAttachmentNotes($focus->name, $focus->module_dir, $focus->id);	
		require_once('modules/Notes/Note.php');
		$n = new Note();
		$n->name = $mod_strings['LBL_EMAIL_ATTACHMENT'].': '.$att[0];
		$n->filename = $att[0];
		$n->file_mime_type = 'application/pdf';
		$n->parent_id = $focus->id;
		$n->parent_type = $focus->module_dir;
		$n->parent_name = $focus->name;
		$nid = $n->save();		
		
		var_dump($att[1]); die();
		if(!copy($att[1], $sugar_config['upload_dir'].$nid)) {
			//$errors= error_get_last(); echo "COPY ERROR: ".$errors['type']; echo "<br />\n".$errors['message'];
		}
		$focus->saved_attachments[] = $n;
	}
*/
  
  /*
  if(isset($_REQUEST['quote_id']) && $_REQUEST['quote_id'] != '') {
    require_once('modules/EcmQuotes/EcmQuote.php');
    $off = new EcmQuote();
    $off->retrieve($_REQUEST['quote_id']);
    $off->formatNumber();
    
    if(isset($off->id) && $off->id != '') {
      require_once('modules/Notes/Note.php');
      $n = new Note();
      $n->name = $mod_strings['LBL_EMAIL_ATTACHMENT'].': '.$off->createPdfFileName(false);
      $n->filename = $off->createPdfFileName();
      $n->file_mime_type = 'application/pdf';
      $n->parent_id = $focus->id;
      $n->parent_type = $focus->module_dir;
      $n->parent_name = $focus->name;
      $nid = $n->save();
      //var_dump($sugar_config['upload_dir'].'oferta.pdf'); die();
      //echo $off->name; die();
      //global $sugar_config;
      if($nid) $off->getPDF(null,'F',$sugar_config['upload_dir'].$nid);
      $focus->saved_attachments[] = $n;      
    }
  
    $off->setTemplate();
    $off->loadParser();
    $focus->name = $off->template->mfp->parseText($focus->name);
    $focus->description = $off->template->mfp->parseText($focus->description);
    $focus->description_html = $off->template->mfp->parseText($focus->description_html);
  }
*/




////	END ATTACHMENT HANDLING
///////////////////////////////////////////////////////////////////////////////
$focus->status = 'draft';
//echo '<pre>';print_r($focus);echo '</pre>';
$_REQUEST['send']=1;
if($focus->type == 'archived' ) {
	$focus->status= 'archived';
} 
elseif(($focus->type == 'out' || $focus->type == 'forward')) {

	///////////////////////////////////////////////////////////////////////////
	////	REPLY PROCESSING
	$old = array('&lt;','&gt;');
	$new = array('<','>');

	if($_REQUEST['from_addr'] != $_REQUEST['from_addr_name'].' &lt;'.$_REQUEST['from_addr_email'].'&gt;') {
		if(false === strpos($_REQUEST['from_addr'], '&lt;')) { // we have an email only?
			$focus->from_addr = $_REQUEST['from_addr'];
			$focus->from_name = '';
		} else { // we have a compound string
			$newFromAddr =  str_replace($old, $new, $_REQUEST['from_addr']);
			$focus->from_addr = substr($newFromAddr, (1 + strpos($newFromAddr, '<')), (strpos($newFromAddr, '>') - strpos($newFromAddr, '<')) -1 );
			$focus->from_name = substr($newFromAddr, 0, (strpos($newFromAddr, '<') -1));
		}
	} elseif(!empty($_REQUEST['from_addr_email']) && isset($_REQUEST['from_addr_email'])) {
		$focus->from_addr = $_REQUEST['from_addr_email'];
		$focus->from_name = $_REQUEST['from_addr_name'];
	} else {
		$focus->from_addr = $focus->getSystemDefaultEmail();
		//echo $focus->from_addr;
	}
	////	REPLY PROCESSING
	///////////////////////////////////////////////////////////////////////////
	
	$expl=explode("&lt;",$_REQUEST['from_addr']);
	$exppp=explode("&gt;",$expl[1]);
			$focus->from_addr = trim($exppp[0]);
			$focus->from_name = trim($expl[0]);
			//echo "addr: (".$focus->from_addr.") name: (".$focus->from_name.") all: ".$_REQUEST['from_addr'];
			$focus->reply_to_addr=$focus->from_addr;
			
	if($focus->send()) {
        $focus->status = 'sent';
		$eerr=$focus->ErrorInfo;
	} else {
	//echo "err";
		$focus->status = 'send_error';
		$eerr=$focus->ErrorInfo;echo $focus->ErrorInfo;
	}
	//echo $eerr;die();
}


			
// delete the existing relationship of all the email addresses with this email
$query = "update emails_email_addr_rel set deleted = 1 WHERE email_id = '{$focus->id}'";
$focus->db->query($query);		

// delete al the relationship of this email with all the beans
$query = "update emails_beans set deleted = 1, bean_id = '', bean_module = '' WHERE email_id = '{$focus->id}'";
$focus->db->query($query);


//relations add//


if(count($acc)>0){
	foreach($acc as $key=>$value){
		$GLOBALS['db']->query("insert into emails_beans(id,email_id,bean_id,bean_module,date_modified,deleted) 
		values('".create_guid()."','".$focus->id."','".$key."','Accounts','".date("Y-m-d H:i:s")."','0')");
	}
}
if(count($cnt)>0){
	foreach($cnt as $key=>$value){
		$GLOBALS['db']->query("insert into emails_beans(id,email_id,bean_id,bean_module,date_modified,deleted) 
		values('".create_guid()."','".$focus->id."','".$key."','Contacts','".date("Y-m-d H:i:s")."','0')");
	}
}
if(count($ac)>0){
	foreach($ac as $key=>$value){
		$GLOBALS['db']->query("insert into emails_beans(id,email_id,bean_id,bean_module,date_modified,deleted) 
		values('".create_guid()."','".$focus->id."','".$key."','Accounts','".date("Y-m-d H:i:s")."','0')");
	}
}
///////////////////////////////


if(isset($_REQUEST['object_type']) && !empty($_REQUEST['object_type']) && isset($_REQUEST['object_id']) && !empty($_REQUEST['object_id'])) {
    //run linking code only if the object_id has not been linked as part of the contacts above
    $GLOBALS['log']->debug("CESELY".$_REQUEST['object_type']);
    if(!in_array($_REQUEST['object_id'],$exContactIds)){
        $rel = strtolower($_REQUEST['object_type']);
        $focus->load_relationship($rel);
        $focus->$rel->add($_REQUEST['object_id']);
        $GLOBALS['log']->debug("CESELY LOADED".$_REQUEST['object_type']);
    }
}
//// handle legacy parent_id/parent_type relationship calls
elseif(isset($_REQUEST['parent_type']) && !empty($_REQUEST['parent_type']) && isset($_REQUEST['parent_id']) && !empty($_REQUEST['parent_id'])) {
    //run linking code only if the object_id has not been linked as part of the contacts above
    if(!isset($exContactIds) || !in_array($_REQUEST['parent_id'],$exContactIds)){
        $rel = strtolower($_REQUEST['parent_type']);
        $focus->load_relationship($rel);
        $focus->$rel->add($_REQUEST['parent_id']);
    }
}
////    END RELATIONSHIP LINKING
///////////////////////////////////////////////////////////////////////////////

// If came from email archiving edit view, this would have been set from form input.
if (!isset($focus->date_start))
{
	$today = gmdate('Y-m-d H:i:s');
	$focus->date_start = $timedate->to_display_date($today);
	$focus->time_start = $timedate->to_display_time($today, true);
}

$focus->date_sent = "";
$focus->save(false);
$GLOBALS['db']->query("update emails_text set from_addr='".$_REQUEST['from_addr']."',to_addrs='".$_REQUEST['to_addrs']."' where email_id='".$focus->id."'");
////	END EMAIL SAVE/SEND SETUP
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
////	RELATIONSHIP LINKING
if(isset($data)) {
	$eedf->saveEmailRelationToAssignedIds($focus->id);
}
$focus->load_relationship('users');
$focus->users->add($current_user->id);

if(!empty($_REQUEST['to_addrs_ids'])) {
	$focus->load_relationship('contacts');
	$exContactIds = explode(';', $_REQUEST['to_addrs_ids']);
	foreach($exContactIds as $contactId) {
		$contactId = trim($contactId);
		$focus->contacts->add($contactId);
	}
}


$out1 = ob_get_contents();
ob_end_clean();

if(isset($_REQUEST['to_pdf']) && ($_REQUEST['to_pdf'] == '1' || $_REQUEST['to_pdf'] == 'true')) {
	echo '
		<script language="javascript" src="include/ECM/EcmPreviewPDF/EcmPreviewPDF.js"></script>
		<script language="javascript">
			alert(\'Email Sent'.$eerr.'\');
			DisplayOtherIframe(true);
			parent.document.getElementById("PreviewPDF_div").style.display="none";
		</script>
	';
	die();
}


//header("Location: index.php?action=EditView&module=EcmEmails".((isset($_REQUEST['to_pdf']) && ($_REQUEST['to_pdf'] == '1' || $_REQUEST['to_pdf'] == 'true'))?'&to_pdf=1':''));
die();
echo "Email Wyslany!"; 
echo $focus->status;
die();


///////////////////////////////////////////////////////////////////////////////
////	PAGE REDIRECTION
///////////////////////////////////////////////////////////////////////////////
$return_id = $focus->id;

if(empty($_POST['return_module'])) {
	$return_module = "EcmEmails";
} else {
	$return_module = $_POST['return_module'];
}
if(empty($_POST['return_action'])) {
	$return_action = "DetailView";
} else {
	$return_action = $_POST['return_action'];
}
$GLOBALS['log']->debug("Saved record with id of ".$return_id);
require_once('include/formbase.php');
if($focus->type == 'draft') {
	if($return_module == 'EcmEmails') {
		header("Location: index.php?module=$return_module&action=ListViewDrafts");
	} else {
		handleRedirect($return_id, 'EcmEmails');
	}
} elseif($focus->type == 'out') {
	if($return_module == 'Home') {
		header('Location: index.php?module='.$return_module.'&action=index');
	}
	if(!empty($_REQUEST['return_id'])) {
		$return_id = $_REQUEST['return_id'];
	}
	header('Location: index.php?action='.$return_action.'&module='.$return_module.'&record='.$return_id.'&assigned_user_id='.$current_user->id.'&type=inbound');
} elseif(isset($_POST['return_id']) && $_POST['return_id'] != "") {
	$return_id = $_POST['return_id'];
}
	header("Location: index.php?action=$return_action&module=$return_module&record=$return_id");
?>
