<?php
session_start();
//=====================================================//
//
// ! YABDAB - FORMLOOM VERSION %fl-version%
// - AUTHOR: Mike Yrabedra
// - MODIFIED: 11-28-2014 09:13:32am
// - (c)2014 Yabdab Inc. All rights reserved.
//
// - PUBLISHED: %publish-date%
//
//=====================================================//

//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
if(ini_get('date.timezone') == '') date_default_timezone_set('GMT');

//=============================================================//
// ! - ENABLE DEBUGGING
//=============================================================//

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

// Turn Errors On
if($debug_enabled) {
    if ( defined( 'E_DEPRECATED' ) ) {
        error_reporting( E_ALL & ~E_DEPRECATED & ~E_STRICT );
    }else{
        error_reporting( E_ALL );
    }
    ini_set( 'display_errors', 1 );
}else{
    ini_set( 'display_errors', 0 );
}

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

// ! -- GENERAL
$fl['plugin'] 			= true; // tell class this is formloom
$fl['debug'] 			= %debug-enabled%; // true or false
$fl['from_email'] 		= '%from-email%';
$fl['from_name'] 		= html_entity_decode('%from-name%');
$fl['subject'] 			= '%subject-field%';
$fl['reply_to_name']    = '%reply-to-name%';
$fl['reply_to_email']   = '%reply-to-email%';
$fl['receipt_template'] = '%receipt-template%';
$fl['email_template']   = '%email-template%';
$fl['email_subject_template']   = '%email-subject-template%';
$fl['receipt_subject_template']   = '%receipt-subject-template%';

// ! -- USERS
$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['notify_enabled']   = %notify-enabled% ; // email admin_email any errors
$fl['notify_email']     = '%notify-email%' ; // email admin_email any errors

// ! -- 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


$fl['date'] 					= date('r');
$fl['encoding_method'] 			= '%email-encoding%'; // base64, 7bit, 8bit
$fl['encoding_charset'] 		= '%email-charset%';
$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%';

// ! -- RECEIPT
$fl['send_receipt'] 			= %send-receipt%; // true or false
$fl['send_receipt_files']       = %send-receipt-files%; // true or false
$fl['receipt_prefix'] 			= html_entity_decode('%receipt-prefix%'); // precedes the receipt email subject
$fl['receipt_files']            = array(%receipt-files%); // Receipt Files

// ! --SECURITY 	
$fl['allowed_file_types'] 		= "%allowed-file-types%";
//$fl['use_captcha'] 			= "true"; // not used
$fl['recaptcha_public_key'] 	= '%recaptcha-public-key%';
$fl['recaptcha_private_key'] 	= '%recaptcha-private-key%';
$fl['max_attachment_size'] 		= %max-attachment-size%;
$fl['max_attachment_size_bytes'] = $fl['max_attachment_size'] * 1024; // Covert KB to bytes value
$fl['email_filter_regexp'] 		= '%field-filter-list%';
$fl['blocked_message'] 			= '%blocked-message%';
$fl['block_emails']             = array(%blocks-email%);
$fl['block_ips']                = array(%blocks-ip%);

// ! --DKIM SIGNING
$fl['dkim']						= %dkim%; // bool
$fl['dkim_domain']				= '%dkim-domain%';
$fl['dkim_privkey_path']		= realpath('%dkim-privkey-path%'); // file created and published.
$fl['dkim_selector']			= '%dkim-selector%';
$fl['dkim_passphrase']			= '%dkim-passphrase%';

// ! -- MySQL PREFS
$fl['save_to_mysql'] 			=  %save-to-mysql%; // true or false
$fl['do_not_send'] 				=  %do-not-send%; // 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%';
$fl['mysql_query']              = array( %mysql-query% ); // array of field->item values

// ! -- GOOGLE SHEEETS PREFS
$fl['save_to_google']           =  %save-to-google%; // true or false
$fl['google_email']             = '%google-email%';
$fl['google_password']          = '%google-password%';
$fl['google_worksheet']         = '%google-worksheet%';
$fl['google_spreadsheet']       = '%google-spreadsheet%';
$fl['google_query']             = array( %google-query% ); // array of column->item values

$fl['ip_field'] 				= '%ip-field%'; // leave blank to skip
$fl['browser_field'] 			= '%browser-field%'; // leave blank to skip
$fl['date_field'] 				= '%date-field%'; // leave blank to skip

// ! -- SMTP
$fl['use_smtp']					=  %use-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'] 				= '0'; // leave off for now
$fl['smtp_secure'] 				= %smtp-secure%; // (bool)
$fl['smtp_secure_prefix'] 		= '%smtp-secure-prefix%';

// ! -- MESSAGE STRINGS
$fl['error_message'] 			= '%error-message%';
$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['required_field_alert'] 	= '%required-fields-alert%';
$fl['invalid_email'] 			= '%invalid-email%';
$fl['ok_button'] 				= '%ok-button%';
$fl['redirect_message'] 		= '%redirect-message%';
$fl['invalid_login']            = '%invalid-login%';


//======================================================================//
// ! START PROCESSING
//======================================================================//
                
// ! -- INIT ERROR ARRAY
$errors = array();

if($fl['debug'])
{
    ini_set('display_errors', 'On');
    error_reporting(E_ALL);
}else{
    ini_set('display_errors', 'Off');
}

//======================================================================//
// ! PHP 5.3 CHECK
//======================================================================//
$php_version = phpversion();
$php_check = 'bad'; // assume it is bad
if( $php_version < 5.3 ){
	$php_error = "Formloom Requires PHP Version 5.3 or better<br />".
	"The server this script is hosted on is using PHP Version $php_version.<br />".
	"Upgrade your server to PHP 5.3 and try again.";
	die($php_error);
}else{
	$php_check = 'good';
}

//======================================================================//
// ! CGI FIX
//======================================================================//
// Some hosts (was it GoDaddy?) complained without this
@ini_set('cgi.fix_pathinfo', 0);

//======================================================================//
// ! PHP 5.3 will complain without this
//======================================================================//
if(ini_get('date.timezone') == '') date_default_timezone_set('GMT');

// ! -- LOAD REQUIRED CLASSES
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR .'formloom3/lib/ydmailer.php');

$output='{"result":"fail", "msg":"'.$fl['error_message'].'(001)"}'; // init

//=====================================================//
// ! - POST SUBMITTED
//=====================================================//


if(
( (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])  && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
||  ( $_POST['fl_xmlhttprequest'] == 'iesux' && preg_match('/(?i)msie [1-9]/',$_SERVER['HTTP_USER_AGENT']))) || $debug_enabled
):


$mailer = new ydmailer;
$mailer->settings = $fl;

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

// ! USER LOGIN
if( $fl['login_required'] && !$_SESSION['logged_in'] )
{	
	if( $mailer->validateUserLogin($_POST['fl_username'], $_POST['fl_password']) )
	{
		$_SESSION['logged_in'] = true;
		echo '{"result":"loginsuccess"}';
		exit;
	}else{
        $_SESSION['logged_in'] = false;
        $msg .= '<div class="notification alert-error spacer-t10"><p><i class="fa fa-bomb"></i> '.$fl['invalid_login'].'</p><a href="#" class="close-btn">&times;</a></div>'.PHP_EOL;
        echo json_encode(array('result'=>'loginfail', 'msg'=>$msg));
        exit;
	}

}

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

//=====================================================//
// ! - CAPTCHA VALIDATION
//=====================================================//
            
if(isset($_POST["ydfl_securitycode"])){
	$securitycode = strip_tags(trim($_POST["ydfl_securitycode"]));
	if (!$securitycode) {
		array_push($errors, "You must enter the security code");
	} else if (md5($securitycode) != $_SESSION['ydflCheck']['securitycode']) {
		array_push($errors, "The security code you entered is incorrect.");
	}
}

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

// ! -- reCAPTCHA CHECK
# was there a reCAPTCHA response?
if(array_key_exists('recaptcha_challenge_field', $_POST))
{	
    // !-- reCAPTCHA TEST
    $recaptcha_result = $mailer->recaptchaCheckAnswer();
    if ( $recaptcha_result != 'good') 
    {    
        array_push($errors, $fl['captcha_failed']);
    }
    unset($recaptcha_result);
}

// ! -- CHECK REQUIRED FIELDS
$required = $mailer->checkRequiredFields();
if($required != 'good')
{
    array_push($errors, $fl['required_field_alert']);
}


// ! -- REPLY EMAIL VALIDATION
if(!$mailer->validateEmail($_POST['form'][$fl['reply_to_email']]))
{
        array_push($errors, 'Reply-To Item "'.$fl['reply_to_email'].'" has a value of "'.$_POST['form'][$fl['reply_to_email']].'" which is an invalid email format.<br>This usually happens when you assign the incorrect Item Name to the Reply-To Item setting.');
}

//=====================================================//
// ! FILTER INPUT FOR HACK ATTEMPTS 
//=====================================================//

if(!empty($fl['email_filter_regexp'])) {
    foreach ($_POST['form'] as $key => $value)
    { 		    
        $filter = '/\r|\n|to:|cc:|bcc:|'.$fl['email_filter_regexp'].'/i';
        $newValue = preg_replace( $filter ,'***',$value);
        $_POST['form'][$key] = $newValue;
    }
}

//=====================================================//
// ! BLOCKED?
//=====================================================//

// Email Blocked?
if( in_array( strtolower($_POST['form'][$fl['reply_to_email']]), $fl['block_emails'])) {
    array_push($errors, $fl['blocked_message']);
}

// IP Blocked?
$banned_ips = $fl['block_ips'];

if(count($banned_ips)) {
	
	array_pop($banned_ips);
	$thisip = $mailer->getIPAddress();
	
	if(in_array($thisip,$banned_ips)) {
	    // this is for exact matches of IP address in array
	    array_push($errors, $fl['blocked_message']);
	} else {
	    // this is for wild card matches
	    foreach($bannedIP as $ip) {
	        if(preg_match("/^{$ip}/i", $thisip)){
	            array_push($errors, $fl['blocked_message']);
	            break;
	        }
	    }
	}

}

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

// process any attachments if present...
$files = $mailer->processAttachments();
if( $files != 'good' )
    array_push($errors, $files);


//=====================================================//
// ! - CUSTOM PHP CODE (ADVANCED)
//=====================================================//

%custom-php-code%

//=====================================================//
// ! - PROCESS
//=====================================================//
if (!$errors)
{
    // process form...
    $mailer->processForm();
}else{
    // notify owner of errors...
    if($fl['notify_enabled'] ){
	    $msg = "Errors:".PHP_EOL;
	    foreach($errors as $error)
	    	$msg .= "-- $error".PHP_EOL;
        $mailer->notifyOwner($msg);
    }
}
	

$output = $mailer->getOutput($errors, $required);

endif; // if POSTED


echo $output;



?>