<?php
//=====================================================//
//
// ! YABDAB - FORMLOOM  v. %fl-version%
// - edited: 05-17-2011 09:01:53 AM
// - author: Mike Yrabedra
// - (c)2011 Yabdab Inc. All rights reserved.
//
// - Portions of this script were carried over from the RapidWeaver Contact plugin
// - with expressed permission from RealMac Software. Thanks Dan! :-)
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
//  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
//  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
//  THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
//  OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
//  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
//  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//=====================================================//

//=====================================================//
// ! - REQUIREMENTS
//=====================================================//

// ! -- START SESSION
session_start();

// ! -- PHP 5 CHECK
$php_version = phpversion();
if( $php_version < 5 ){
	$error .= "<p><strong>FormLoom Requires PHP Version 5 or better</strong><br />".PHP_EOL;
	$error .= "The server this script is hosted on is using PHP Version $php_version.<br />".PHP_EOL;
	$error .= "Upgrade your server to PHP5 and try again.</p>".PHP_EOL;
	die($error);	
}


// ! -- PHP SESSION CHECK
if( $_SESSION['text_value'] != "makesuresessionsareenabled" ){
	$error .= "<p><strong>FormLoom Requires PHP Sessions to be enabled.</strong><br />".PHP_EOL;
	$error .= "The server this script is hosted on appears to have PHP Sessions disabled.<br />".PHP_EOL;
	$error .= "Please make sure PHP Sessions are enabled and try again.<br />".PHP_EOL;
	$error .= "You will need to contact your web host, not Yabdab.</p>".PHP_EOL;
	die($error);	
}

// Uncomment for more in-depth debugging
//error_reporting(E_ALL ^ E_NOTICE);
//ini_set('display_errors', '1');

$debug_enabled = %debug-enabled%; // true or false

// ! -- LOAD REQUIRED CLASSES
require_once('recaptchalib.php'); // include reCAPTCHA lib
require_once('ydfl_browser.php'); // include browser sniffer lib
require_once('class.phpmailer.php'); // phpMailer 5.1
require_once('class.smtp.php'); // phpMailer SMTP Class

// We use our own custom function to handle errors.
// Only used is debug is enabled.
if($debug_enabled){
	set_error_handler('YDFLErrorHandler');
}


//=============================================================//
// ! - CONFIGURE SETTINGS
//=============================================================//

// ! -- GENERAL

$fl = array(); // to hold all of our settings variables

$fl['login_required'] = %login_required%; // true or false
$fl['user_logins'] = array(%user-logins%);

//array of fields in form. (In the format "field_name" => "field_label")
%form-fields%

$fl['subject_item'] = '%subject-field%';
$fl['reply_to_name'] = '%reply-to-name%';
$fl['reply_to_email'] = '%reply-to-email%';

$fl['from_email'] = '%from-email%';
$fl['from_name'] = '%from-name%';
$fl['date'] = date('r');
$fl['encoding_method'] = '%email-encoding%'; // base64, 7bit, 8bit
$fl['encoding_charset'] = '%email-charset%';
$fl['notify_enabled'] = %notify-enabled% ; // email admin_email any errors
$fl['notify_email'] = '%notify-email%' ; // email admin_email any errors
$fl['word_wrap'] = "50";
$fl['success_redirect']	= %success-redirect%; // true or false
$fl['success_url'] = '%success-url%';
$fl['error_redirect'] = %error-redirect%; // true or false
$fl['error_url'] = '%error-url%';
$fl['mixed_boundary'] = 'YDFL_MIX_'.md5(mt_rand()).'_'; //set mime boundry. Needed to send the email. Mixed seperates text from attachments.
$fl['alt_boundary'] = 'YDFL_ALT_'.md5(mt_rand()).'_'; //alt seperates html from plain text.

$browser = new Browser(); // set instance of browser class
$fl['browser'] = $browser->getBrowser().' v.'.$browser->getVersion(). ' ('.$browser->getPlatform().')';
$fl['ip_address'] = $_SERVER['REMOTE_ADDR'];
$fl['parent_page'] = $_SERVER['HTTP_REFERER'];

// ! -- RECEIPT
$fl['send_receipt'] = %send-receipt%; // true or false
$fl['send_receipt_files']	= %send-receipt-files%; // true or false
$fl['receipt'] = array( array('name' => $_POST['form']['%reply-to-name%'],'email' => $_POST['form']['%reply-to-email%'])); // Send Receipt(s) to...
$fl['receipt_files'] = array(%receipt-files%); // Receipt Files
$fl['receipt_prefix'] = '%receipt-prefix%'; // precedes the receipt email subject

// ! -- RECIPIENTS
$fl['to'] = array(%recipients-to%); // To
$fl['cc'] = array(%recipients-cc%); // Cc
$fl['bcc'] = array(%recipients-bcc%); // Bcc
$fl['reply'] = array(%recipients-replyto%); // Reply-To

// not available yet...
$fl['read_receipt'] = false; // was the email opened?
$fl['read'] = array(); // Disposition-Notification-To
			
// ! --SECURITY 	
$fl['allowed_file_types'] = "%allowed-file-types%";
$fl['use_captcha'] = "%captcha-test%";
$fl['reCaptchaPublicKey'] = '%recaptcha-public-key%';
$fl['reCaptchaPrivateKey'] = '%recaptcha-private-key%';
$fl['maxAttachmentSize'] = %max-attachment-size%;
$fl['maxAttachmentSizeInBytes'] = $fl['maxAttachmentSize'] * 1024; // Covert KB to bytes value
$fl['email_filter_regexp'] = '/\r|\n|to:|cc:|bcc:|%field-filter-list%/i';

// ! -- ERROR MESSAGES
$fl['success_message'] = '%success-message%';
$fl['captcha_failed'] = '%captcha-failed%';
$fl['file_too_big'] = '%file-too-big%';
$fl['file_not_allowed'] = '%file-not-allowed%';
$fl['error_message'] = '%error-message%';
$fl['required_fields_alert'] = '%required-fields-alert%';
$fl['invalid_login'] = '%invalid-login%';

// ! -- MySQL PREFS
$fl['save_to_mysql'] =  %save-to-mysql%; // true or false
$fl['mysql_host'] = '%mysql-host-name%';
$fl['mysql_db'] = '%mysql-database-name%';
$fl['mysql_user'] = '%mysql-user-name%';
$fl['mysql_password'] = '%mysql-password%';
$fl['mysql_table'] = '%mysql-table%';

// ! -- PHPMAILER GROUNDWORK
$use_phpmailer =  %use-phpmailer%;
$use_phpmailer_smtp =  %use-phpmailer-smtp%;
$fl['smtp_host'] = '%smtp-host%';
$fl['smtp_port'] = '%smtp-port%';
$fl['smtp_auth'] = %smtp-auth%; // (bool)
$fl['smtp_username'] = '%smtp-username%';
$fl['smtp_password'] = '%smtp-password%';
$fl['smtp_debug'] = '1';
$fl['smtp_secure'] = %smtp-secure%; // (bool)
$fl['smtp_secure_prefix'] = '%smtp-secure-prefix%';

//for windows users.
if ($fl['windows_server'] === true) {
	ini_set('sendmail_from', $fl['from_email']);
}


//=====================================================//
// ! - SECURITY CHECKS
//=====================================================//

// ! -- TEST FORM TOKEN
// Check key variable from form against session key.
if ( ! isset($_POST['security_token']) || $_POST['security_token'] !== $_SESSION['security_token']) {
	// Set a fixed error message if the keys don't match.
	YDFLRedirect( $fl['parent_page'], 'We cannot verify that you are trying to send an email from this form. Please try again.' );
}


// ! USER LOGIN
if( $fl['login_required'] && !$_SESSION['logged_in'] )
{	
	if( YDFLValidateUserLogin($_POST['fl_username'], $_POST['fl_password']) )
	{
		$_SESSION['logged_in'] = true;
		YDFLRedirect($fl['parent_page'], "", "login-good");
	}else{
		$_SESSION['logged_in'] = false;
		YDFLRedirect($fl['parent_page'], $fl['invalid_login'], "login-fail");
	}
}


// SPAM checking. If the "comment" form field has been filled out,
// send back to form asking to remove content and exit the script.
if ($_POST['comment']) {
	YDFLRedirect( $fl['parent_page'], 'Please remove content from the last textarea before submitting the form again. This is to protect against SPAM abuse.' );
}


//=====================================================//
// ! - CONVERT FORM FIELDS
//=====================================================//

// put everything into a SESSION var
$magic_quotes = (bool) get_magic_quotes_gpc();
foreach ($_POST['form'] as $key => $value) {
	if ($magic_quotes) {
	
		// only do this if it is NOT an array
		if(!is_array($value))
		{
			$value = stripslashes($value);
		}
	}
	$_SESSION['form'][$key] = $value;
}

//print_r($_SESSION);die;
//YDFLRedirect( $fl['parent_page'], 'tmp_error');


//=====================================================//
// ! - CAPTCHA & VALIDATION
//=====================================================//

// ! -- reCAPTCHA CHECK
# was there a reCAPTCHA response?
if(array_key_exists('recaptcha_challenge_field', $_POST))
{

	// Get a key from http://recaptcha.net/api/getkey
	$publickey = $fl['reCaptchaPublicKey'];
	$privatekey = $fl['reCaptchaPrivateKey'];

	# the response from reCAPTCHA
	$resp = null;
	# the error code from reCAPTCHA, if any
	$error = null;

    $resp = recaptcha_check_answer($privatekey,$_SERVER["REMOTE_ADDR"],$_POST['recaptcha_challenge_field'],$_POST['recaptcha_response_field']);

    if (!$resp->is_valid) {
            # set the error code so that we can display it
            $error = $resp->error;				
    }

	// send error
	if ($error) {    
		YDFLRedirect( $fl['parent_page'], $fl['captcha_failed'] );
	}

}

// ! -- VALIDATION

%validate-string%


// ! -- REPLY EMAIL VALIDATION
if(!YDFLValidateEmail($_SESSION['form'][$fl['reply_to_email']])){
	YDFLRedirect( $fl['parent_page'], "Reply Email value, \"".YDFLValue($_SESSION['form'][$fl['reply_to_email']])."\", is not a valid email address." );
}



//=====================================================//
// ! - CUSTOM CODE
//=====================================================//

%custom-code%

//=====================================================//
// ! - SAVE TO MYSQL
//=====================================================//

if($fl['save_to_mysql'] == "true"){
	
	// Connect to Database
	$s = @mysql_connect($fl['mysql_host'], $fl['mysql_user'], $fl['mysql_password']);
	$d = @mysql_select_db($fl['mysql_db'], $s);
	
	$fl['mysql_query'] = "%mysql-query%";
		
	if(!$s || !$d){ 		
		YDFLRedirect( $fl['parent_page'], "Cannot connect to database, ".$fl['mysql_db']);	
	}
	
	// Save data
	$mySQLQuery = 'INSERT INTO `'. $fl['mysql_table']. '` SET '. $fl['mysql_query'];
	$rs = @mysql_query($mySQLQuery);
	
	// Add returning MySQL errors
	
	if( mysql_errno() ){ 		
		$mysql_error= "MySQL Error: (".mysql_errno().") ".mysql_error()."<br />When executing:<br />".$mySQLQuery;
		YDFLRedirect( $fl['parent_page'], $mysql_error);	
	}

}



//=====================================================//
// ! - SETUP TEMPLATES
//=====================================================//

// ! -- EMAIL TEMPLATES
$fl['receipt_template'] = '%receipt-template%';
$fl['email_template'] = '%email-template%';


//=====================================================//
// ! - BUILD MESSAGE
//=====================================================//

if(!isset($fl['email_template']) || empty($fl['email_template']) )
{
	//Set a variable for the message content
	$html_content = "<html>".PHP_EOL."<head>".PHP_EOL."<title>" .
	                YDFLSafeEscapeString($fl['subject']) .
	                "</title>".PHP_EOL."</head>".PHP_EOL."<body>".PHP_EOL."<p>".PHP_EOL;
	                
	$html_content .= "<table><tbody>".PHP_EOL;

	//construct a plain text version of the email.
	$text_content = '';

	//build a message from the reply for both HTML and text in one loop.
	foreach ($fl['form_fields'] as $field => $label) {
		
		// no need to include button and breaks...
		if($label != 'ydfl-do-not-process'){
	
			$html_content .= '<tr><td align="right" valign="top" nowrap><b>' . strip_tags($label) . '</b></td><td> ';
			$text_content .= "$label ";
			if (isset($_FILES[$field])) {
				$string = (isset($_FILES[$field]['name'])) ? $_FILES[$field]['name'] : '';
			} else {			
				$string = YDFLValue($_SESSION['form'][$field]);
			}
			$html_content .= nl2br($string) . "</td></tr>".PHP_EOL;
			$text_content .= $string.PHP_EOL.PHP_EOL;
		
		}
		
		
	}

	//close the HTML content.
	$html_content .= "</tbody></table>".PHP_EOL;
	$html_content .= "</p>".PHP_EOL."</body>".PHP_EOL."</html>";

}else{

	$html_content = $fl['email_template'];
	$text_content = YDFLHtml2Text($html_content); // remove markup and add linebreaks

}

//Now we combine both HTML and plain text version of the email into one.
//Creating the message body which contains a Plain text version and an HTML version,
//users email client will decide which version to display
$message = PHP_EOL."--".$fl['mixed_boundary'].PHP_EOL;
$message .= "Content-Type: multipart/alternative; boundary=".$fl['alt_boundary'].PHP_EOL.PHP_EOL;
$message .= "--".$fl['alt_boundary'].PHP_EOL;
$message .= "Content-Type: text/plain; charset=".$fl['encoding_charset']."; format=flowed".PHP_EOL;
$message .= "Content-Transfer-Encoding: ".$fl['encoding_method'].PHP_EOL.PHP_EOL;
$message .= $text_content.PHP_EOL.PHP_EOL;
$message .= "--".$fl['alt_boundary'].PHP_EOL;
$message .= "Content-Type: text/html; charset=".$fl['encoding_charset'].PHP_EOL;
$message .= "Content-Transfer-Encoding: ".$fl['encoding_method'].PHP_EOL.PHP_EOL;
$message .= $html_content.PHP_EOL.PHP_EOL;
$message .= "--".$fl['alt_boundary']."--".PHP_EOL.PHP_EOL;
$message .= "--".$fl['mixed_boundary'];


//=====================================================//
// ! - ATTACHMENTS
//=====================================================//

if (isset($_FILES)) {
$files=array();
	foreach ($_FILES as $attachment) {
	
		$attachment_name = $attachment['name'];
		$attachment_size = $attachment["size"];
	  	$attachment_temp = $attachment["tmp_name"];
	  	$attachment_type = $attachment["type"];
	  	$attachment_ext  = explode('.', $attachment_name);  
	  	$attachment_ext  = $attachment_ext[count($attachment_ext)-1]; 
	  	
	  	
	  	if ( $attachment['error'] === UPLOAD_ERR_OK && is_uploaded_file($attachment['tmp_name']) ) {
	  		
	
	  		// User set filtering; size, ext, etc...
	  		if(stristr($fl['allowed_file_types'], $attachment_ext) == FALSE){ // make sure we accet this file type....
	  			YDFLRedirect( $fl['parent_page'], $fl['file_not_allowed'] );
	  		} 
	  		
	  		
	  		
	  		// See is file is not too big.
			if($attachment_size > $fl['maxAttachmentSizeInBytes']){
				YDFLRedirect( $fl['parent_page'], $fl['file_too_big'] );
			}
					
			$file = fopen($attachment_temp,'rb');
			$data = fread($file,filesize($attachment_temp));
			fclose($file);
			$data = chunk_split(base64_encode($data));
            
            $attachment_str .= PHP_EOL."Content-Type: application/octet-stream; name=\"$attachment_name\"" .PHP_EOL.
	                  "Content-Disposition: attachment; filename=\"$attachment_name\"" .PHP_EOL.
	                  "Content-Transfer-Encoding: base64".PHP_EOL.PHP_EOL.$data.PHP_EOL.PHP_EOL."--$fl[mixed_boundary]";
	                  
		// add to array for phpmailer to use...
		$files[] = array('temp'=> $attachment_temp, 'name' => $attachment_name);
	  	
	  	} else if ($attachment['error'] !== UPLOAD_ERR_NO_FILE) {
	  	
	  		// ! -- SERVER ERRORS
			switch ($attachment['error']) {
				case UPLOAD_ERR_INI_SIZE:
				case UPLOAD_ERR_FORM_SIZE:
					$error = "File $attachment_name exceeds the " . ini_get('upload_max_filesize') . 'B limit for the server.';
					break;
				case UPLOAD_ERR_PARTIAL:
					$error = "Only part of the file $attachment_name could be uploaded, please try again.";
					break;
				default:
					$error = "There has been an error attaching the file $attachment_name, please try again.";
			}
			
			YDFLRedirect( $fl['parent_page'], $error );
	  	
	  	} // file was uploaded
	  	
	  }
	  
	$attachment_str .= '--';
	  	
}



//=====================================================//
// ! - SEND MESSAGE WITH PHPMAILER (beta)
//=====================================================//

if($use_phpmailer){

	$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
	$mail->CharSet = $fl['encoding_charset'];
	$mail->Encoding = $fl['encoding_method'];
	
	if($use_phpmailer_smtp)
			$mail->IsSMTP(); // telling the class to use
	
	try {
	
		if($use_phpmailer_smtp){

				$mail->Host       = $fl['smtp_host'];	// SMTP server
				$mail->SMTPDebug  = $fl['smtp_debug'];	// enables SMTP debug information (for testing)(1,2)
														// 1 = errors and messages
														// 2 = messages only
				if($fl['smtp_secure'])
					$mail->SMTPSecure = $fl['smtp_secure_prefix'];
					
				$mail->SMTPAuth   = $fl['smtp_auth'];	// enable SMTP authentication (bool)
				$mail->Port       = $fl['smtp_port'];	// set the SMTP port
				$mail->Username   = $fl['smtp_username']; // SMTP account username
				$mail->Password   = $fl['smtp_password'];	// SMTP account password
		}
	
	// To recipients...
	foreach($fl['to'] as $to){
		$mail->AddAddress($to['email'], $to['name']);
	}
	// Cc recipients...
	foreach($fl['cc'] as $cc){
		$mail->AddCC($cc['email'], $cc['name']);
	}
	// Bcc recipients...
	foreach($fl['bcc'] as $bcc){
		$mail->AddBCC($bcc['email'], $bcc['name']);
	}
	// Reply-To recipients...
	foreach($fl['reply'] as $reply){
		$mail->AddReplyTo($reply['email'], $reply['name']);
	}
	
	  $mail->AddReplyTo($_SESSION['form'][$fl['reply_to_email']], $_SESSION['form'][$fl['reply_to_name']]);
	  $mail->SetFrom($fl['from_email'], $fl['from_name']);
	  $mail->Subject = strip_tags($_SESSION['form'][$fl['subject_item']]);
	  $mail->AltBody = $text_content; // optional - MsgHTML will create an alternate automatically
	  $mail->MsgHTML($html_content);
	  
	  if($files){
			for ( $i = 0; $i < sizeof ( $files ); $i++ )
			{
				$mail->AddAttachment($files[$i]['temp'], $files[$i]['name']);   
			}
		}

	  
	  
	  $mail->Send();
	 
	} catch (phpmailerException $e) {
		YDFLRedirect( $fl['parent_page'], $fl['error_message'].$e->errorMessage());
	} catch (Exception $e) {
		YDFLRedirect( $fl['parent_page'], $fl['error_message'].$e->getMessage());
	}



} else {

	//=====================================================//
	// ! - SEND MESSAGE 
	//=====================================================//

	$send_to = YDFLGenerateHeaderstr($fl['to']);

	// add dynamic reply address
	if($_SESSION['form'][$fl['reply_to_name']] && $_SESSION['form'][$fl['reply_to_email']])
		array_push( $fl['reply'], array('name' => $_SESSION['form'][$fl['reply_to_name']] ,'email' => $_SESSION['form'][$fl['reply_to_email']]));

	$headers = YDFLGenerateHeaders('message'); // get headers for sending to form owner

	$fifth = "-f " . $fl['from_email']; // makes sure Return-Path is user and not server

	// Combine the body parts
	$message_body = $message;
	if($attachment_str)
		$message_body = $message_body.$attachment_str;
		
		
	$subject = strip_tags($_SESSION['form'][$fl['subject_item']]);
	$subject = '=?'.$fl['encoding_charset'].'?B?'.base64_encode($subject).'?=';

	if( ini_get('safe_mode') ){
		// send without fifth parameter
		if (!@mail($send_to, $subject, $message_body, $headers)) {
			YDFLRedirect( $fl['parent_page'], $fl['error_message']."<br />Email Send Failed");
		}
	}else{
		// send with fifth parameter
		if (!@mail($send_to, $subject, $message_body, $headers, $fifth)) {
			YDFLRedirect( $fl['parent_page'], $fl['error_message']."<br />Email Send Failed");
		}
	}

}

//=====================================================//
// ! - BUILD RECEIPT
//=====================================================//

if(!isset($fl['receipt_template']) || empty($fl['receipt_template']) )
{
	//Set a variable for the message content
	$html_content = "<html>".PHP_EOL."<head>".PHP_EOL."<title>" .
	                YDFLSafeEscapeString($fl['receipt_prefix'].$_SESSION['form'][$fl['subject_item']]) .
	                "</title>".PHP_EOL."</head>".PHP_EOL."<body>".PHP_EOL."<p>".PHP_EOL;
	$html_content .= "Your email has been sent<br /><br /><b>Thank You</b>";
	//construct a plain text version of the email.
	$text_content = "Your email has been sent".PHP_EOL.PHP_EOL."Thank You";
	//close the HTML content.
	$html_content .= "</p>".PHP_EOL."</body>".PHP_EOL."</html>";

}else{

	$html_content = $fl['receipt_template'];
	$text_content = YDFLHtml2Text($html_content); // remove markup and add linebreaks

}

//Now we combine both HTML and plain text version of the email into one.
//Creating the message body which contains a Plain text version and an HTML version,
//users email client will decide which version to display

$message = PHP_EOL."--".$fl['mixed_boundary'].PHP_EOL;
$message .= "Content-Type: multipart/alternative; boundary=".$fl['alt_boundary'].PHP_EOL.PHP_EOL;
$message .= "--".$fl['alt_boundary'].PHP_EOL;
$message .= "Content-Type: text/plain; charset=".$fl['encoding_charset']."; format=flowed".PHP_EOL;
$message .= "Content-Transfer-Encoding: ".$fl['encoding_method'].PHP_EOL.PHP_EOL;
$message .= $text_content.PHP_EOL.PHP_EOL;
$message .= "--".$fl['alt_boundary'].PHP_EOL;
$message .= "Content-Type: text/html; charset=".$fl['encoding_charset'].PHP_EOL;
$message .= "Content-Transfer-Encoding: ".$fl['encoding_method'].PHP_EOL.PHP_EOL;
$message .= $html_content.PHP_EOL.PHP_EOL;
$message .= "--".$fl['alt_boundary']."--".PHP_EOL.PHP_EOL;
$message .= "--".$fl['mixed_boundary'];
	





if($fl['send_receipt'] == true){
	
//=====================================================//
// ! - SEND RECEIPT WITH PHPMAILER (beta)
//=====================================================//
	
	if($use_phpmailer){

		$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
		$mail->CharSet = $fl['encoding_charset'];
		$mail->Encoding = $fl['encoding_method'];
		
		 if($use_phpmailer_smtp)
			$mail->IsSMTP(); // telling the class to use 
		
		try {
		
		  if($use_phpmailer_smtp){

				$mail->Host       = $fl['smtp_host'];	// SMTP server
				$mail->SMTPDebug  = $fl['smtp_debug'];	// enables SMTP debug information (for testing)(1,2)
				
				if($fl['smtp_secure'])
					$mail->SMTPSecure = $fl['smtp_secure_prefix'];
					
				$mail->SMTPAuth   = $fl['smtp_auth'];	// enable SMTP authentication (bool)
				$mail->Port       = $fl['smtp_port'];	// set the SMTP port
				$mail->Username   = $fl['smtp_username']; // SMTP account username
				$mail->Password   = $fl['smtp_password'];	// SMTP account password
			}
		
		  $mail->AddAddress($_SESSION['form'][$fl['reply_to_email']], $_SESSION['form'][$fl['reply_to_name']]);
		  $mail->SetFrom($fl['from_email'], $fl['from_name']);
		  $mail->Subject = $fl['receipt_prefix'].strip_tags($_SESSION['form'][$fl['subject_item']]);
		  $mail->AltBody = $text_content; // optional - MsgHTML will create an alternate automatically
		  $mail->MsgHTML($html_content);
		  
		  if($fl['send_receipt_files'] == true ) {
				foreach ($fl['receipt_files'] as $attachment)
				{
					$mail->AddAttachment($attachment['filename'], $attachment['filename']);   
				}
			}

		  
		  
		  $mail->Send();
		  
		} catch (phpmailerException $e) {
		  YDFLRedirect( $fl['parent_page'], $fl['error_message'].$e->errorMessage());
		} catch (Exception $e) {
		  YDFLRedirect( $fl['parent_page'], $fl['error_message'].$e->getMessage());
		}



	} else {


//=====================================================//
// ! - SEND RECEIPT 
//=====================================================//


		// ! -- GET RECEIPT ATTACHMENTS
		// Any attachments to add to receipt?
		if($fl['send_receipt_files'] == true ) {
		
			foreach ($fl['receipt_files'] as $attachment) {
			
				if($attachment['filename'] != "")
				{
					$filename = $attachment['filename'];
					$file = fopen($filename,'rb');
					$data = fread($file,filesize($attachment['filename']));
					fclose($file);
					$data = chunk_split(base64_encode($data));
					
					$receipt_attachment_str .= PHP_EOL."Content-Type: application/octet-stream; name=\"$filename\"" .PHP_EOL.
							  "Content-Disposition: attachment; filename=\"$filename\"" .PHP_EOL.
							  "Content-Transfer-Encoding: base64".PHP_EOL.PHP_EOL.$data.PHP_EOL.PHP_EOL."--$fl[mixed_boundary]";
				}
			}
		
		}
		
		$receipt_attachment_str .= '--';
		
		
		$send_to = YDFLGenerateHeaderstr($fl['receipt']);
		$headers = YDFLGenerateHeaders('receipt'); // get headers for sending to form owner
		$fifth = '-f "' . $fl['from_email'].'"'; // makes sure Return-Path is user and not server
		
		// Combine the body parts
		$message_body = $message;
		if($attachment_str)
			$message_body = $message_body.$receipt_attachment_str;
			
		
		$subject = $fl['receipt_prefix'].strip_tags($_SESSION['form'][$fl['subject_item']]);
		$subject = '=?'.$fl['encoding_charset'].'?B?'.base64_encode($subject).'?=';
		
		if( ini_get('safe_mode') ){
			// send without fifth parameter
			if (!@mail($send_to, $subject, $message_body, $headers)) {
				YDFLRedirect( $fl['parent_page'], $fl['error_message']."<br />Could not Send Receipt Email.");
			}
		}else{
			// send with fifth parameter
			if (!@mail($send_to, $subject, $message_body, $headers, $fifth)) {
				YDFLRedirect( $fl['parent_page'], $fl['error_message']."<br />Could not Send Receipt Email.");
			}
		}	
		

	} 
}



//=====================================================//
// ! - SUCCESSFUL RESULT
//=====================================================//

/* If we made it this far then that means no fails and script executed without any errors... */

unset($_SESSION['form']); // reset form session
YDFLRedirect( $fl['parent_page'], $fl['success_message'], "good");



//=====================================================//
// ! - HELPER FUNCTIONS
//=====================================================//

//=====================================================//
// YDFLValidateUserLogin
//=====================================================//

function YDFLValidateUserLogin($name, $password)
{
	global $fl;	
	$users = $fl['user_logins'];
	
	for ($i = 0; $i < count($users); $i++) {
	    
	    if($name === $users[$i]['name'] && $password === $users[$i]['password'])
	    	return true;
	    
	}
	
	return false;

}

//=====================================================//
// YDFLStringCleaner
//=====================================================//

function YDFLStringCleaner($str) { 
	$str = preg_replace( '((?:\n|\r|\t|%0A|%0D|%08|%09)+)i' , '', $str );
	// Remove those slashes
	if(get_magic_quotes_gpc()){
		$str = stripslashes($str);
	}
	
	return $str;
}

//=====================================================//
// YDFLValidateEmail
//=====================================================//

function YDFLValidateEmail($email) {
   //check for all the non-printable codes in the standard ASCII set,
   //including null bytes and newlines, and exit immediately if any are found.
   if (preg_match("/[\\000-\\037]/",$email)) {
      return false;
   }
   $pattern = "/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD";
   if(!preg_match($pattern, $email)){
      return false;
   }
   return true;
} 

//=====================================================//
// YDFLRedirect
//=====================================================//

function YDFLRedirect($url, $message = NULL, $status='fail') {
	
	global $fl;
	
	if ($message) {
	
		if(is_array($message))
		{
			$message = YDFLValue($message, "<br />");
		}
	
		// notify owner?
		if( $fl['notify_enabled'] == true && $status == 'fail' || $status == "login-fail" ) {
			$headers = 'Content-type: text/plain; charset=utf-8' . PHP_EOL;
			$headers .= 'From: "'.$fl['from_name'].'" <'.$fl['from_email'].'>' . PHP_EOL;
			$notification = "FormLoom Notification:".PHP_EOL.PHP_EOL;
			$notification .= "Page: ".$_SERVER['HTTP_REFERER']. PHP_EOL.PHP_EOL;
			$notification .= "Date: ".date('r'). PHP_EOL.PHP_EOL;
			$notification .= "Error: ".PHP_EOL.PHP_EOL.$message;
			@mail($fl['notify_email'], 'FormLoom Notification', $notification, $headers);
		}
		
		switch($status){
		
			case "good":
				$display_message = "<div class=\"ydfl-good\">".PHP_EOL;
				$display_message .= $message.PHP_EOL;
				$display_message .= "</div>";
			break;
			
			case "fail":
				$display_message = "<div class=\"ydfl-fail\">".PHP_EOL;
				$display_message .= "<strong>".$fl['error_message']."</strong><br />".PHP_EOL;
				$display_message .= $message.PHP_EOL;
				$display_message .= "</div>";
			break;
			
			case "login-fail":
				$display_message = "<div class=\"ydfl-fail\">".PHP_EOL;
				$display_message .= "<strong>".$fl['error_message']."</strong><br />".PHP_EOL;
				$display_message .= $message.PHP_EOL;
				$display_message .= "</div>";
			break;
			
			case "login-good":
				$display_message = ""; // no message on successful login
			break;
			
			default:
				$display_message = "<div class=\"ydfl-fail\">".PHP_EOL;
				$display_message .= $message.PHP_EOL;
				$display_message .= "</div>";
			break;
			
		}
		
		$_SESSION['form_message'] = $display_message;
	}
	
	if($status !== "login-good" && $status != "login-fail")
	{
		// Redirect elsewhere?
		if ($fl['success_redirect'] && !empty($fl['success_url']) && $status == "good")
			$url = $fl['success_url'];
			
		if ($fl['error_redirect'] && !empty($fl['error_url']) && $status == "fail")
			$url = $fl['error_url'];
		
	}			
	
	header('Location: ' . $url);
	exit;
}

//=====================================================//
// YDFLSafeEscapeString
//=====================================================//

// Function to escape data inputted from users. This is to protect against embedding
// of malicious code being inserted into the HTML email.

function YDFLSafeEscapeString($string) {
	$str = strip_tags($string);
	$str = YDFLHTMLEntities($str);
	return $str;
}

//=====================================================//
// YDFLCheckRequiredFields
//=====================================================//

// Function to check the required fields are filled in.
function YDFLCheckRequiredFields($required_fields) {

	foreach($required_fields as $field) {
		if (( ! isset($_SESSION['form'][$field]) || empty($_SESSION['form'][$field])) &&
			( ! isset($_FILES[$field]) || empty($_FILES[$field]['name']))) {
			return false;
		}
	}
	
	return true;
}

//=====================================================//
// YDFLErrorHandler
//=====================================================//

function YDFLErrorHandler($number, $message, $file, $line, $vars) {
	
	global $fl; // make $fl array global so we can use all the vars if needed.
	
	$error_msg = "
		<p>An error ($number) occurred on line
		<strong>$line</strong> and in the <strong>file: $file.</strong>
		<p> $message </p>";

	$error_msg .= "<pre>" . print_r($vars, 1) . "</pre>";

	// Email the error to someone...
	if ( ($fl['notify_enabled'] == true) && ($number !== E_NOTICE) && ($number < 2048) )
		error_log($error_msg, 1, $fl['notify_email'], $headers);

	// The code below ensures that we only "die" if the error was more than
	// just a NOTICE.
	if ( ($number !== E_NOTICE) && ($number < 2048) ) {
		//die("There was an error. Please try again later.");
		YDFLRedirect( $fl['parent_page'], $error_msg);
	}
}

//=====================================================//
// YDFLGenerateHeaders
//=====================================================//

function YDFLGenerateHeaders($type='message'){

	global $fl; // make $fl array global so we can use all the vars if needed.
	
	$headers  = "MIME-Version: 1.0" .PHP_EOL. "Content-Type: multipart/mixed; charset=".$fl['encoding_charset']."; type=\"multipart/alternative\";" .
	            "boundary=".$fl['mixed_boundary'].PHP_EOL;

	$headers .= 'From: "'.$fl['from_name'].'" <'.$fl['from_email'].'>' . PHP_EOL;
	
	// Who is getting this email
	
	if ($type == 'message')
	{
		//$headers .= YDFLGenerateHeaderstr($fl['to'], 'To'); // disabled 03-16-2011 02:22:06 PM - MY
		
		if(is_array($fl['cc']) && count($fl['cc']) > 0){
			$headers .= YDFLGenerateHeaderstr($fl['cc'], 'Cc');
		}
		
		if(is_array($fl['bcc']) && count($fl['bcc']) > 0){
			$headers .= YDFLGenerateHeaderstr($fl['bcc'], 'Bcc');
		}
		
		if(is_array($fl['reply']) && (count($fl['reply']) > 0)){
	
			$headers .= YDFLGenerateHeaderstr($fl['reply'], 'Reply-To');
		}
		
		if(is_array($fl['read']) && ($fl['read_receipt'] == true) && (count($fl['read']) > 0)){
			$headers .= YDFLGenerateHeaderstr($fl['read'], 'Disposition-Notification-To');
			
		}
	
	}
	
	
	return $headers;
}

//=====================================================//
// YDFLGenerateHeaderstr
//=====================================================//


function YDFLGenerateHeaderstr($whom, $param =''){
	if($param == ''){ // this is normally going to be To
		if(count($whom) > 0){
			$i = 0;
			foreach($whom as $rVal){
				$i++;
				if($i == count($whom)){
					$returnHeader .= strtolower($rVal['email']);
				}else{
					$returnHeader .= strtolower($rVal['email']).', ';
				}
			}
		}
	}else{
		$returnHeader .=  $param.': ';
		if(count($whom) > 0){
			$i = 0;
			foreach($whom as $rVal){
				$i++;
				if($i == count($whom)){
					$returnHeader .= '"'.$rVal['name'].'" <'.strtolower($rVal['email']).'>'. PHP_EOL	;
				}else{
					$returnHeader .= '"'.$rVal['name'].'" <'.strtolower($rVal['email']).'>, ';
				}
			}
		}
	}
	return $returnHeader;
}


//=====================================================//
// YDFLValue
//=====================================================//

function YDFLValue($var, $sep=", "){
	
	$var = YDFLHTMLEntities($var); // encode all html tags
	
	if(is_array($var)){ 
		$str = (isset($var)) ? implode($sep, $var) : '';
	}else{
		$str = (isset($var)) ? $var : '';
	}
			
	return $str;
}

//=====================================================//
// YDFLHTMLEntities
//=====================================================//

function YDFLHTMLEntities($mixed, $quote_style = ENT_QUOTES, $charset = 'UTF-8') 
{ 
    if (is_array($mixed)) { 
        foreach($mixed as $key => $value) { 
            $mixed[$key] = YDFLHTMLEntities($value, $quote_style, $charset); 
        } 
    } elseif (is_string($mixed)) { 
        $mixed = htmlentities(html_entity_decode($mixed, $quote_style), $quote_style, $charset); 
    } 
    return $mixed; 
}

//=====================================================//
// YDFLHtml2Text
//=====================================================//

function YDFLHtml2Text($str) 
{ 
    $text_str = str_replace("<br />", PHP_EOL, $str); // convert breaks into line-breaks.
    $text_str = strip_tags($text_str); // remove all markup.
    $text_str = htmlspecialchars_decode($text_str); // convert values with special chars back to unencoded.

    return $text_str;
     
}

//=====================================================//
// !  THE END 
//=====================================================//