<?php
// FormMailer, copyright 2007-2011, EB Dynamics, Inc., Ed Lemmers
// For licensing, see license.txt.
//
// This module may be customized to your needs, however, the design is intended to cover all
// form mailing needs without modification by directing this module through hidden fields
// from within your form.  Having said that, we know there will always be something else that
// is required, but we think this module should do a good job of handling most situations
// without modification.
error_reporting (E_ALL ^ E_NOTICE);

if ((isset($_FILES)) && (count($_FILES) > 0) && ($_FILES["upload_file"]["name"] != ""))	{
	ini_set('max_execution_time', 21600);
	set_time_limit(21600);
	ini_set('memory_limit','512M');
	ini_set('post_max_size','128M');
}

// Modify the line below for your particular website.  This will eliminate attacks from remote servers.
//$referers = array('www.example.com', 'example.com');
$server_name = $_SERVER['SERVER_NAME'];
$server_name_www = "www." . $server_name;
$referers = array($server_name_www, $server_name);

// Module for performaing actual email operation.
include("mime_mail.inc");
// DB connection for retrieving HTML message format for message back to inquirer, etc.
include("../connect/db_connect.php");
include("../connect/config.php");
include("clean_var.php");
// List of key fields to ignore (not customer data, but rather configuration hidden fields).
include("ignore_fields.php");

// If alternate go back specified, then use that if any errors.  This is usefule if sending page session expires if back button is used.
if ($_POST['alt_go_back'])
{
	$go_back = $_POST['alt_go_back'];
	$delim = "?";
	foreach($_POST as $key => $val)
	{
		if (!in_array($key, $ignore_fields) || ($key == "redirect") || ($key == "redirect2") || ($key == "redirect3"))
		{
			if ((isset($val) && ($val != "")))
			{
				$go_back .= $delim . $key . "=" . $val;
				$delim = "&";
			}
		}
	}
}
else
	$go_back = "javascript:history.go(-1);";


// Used in conjunciton with $referers to eliminate atacks from remote servers.
$valid_env = array('REMOTE_HOST', 'REMOTE_ADDR', 'REMOTE_USER', 'HTTP_USER_AGENT');

// Add additional ignore fields from hidden ingore_fields element on form to ingore_field list.
$post_ignore_fields = $_POST['ignore_fields'];
$additional_ignore_fields = explode(",", $post_ignore_fields);
foreach ($additional_ignore_fields as $val)	{
	$ignore_fields[] = trim($val);
}

// List of longtext type fields.
$longtext_fields = array("comments", "note", "notes", "suggestions", "feedback", "question", "questions", "memo");

// Add additional longtext type fields from hidden longtext_fields element on form to longtext_fields list.
$post_longtext_fields = $_POST['longtext_fields'];
$additional_longtext_fields = explode(",", $post_longtext_fields);
foreach ($additional_longtext_fields as $val)	{
	$longtext_fields[] = trim($val);
}


// From hidden fields to direct mail to site manager and forward page to desired message, etc.
// "recipient", "redirect" and "subject" are required.  If "from" is left blank then the 'from' 
// will show as "Mail Request Form <email>".  If "html" is left blank, then the message will
// default to text.
// If desired, you may repalec the @ simbol with 5 plus signs in your mail form.  This will prenvent robots from harvesting your email
// until this technique gains popularity.
$referer = $_SERVER['HTTP_REFERER'];
$referer_arr = explode("/", $referer);
$page_name = $referer_arr[count($referer_arr)-1];
$page_name_arr = explode(".php", $page_name);
$page_name = $page_name_arr[0];
$query = "SELECT * FROM form_recipients WHERE page_name = :page_name";
$stmt = $bwb_dbh->prepare($query);
$stmt->execute(array(':page_name' => $page_name));
if ($stmt->rowCount() > 0)	{
	$row = $stmt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT);
	$recipient = $row['recipient'];
}
else	{
	$recipient = $_POST['recipient'];
	$recipient = str_replace("+++++", "@", $recipient);
}

$redirect = $_POST['redirect'];
$subject = $_POST['subject'];
$reply_to = $_POST['reply_to'];
$from = $_POST['from'];
if ($_POST['html'])
	$html = 1;	// html
else
	$html = 0;	// text
if ($_POST['no_mime'])
	$no_mime = 1;	// Certain servers can't handle mime messages such as GoDaddy hosting.
else
	$no_mime = 0;
if ($_POST['html_msg_as_text'])
	$html_msg_as_text = 1;	// Override to send HTML message to form user as text instead.
else
	$html_msg_as_text = 0;
$attachment_application = $_POST['attachment_application'];
$charset = $_POST['charset'];
$encode_type = $_POST['encode_type'];
$transfer_encoding = $_POST['transfer_encoding'];
	
// Special flag to denote that 'email' is a required field.  If 'email' is required here, 'email_confirm'
// will also be required.  If you do not need email confirm, then add "email" to the 'required_fields'
// string on your form instead.
$email_required = $_POST['email_required'];

// Special flag to denote that 'password' is a required field.  If 'password' is required here,
// 'password_confirm' will also be required.
$password_required = $_POST['password_required'];
$password_length = $_POST['password_length'];
$password_strength = $_POST['password_strength'];

// Flag to switch redirect back to form instead of displaying error message from this module.  Set to 1 to send errors back to form.
$redirect_err_to_src = $_POST['redirect_err_to_src'];

// You may specify which fields are required to be filled in.  Use a comma "," to separate fields.
$required_fields = $_POST['required_fields'];
if ($required_fields)
{
	$required_field_array = explode(",", $required_fields);
	foreach ($required_field_array as $value)
	{
		if (!$_POST[$value])
		{
			$err_code = "required&field=$value";
			$err_msg = "The '$value' field has not been filled in.  Please fill in this field.";
			DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back);
		}	
	}
}

// Information from user input.  Possible expected fields that may require special handling.
$email	= trim($_POST['email']);
$email_confirm = trim($_POST['email_confirm']);
$password	= trim($_POST['password']);
$password_confirm = trim($_POST['password_confirm']);
$use_email_as_userid = $_POST['use_email_as_userid'];

// If email required flag is sent, then verify that 'email' has been filled in and 'email_confirm'
// matches 'email'.
if (((!$email) || ($email != $email_confirm)) && $email_required)
{
	$err_code = "email";
	$err_msg = "Your email is blank or does not match the confirm.  Please fill in your email address.";
	DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back);
}

// If password required flag is sent, then verify that 'password' has been filled in and 'password_confirm'
// matches 'password'.
if (((!$password) || ($password != $password_confirm)) && $password_required)
{
	$err_code = "no_match";
	$err_msg = "Your password is blank or does not match the confirm.  Please fill in your password.";
	DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back);
}
// Verify password length is at least password_length long.
if (isset($password) && isset($password_length))
{
	if (strlen($password) < $password_length)
	{
		$err_code = "too_short";
		$err_msg = "Your password is too short.  Please fill in a password of at least $password_length characters long.";
		DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back);
	}
}
// Verify password meets strength requirements.
if (isset($password) && isset($password_strength))
{
	$pass_strength_err = false;
	
	if ($password_strength == "medium")
	{
		if (!preg_match('/[A-Za-z]/', $password) || !preg_match('/[0-9]/', $password))
		{
			$pass_strength_err = true;
			$err_msg = "Your password is too weak.  Please fill in a password contaning both letters and numbers.";
		}
	}
	if ($password_strength == "high")
	{
		$symbols = array('~','!','@','#','\$','%','^','&','*','(',')','[',']','{','}','?','+','=','-','_','/','|','\\','.',',','<','>',',',"'",'"',':',';');
		if (!preg_match('/[A-Za-z]/', $password) || !preg_match('/[0-9]/', $password) || (strpos_a($password, $symbols) === false))
		{
			$pass_strength_err = true;
			$err_msg = "Your password is too weak.  Please fill in a password contaning letters, numbers and symbols.";
		}
	}
	
	if ($pass_strength_err === true)
	{
		$err_code = "too_weak&password_strength=" . $password_strength;
		DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back);
	}
}

// Check email address to make sure it is not bogus.
if ($email_required)
{
	if (!check_email_address($email))
	{
		$err_code = "bad_email";
		$err_msg = "The email address $email is not valid.  Please go back and type your email address again.";
		DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back);
	}
}

// Check referers to make sure SPAM bot is not trying to brake in.
if (!check_referer($referers))
{
	$err = "You do not appear to be a valid.  If this is in error, go back and try again.<br />\n<a href='$go_back'>Click here</a> to return to the previous page, or use your 'Back' button.";
	$button_label = "OK";
	include("error_msg.php");
	exit;
}

///////////////////////////////////////
if ($_POST['use_captcha'])
{
	$captcha_err = false;
	
	if (!isset($_POST['captcha_type']) || ($_POST['captcha_type'] == "recaptcha"))
	{
	  include("../connect/captchakeys.php");
	  require_once('recaptchalib.php');
	  $resp = recaptcha_check_answer (RECAPTCHA_PRIVATE_KEY,
									$_SERVER["REMOTE_ADDR"],
									$_POST["recaptcha_challenge_field"],
									$_POST["recaptcha_response_field"]);
	
	  if (!$resp->is_valid)
			$captcha_err = true;	// Verification code is incorrect.
	}
	elseif ($_POST['captcha_type'] == "recaptcha2")
	{
		include("../connect/captchakeys.php");
		require_once('recaptchalib2.php');
		// The response from reCAPTCHA
		$resp = null;
		// The error code from reCAPTCHA, if any
		$error = null;
		$reCaptcha = new ReCaptcha(RECAPTCHA_SECRET);
		// Was there a reCAPTCHA response?
		if ($_POST["g-recaptcha-response"])
			$resp = $reCaptcha->verifyResponse($_SERVER["REMOTE_ADDR"],	$_POST["g-recaptcha-response"]);
		// reCAPTCHA response correct?
		if (($resp == null) || !($resp->success))
			$captcha_err = true;	// Verification code is incorrect.
	}
	elseif ($_POST['captcha_type'] == "wscaptcha")	// Requires purchase of PHP Captcha from http://webspamprotect.com/
	{
		require_once("wspcaptchalib.php");
		if (!WSP_CheckCAPTCHA())
			$captcha_err = true;	// Verification code is incorrect.
	}
	elseif ($_POST['captcha_type'] == "mollom")	// Requires acquisition of public and private keys from http://mollom.com
	{
		require_once("mollom.php");
		include("../connect/captchakeys.php");
		
		$captcha_response_field = $_POST['captcha_response_field'];
		$mollom_session = $_POST['mollom_session'];
		
		// Set keys from connect/captchakeys.php
		Mollom::setPublicKey(MOLLOM_PUBLIC_KEY);
		Mollom::setPrivateKey(MOLLOM_PRIVATE_KEY);
		
		$servers = Mollom::getServerList();
		Mollom::setServerList($servers);
	
		try
		{
			if (!Mollom::checkCaptcha($mollom_session, $captcha_response_field))	{
				$captcha_err = true;
			}
		}
		catch (Exception $e)
		{
			$err = "Error accessing Mollom CAPTCHA.  Please <a href='$go_back'>go back</a> and try again.<br />$e";
			$button_label = "OK";
			include("error_msg.php");
			
			exit;
		}
	}
	
	if ($captcha_err === true)
	{
		$err_code = "captcha";
		$err_msg = "Your CAPTCHA entry is incorrect.";
		DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back);
	}
}
///////////////////////////////////////

// In many instances, it is desirable to use the email address as the user ID.
if (isset($use_email_as_userid))
	$_POST['UserID'] = $email;

//Mail fields to recipient.
$mail = new mime_mail;

if ($from)
	$from_email = "$from";
else
	$from_email = "Mail Request Form <$email>";
	
$to_email = $recipient;
//$cc_email = "ed@ebdynamics.com";	//for testing

	
if ($html == 1)
	$lf = "<br>";
else
	$lf = "\n";

$msg = $_POST;
foreach ( $msg as $key => $value )
{
	// If a phone number is found, then check for robot attacks.
	if ((strpos($key, "phone") > -1) && ($key != "preferred_phone"))
	{
		if (!CheckPhoneField($value))
		{
			$err_code = "bad_phone&field=$key";
			$err_msg = "The phone number $value is not a valid phone number.  Please go back and type your phone number again.";
			DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back);
		}
	}
	
	if ((!in_array($key, $ignore_fields)) && ($key != "subject") && ($key != "password"))
		$msg = $msg."$lf".$key.": ".$value;
}
$msg = str_replace( "Array", "", $msg );
if ($html == 1)
	$msg = "<b>$subject</b>$lf" . $msg;
else
	$msg = "$subject$lf" . $msg;

/////////// Check for robots by counting URLs. ////////////////////
if (isset($_POST['max_url']) && ($_POST['max_url'] > -1))
{
	$http_cnt = 0;
	$pos = stripos($msg, "http");
	if ($pos !== false)
	{
		$http_cnt++;
		$pos2 = stripos($msg, "http", $pos + 1);
		if ($pos2 !== false)
			$http_cnt++;
	}
	if ($http_cnt >= $_POST['max_url'])
	{
		if (isset($redirect) && ($redirect != ""))
			header("Location: $redirect");
		exit;
	}
}
/////////// Check for robots by counting URLs. ////////////////////

// If attachements, then get files onto server.
if (isset($_FILES))	{
	$bad_file_ext = array("php", "htm", "html", "js", "asp", "exe", "cf", "jsp", "sh");
	if (isset($_POST['allowed_file_ext']))	{
		$_POST['allowed_file_ext'] = str_replace(array(".", " "), "", $_POST['allowed_file_ext']);
		$allowed_file_ext = explode(",", $_POST['allowed_file_ext']);
	}
	//////////////////////////////////////////////////////
	if ((isset($_POST['image_width']) && ($_POST['image_width'] != "")) || (isset($_POST['image_height']) && ($_POST['image_height'] != "")))	{
		include("image_processing.php");
		$process_images = true;
		$image_ext = array("jpg", "gif", "png", "jpeg");
		if (isset($_POST['image_width']) && ($_POST['image_width'] != ""))
			$max_width = $_POST['image_width'];
		else
			$max_width = 1000000;
		if (isset($_POST['image_height']) && ($_POST['image_height'] != ""))
			$max_height = $_POST['image_height'];
		else
			$max_height = 1000000;
		if (isset($_POST['preserve_aspect_ratio']) && ($_POST['preserve_aspect_ratio'] != ""))
			$preserve_aspect_ratio = $_POST['preserve_aspect_ratio'];
		else
			$preserve_aspect_ratio = 1;
	}
	//////////////////////////////////////////////////////
	
	foreach($_FILES as $file_key => $file)	{
		if (basename($file["name"] == ""))	{
			// If no file was selected, can't upload it. Unset files and get out of here.
			if (count($_FILES) < 2)	{
				unset($_FILES);
				break;
			}
			else
				unset($_FILES[$file_key]);
				continue;
		}
		$_POST[$file_key] = basename($file["name"]);

		if (isset($_POST["uploads_dir"]) && ($_POST["uploads_dir"] != ""))
			$uploads_dir = "../" . $_POST["uploads_dir"];
		else
			$uploads_dir = "../uploads";
		$target_dir = $uploads_dir;
		
		if (!file_exists($target_dir))
			mkdir($target_dir);
		$target_file = $target_dir . "/" . basename($file["name"]);
		// Allow certain file formats
		$file_parts = explode(".", $target_file);
		$ext = $file_parts[count($file_parts) - 1];
		if ((in_array(strtolower($ext), $bad_file_ext)) || (isset($allowed_file_ext) && !in_array(strtolower($ext), $allowed_file_ext)))	{
			$err_code = "file_type";
			$err_msg = "The file you are trying to send is of a type that is not allowed to be be emailed.  Please select a different file.";
			DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back);
		}
		// Check if file already exists
		if (file_exists($target_file))	{
			$NUM = time();		
			$target_file = str_replace("." . $ext, "", basename($file["name"]));
			$target_file .= "_" . $NUM . "." .  $ext;
			$_POST[$file_key] = $target_file;
			$target_file = $target_dir . "/" . $target_file;
		}
		// Check file size
		if ($file["size"] > 50000000) {
			$err_code = "file_size";
			$err_msg = "The file you are trying to send is too large for email.  Please select a different file.";
			DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back);
		}
		// if everything is ok, try to upload file
		if (!move_uploaded_file($file["tmp_name"], $target_file)) {
			$err_code = "upload";
			$err_msg = "There was an error uploading your file.  Please try again.";
			DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back);
		}
		///////////////////////////////////////////
		if (($process_images === true) && in_array(strtolower($ext), $image_ext))	{
			if (resize_image($target_file, $max_width, $max_height, $target_file, 1, $preserve_aspect_ratio) != 1)	{
				$err_code = "img_resize";
				$err_msg = "There was an error resizing your image.  Please try again.";
				DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back);
			}
		}
		///////////////////////////////////////////
	}
}

$mail->from = $from_email;
$mail->to = $to_email;
$mail->cc = $cc_email;
$mail->replyto = $reply_to;
$mail->subject = $subject;
$mail->body = $msg;
$mail->html = $html;
$mail->no_mime = $no_mime;
if (isset($_FILES) && ($_POST["store_uploads_instead"] < 1))	{
	$i = 0;
	foreach($_FILES as $file)	{
		$mail->attachment[$i] = $uploads_dir . "/" . $file["name"];
		$i++;
	}
}
if (isset($attachment_application) && ($attachment_application != ""))
	$mail->attachment_application = $attachment_application;
if (isset($charset) && ($charset != ""))
	$mail->charset = $charset;
if (isset($encode_type) && ($encode_type != ""))
	$mail->encode_type = $encode_type;
if (isset($transfer_encoding) && ($transfer_encoding != ""))
	$mail->transfer_encoding = $transfer_encoding;

$mail->send();

/////////////////////////////////////////////////////////////////////////
// Pipe data to table.  Create table if it does not exist.
// But first clean entire POST var array:
foreach ($_POST as $key => $value)	{
	if ((!is_array($value)) && (!is_object($value)))
		$_POST[$key] = CleanVar($value);
	else	{
		foreach ($value as $k => $val)	{
			$value[$k]= CleanVar($val);
		}
		$_POST[$key] = $value;
	}
}
	
$table_name = $_POST['table_name'];

if (isset($table_name) && ($table_name != ""))
{
	if (isset($_POST['userid']) && isset($_POST['UserID']))
	{	// Can't have both, need to consolitade.
		if ($_POST['userid'] == $_POST['UserID'])
			unset($_POST['userid']);
		elseif (strlen($_POST['userid']) > strlen($_POST['UserID']))
			unset($_POST['UserID']);
		else
			unset($_POST['userid']);
	}

	// Check to see if table exists.
	$query = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '[$bwb_database]' AND table_name = '[$table_name]'";
	$result = $bwb_dbh->query($query);
	$row = $result->fetch(PDO::FETCH_ASSOC);

	if ($row["COUNT"] < 1)
	{
		$query = "CREATE TABLE IF NOT EXISTS `$table_name` (`id` bigint(20) NOT NULL auto_increment, ";
		// Add column for each key.
		foreach ($_POST as $key => $value)
		{
			if ((!is_array($value)) && (!is_object($value)))	{
				if ((!is_array($key)) && (!is_object($key)))
					$key = CleanVar($key);
				if (in_array($key, $longtext_fields))
					$query .= "`$key` longtext default NULL, ";
				elseif (!in_array($key, $ignore_fields))
					$query .= "`$key` varchar(255) default NULL, ";
			}
			else	{
				foreach ($value as $k => $val)	{
					$k= CleanVar($k);
					if (in_array($key . "[" . $k . "]", $longtext_fields))
						$query .= "`" . $key . "[" . $k . "]` longtext default NULL, ";
					elseif (!in_array($key, $ignore_fields))
						$query .= "`" . $key . "[" . $k . "]` varchar(255) default NULL, ";
				}
			}
		}
		// Add created field.
		$query .= "`created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, ";
		// Add primary key.
		$query .= "PRIMARY KEY  (`id`) )";
		$cnt = $bwb_dbh->exec($query);
	}

	// Add any missing columns due to new fields in form.
	foreach ($_POST as $key => $value)
	{
		if ((!is_array($value)) && (!is_object($value)))	{
			if ((!is_array($key)) && (!is_object($key)))
				$key = CleanVar($key);
			$field_found = false;
			$query ="SHOW COLUMNS FROM $bwb_database.$table_name";
			$result = $bwb_dbh->query($query);
			while ($row = $result->fetch(PDO::FETCH_ASSOC))
			{
				if (($row['Field'] == $key) || ($row['field'] == $key))
					$field_found = true;
			}
			if (!$field_found && in_array($key, $longtext_fields))
			{
				$query2 = "ALTER TABLE `$table_name` ADD `$key` longtext NULL ";
				$cnt = $bwb_dbh->exec($query2);
			}
			elseif (!$field_found && !in_array($key, $ignore_fields))
			{
				$query2 = "ALTER TABLE `$table_name` ADD `$key` VARCHAR( 255 ) NULL ";
				$cnt = $bwb_dbh->exec($query2);
			}
		}
		else	{
			foreach ($value as $k => $val)	{
				$k= CleanVar($k);
				$field_found = false;
				$query ="SHOW COLUMNS FROM $bwb_database.$table_name";
				$result = $bwb_dbh->query($query);
				while ($row = $result->fetch(PDO::FETCH_ASSOC))
				{
					if (($row['Field'] == $key . "[" . $k . "]") || ($row['field'] == $key . "[" . $k . "]"))
						$field_found = true;
				}
				if (!$field_found && in_array($key . "[" . $k . "]", $longtext_fields))
				{
					$query2 = "ALTER TABLE `$table_name` ADD `" . $key . "[" . $k . "]` longtext NULL ";
					$cnt = $bwb_dbh->exec($query2);
				}
				elseif (!$field_found && !in_array($key . "[" . $k . "]", $ignore_fields))
				{
					$query2 = "ALTER TABLE `$table_name` ADD `" . $key . "[" . $k . "]` VARCHAR( 255 ) NULL ";
					$cnt = $bwb_dbh->exec($query2);
				}
			}
		}
	}

	// If no_duplicates defined, then check to see if record already exists.
	$no_duplicates = $_POST['no_duplicates'];
	if ($no_duplicates)
	{
		$no_dupes_array = explode(",", $no_duplicates);
		foreach ($no_dupes_array as $value)
		{
			$unique_field_val = $_POST[$value];
			$query = "SELECT * FROM " . $table_name . " WHERE `" . $value . "`='" . $unique_field_val . "'";
			$result = $bwb_dbh->query($query);
			if ($result->rowCount() > 0)
			{	
				$err_msg = "<b>$unique_field_val</b> already exists for the <b>$value</b> field.  You will need to enter a different $value.";
				$err_code = "duplicate&field=$value";
				DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back);
			}
		}
	}

	// Insert/Update row.
	if (isset($_POST['update_record']) && ($_POST['update_record'] == 1))
	{
		$verb = "UPDATE";
		if (isset($_POST['update_record_key']) && ($_POST['update_record_key'] != ""))
			$where_key = $_POST['update_record_key'];
		else
		{
			if (isset($_POST['userid']) && ($_POST['userid'] != ""))
				$where_key = 'userid';
			elseif (isset($_POST['UserID']) && ($_POST['UserID'] != ""))
				$where_key = 'UserID';
			elseif (isset($_POST['email']) && ($_POST['email'] != ""))
				$where_key = 'email';
			else
				$verb = "INSERT INTO";
		}
		$where = " WHERE `$where_key` = '" . $_POST[$where_key] . "'";
	}
	else
		$verb = "INSERT INTO";
		
	$query = "$verb `$table_name` SET ";
	$first = true;

	foreach ($_POST as $key => $value)
	{
		if ((!is_array($key)) && (!is_object($key)))	
			$key = CleanVar($key);
		else	{
			foreach ($key as $k => $val)	{
				$key[$k]= CleanVar($val);
			}
		}
		if (!in_array($key, $ignore_fields))
		{
			if (($value == "") && ($verb == "UPDATE"))
				continue;	// Don't overwrite fields with blanks if updating.
				
			//If password found, encrypt password using user ID,last name or email address as key.
			if ($key == "password")
			{
				// Insert salt into password.
				$pos = rand(0, (strlen($value)-1) );
				$pass1 = substr($value, 0, $pos);
				$pass2 = substr($value, $pos);
				$salted_pass = $pass1 . BWB_PUB_SALT . $pass2;
				// Encrypt password using user name as key.
				if (isset($_POST['userid']))
					$value = doEncrypt($salted_pass, $_POST['userid']);
				elseif (isset($_POST['UserID']))
					$value = doEncrypt($salted_pass, $_POST['UserID']);
				elseif (isset($_POST['last_name']))
					$value = doEncrypt($salted_pass, $_POST['last_name']);
				elseif (isset($_POST['email']))
					$value = doEncrypt($salted_pass, $_POST['email']);
			}
	
			if ((!is_array($value)) && (!is_object($value)))	{
				if (!$first) $query .= ", "; else $first = false;
				if (strpos($value, "'") !== false)	{
					// Optionally, replace all single quotes with HTLM ampersand code.
					if (isset($_POST['replace_single_quotes']) && ($_POST['replace_single_quotes'] > 0))
						$value = str_replace("'", "&#39;", $value);
					else
						$value = addslashes($value);
				}
				$query .= "`$key` = '$value'";
			}
			else	{
				foreach ($value as $k => $val)	{
					$val = CleanVar($val);
					if (!$first) $query .= ", "; else $first = false;
					$query .= "`" . $key . "[" . $k . "]` = '" . $val . "'";
				}
			}
		}
	}
	if ($verb == "UPDATE")
		$query .= $where;
	$cnt = $bwb_dbh->exec($query);

	// Get last inserted id for possible use by other modules.
	if ($verb == "INSERT INTO")
		$last_id = $bwb_dbh->lastInsertId();
	else	{
		$query = "SELECT * FROM " . $table_name . " WHERE `" . $where_key . "`='" . $_POST[$where_key] . "'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		if (isset($row["id"]))
			$last_id = $row["id"];
		else
			$last_id = $row[0];
	}
	

	/////////////////////////////////////////////
	// If table is user table for page access, then see if need to activate right now.
	if ($verb != "UPDATE" || (isset($_POST['update_and_login']) && ($_POST['update_and_login'] == 1)))
	{
		$query = "SELECT option_value FROM `" . BWB_TABLE_PREFIX . "options_selected` WHERE option_name='ActivateNewUsersAutomatically'";
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$activate = $row['option_value'];
	
		if ($activate == 1)
		{
			$got_active = false;
			$got_session = false;
			$got_ip = false;
			$got_userid = false;
			$got_password = false;
			$query ="SHOW COLUMNS FROM $bwb_database.$table_name";
			$result = $bwb_dbh->query($query);
			while ($row = $result->fetch(PDO::FETCH_ASSOC))
			{
				if (($row['Key'] == "PRI") || ($row['key'] == "PRI"))	{
					if (isset($row['Field']))
						$key_field = $row['Field'];
					elseif (isset($row['field']))
						$key_field = $row['field'];
					else
						$key_field = "id";
				}
				if (($row['field'] == "Active") || ($row['Field'] == "Active"))
					$got_active = true;
				if (($row['field'] == "Session") || ($row['Field'] == "Session"))
					$got_session = true;
				if (($row['field'] == "IP") || ($row['Field'] == "IP"))
					$got_ip = true;
				if (($row['field'] == "UserID") || ($row['field'] == "userid") || ($row['Field'] == "UserID") || ($row['Field'] == "userid"))
					$got_userid = true;
				if (($row['field'] == "password") || ($row['Field'] == "password"))
					$got_password = true;
			}
			if ($got_active && $got_session && $got_ip && $got_userid && $got_password)
			{
				$query = "UPDATE `$table_name` SET `Active`=1 WHERE `UserID`='$userid'";
				$cnt = $bwb_dbh->exec($query);
				$query = "UPDATE `$table_name` SET `Active`=1 WHERE `$key_field`=$last_id";
				$cnt = $bwb_dbh->exec($query);
				
				// Account activated, now go ahead and log in.
				session_start();
				if (isset($_POST['UserID']))
					$userid = $_POST['UserID'];
				elseif (isset($_POST['userid']))
					$userid = $_POST['userid'];
				$_SESSION['pub_userid'] = $userid;
				$session = md5(session_id());
				$ip = $_SERVER['REMOTE_ADDR'];
				$query = "UPDATE `" . $table_name . "` SET `Session`='$session', `IP`='$ip' WHERE `UserID`='$userid'";
				$cnt = $bwb_dbh->exec($query);
				$query = "UPDATE `" . $table_name . "` SET `Session`='$session', `IP`='$ip' WHERE `$key_field`=$last_id";
				$cnt = $bwb_dbh->exec($query);
			}
		}
	}
	/////////////////////////////////////////////
}

/////////////////////////////////////////////////////////////////////////
// Send HTML message to inquirer if message is setup.
$html_message_page = $_POST['html_message_page'];
if (isset($html_message_page) && ($html_message_page != ""))
{
	$mail = new mime_mail;
	
	$first_name = $_POST['first_name'];
	$last_name = $_POST['last_name'];
	if (isset($_POST['UserID']))
		$userid = $_POST['UserID'];
	elseif (isset($_POST['userid']))
		$userid = $_POST['userid'];
	else
		$userid = "";
	if (isset($_POST['user_defined_placeholders']) && ($_POST['user_defined_placeholders'] != ""))
	{
		$user_defined_placeholders_str = $_POST['user_defined_placeholders'];
		$user_defined_placeholders_arr = explode(",", $user_defined_placeholders_str);
		$user_defined_placeholders = array();
		foreach ($user_defined_placeholders_arr as $placeholder_pair)
		{
			$placeholder_pair_arr = explode(":", $placeholder_pair);
			$user_defined_placeholders[$placeholder_pair_arr[0]] = $placeholder_pair_arr[1];
		}
	}
	
	$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "page_data WHERE page_name = '". $html_message_page . "'";
	$result = $bwb_dbh->query($query);
	if ($row = $result->fetch(PDO::FETCH_ASSOC))
	{
		$html_msg = stripslashes($row["page_content"]);
		////////////////// Process Conditional Content First /////////////////
		include("return_msg_cond_proc.php");
		//////////////////////////////////////////////////////////////////////
		$html_msg = str_replace("[FIRST_NAME]", $first_name, $html_msg);
		$html_msg = str_replace("[LAST_NAME]", $last_name, $html_msg);
		$html_msg = str_replace("[USER_ID]", $userid, $html_msg);
		$html_msg = str_replace("[PASSWORD]", $password, $html_msg);
		$html_msg = str_replace("[EMAIL]", $email, $html_msg);
		if (isset($user_defined_placeholders) && ($user_defined_placeholders != ""))
		{
			foreach ($user_defined_placeholders as $placeholder_str => $placeholder_field)
			{
				$html_msg = str_replace($placeholder_str, $_POST[$placeholder_field], $html_msg);
			}
		}
		
		$mail->from = $from;
		$mail->to = $email;
		$mail->replyto = $reply_to;
		$mail->subject = $subject;
		if ($html_msg_as_text == 1)	{
			$mail->html = 0;
			$mail->body = strip_tags($html_msg);
		}
		else	{
			$mail->html = 1;
			$mail->body = $html_msg;
		}
		$mail->no_mime = $no_mime;
		
		$mail->send();
		
		if (isset($attachment_application) && ($attachment_application != ""))
			$mail->attachment_application = $attachment_application;
		if (isset($charset) && ($charset != ""))
			$mail->charset = $charset;
		if (isset($encode_type) && ($encode_type != ""))
			$mail->encode_type = $encode_type;
		if (isset($transfer_encoding) && ($transfer_encoding != ""))
			$mail->transfer_encoding = $transfer_encoding;
	}
}

// If attachements sent, then delete them off of server.
if (isset($_FILES) && ($_POST["store_uploads_instead"] < 1))	{
	foreach($_FILES as $file)	{
		$target_file = $target_dir . "/" . basename($file["name"]);
		if (file_exists($target_file)) {
			unlink($target_file);
		}
	}
}

/////////////////////////////////////////////////////////////////////////
// If data stored in table, then pass along last id to next page.
if (isset($redirect) && ($redirect != ""))
{
	if (isset($table_name) && ($table_name != ""))
	{
		if (strpos($redirect, "?") > 0)
			$redirect .= "&last_id=" . $last_id;
		else
			$redirect .= "?last_id=" . $last_id;
	}
		
	// Go to desired next page.
	header("Location: $redirect");
}
exit;

/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// Check for valid emails. //////////////////////////////////////////////
function check_email_address($email) {
	if (!filter_var($email, FILTER_VALIDATE_EMAIL))
	 	return false;
	else
		return true;
}

/****************************************************************
 * check_referer() breaks up the enviromental variable		*
 * HTTP_REFERER by "/" and then checks to see if the second	*
 * member of the array (from the explode) matches any of the	*
 * domains listed in the $referers array (declaired at top)	*
 ****************************************************************/

function check_referer($referers)
{
	global $errors;
	if (count($referers)) {
		if (getenv('HTTP_REFERER')) {
			$temp = explode('/', getenv('HTTP_REFERER'));
			$found = false;
			while (list(,$stored_referer) = each($referers)) {
				if (preg_match('/^' . $stored_referer . '$/i', $temp[2]))
					$found = true;
			}
			if (!$found) {
				$errors[] = '1|You are coming from an unauthorized domain.  Please read the manual section titled &quot;<a href="' . MANUAL . '#setting_up" target="_blank">Setting Up the PHPFormMail Script</a>&quot;.';
				error_log('[PHPFormMail] Illegal Referer. (' . getenv('HTTP_REFERER') . ')', 0);
			}
			return $found;
		} else {
			$errors[] = '0|Sorry, but I cannot figure out who sent you here.  Your browser is not sending an HTTP_REFERER.  This could be caused by a firewall or browser that removes the HTTP_REFERER from each HTTP request you submit.';
			error_log('[PHPFormMail] HTTP_REFERER not defined. Browser: ' . getenv('HTTP_USER_AGENT') . '; Client IP: ' . getenv('REMOTE_ADDR') . '; Request Method: ' . getenv('REQUEST_METHOD') . ';', 0);
			return false;
		}
	} else {
		$errors[] = '1|There are no referers defined.  All submissions will be denied.  Please read the manual section titled &quot;<a href="' . MANUAL . '#setting_up" target="_blank">Setting Up the PHPFormMail Script</a>&quot;.';
		error_log('[PHPFormMail] You have no referers defined.  All submissions will be denied.', 0);
		return false;
	}
}

///////////////////////////////////////////////////////////////
// Check all phone numbers for valid charecters.
function CheckPhoneField($number)
{
	$formats = array('###-###-####', '####-###-###',
                 '(###) ###-###', '(###)###-###', '####-####-####',
                 '##-###-####-####', '####-####', '###-###-###',
                 '#####-###-###', '##########',
				 '#-###-###-####', '#-####-###-###',
                 '# (###) ###-###', '#(###)###-###', '#-####-####-####',
                 '#-##-###-####-####', '#-####-####', '#-###-###-###',
                 '#-#####-###-###', '###########',
				 '##-###-###-####', '##-####-###-###',
                 '##-####-####-####',
                 '##-##-###-####-####', '##-####-####', '##-###-###-###',
                 '##-#####-###-###', '############');
	
	if (strlen($number) == 0)
		return true;	// Don't worry about blank phone numbers here.
		
	if ( preg_match("/^[A-Za-z]$/", $number) )
		return false;	// If any letters are found, then most likely bogus junk found.
		
	// + and _ are OK, -so remove for testing.
	$ignore_chars = array("+", "_");
	$number = str_replace($ignore_chars, "", $number);
	// . is used inplace of - many times, so just replace.
	$number = str_replace(".", "-", $number);
		
	$format = trim(preg_replace("/[0-9]/", "#", $number));
	return (in_array($format, $formats)) ? true : false;
}

/////////////////////////////////
function doEncrypt($Data, $Key)
{
// encrypting  a[] with key k[] into e[]
// a[] = array to be encrypted
// k[] = key of truly random gibberish
// e[] = encrypted data

	for( $i = 0; $i < strlen($Data); $i++)
	{
		$c = substr($Data, $i, 1);
		$a[$i] = ord($c);
	}
	
	for( $i = 0; $i < strlen($Data); $i++)
	{
		if ($i < strlen($Key))
		{
			$c = substr($Key, $i, 1);
			$k[$i] = ord($c);
		}
		else
			$k[$i] = 65 + $i;
	}
	
	for ( $i=0; $i < strlen($Data); $i++ )
   	{
   		$e[$i] = $k[$i] ^ $a[$i];
   	}
	
	$encrypted = "";
	for ( $i = 0; $i < strlen($Data); $i++ )
	{
		$encrypted = $encrypted. decToHex($e[$i]);
	}
	return($encrypted);
	
}

function decToHex($dec)
{
	$hexStr = "0123456789ABCDEF";
	$low = $dec % 16;
	$high = ($dec - $low)/16;
	$hex = "";
	$hex = substr($hexStr, $high, 1) . substr($hexStr, $low, 1);
	return $hex;
}

/////////////////////////////////////////////////////////////
function strpos_a($haystack, $needle)
{
     if (is_array($needle)) {
         foreach ($needle as $need) {
               if (strpos($haystack, $need) !== false) {
                       return (strpos($haystack, $need));
               }
         }
     }else {
          if (strpos($haystack, $need) !== false) {
                       return (strpos($haystack, $need));
          }
     }

     return false;
}

/////////////////////////////////////////////////////////////
function DisplayError($redirect_err_to_src, $err_msg, $err_code, $go_back)
{
	if (($redirect_err_to_src == 1) && ($go_back != "javascript:history.go(-1);"))
	{
		if (strpos($go_back, "?") === false)
			$go_back .= "?err=" . $err_code;
		else
			$go_back .= "&err=" . $err_code;
			
		header("Location: $go_back");
	}
	else
	{
		$err = $err_msg . "<br />\n<a href='$go_back'>Click here</a> to return to the previous page, or use your 'Back' button.";
		$button_label = "OK";
		include("error_msg.php");
	}
	exit;
}

?>