<?php
/*
 * This file is part of Web Pro Manager.
 * 
 * Web Pro Manager is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Web Pro Manager 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 Web Pro Manager.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @author The Web Pro Miami, Inc. <info@thewebpro.com>
 * @copyright The Web Pro Miami, Inc. <info@thewebpro.com>, http://www.thewebpro.com/
 * @license http://www.gnu.org/licenses/gpl.html GNU GPL
 * @package WebProManager
*/

// ver 1.1.5
// 1.0.2 - added validation min/max length
// 1.0.3 - skipped
// 1.0.4 - completed email integration
// 1.0.5 - added more error styling (CUSTOM STYLING)
// 1.0.7 - (pushed to 1.0.7) added SQLNoQuotes to allow certain items to have no quotes in SQL string (i.e. integers)
// 1.0.8 - switched POST to separate array to allow for pass thrus
// 1.0.9 - removed faulty database processing for empty query sets
// 1.1.0 - updated POST in parseBodyFile to use _POST instead of separate array (bugfix), adding small error checking for mailhost/user/pass
// 1.1.1 - added nMySQLInsertID to give access to mysql_insert_id of last added item to database
// 1.1.2 - added nUseSendMail flag for email servers that require it
// 1.1.3 - added "custom" validation handling
// 1.1.4 - bug fixes based on XAMPP 1.7.4 default install
// 1.1.5 - moved nPOST to global to allow custom function override of posted values

if($nDEBUG){ print "DEBUG mode enabled.<BR>"; }

$nRC4Key = "wwsfg321";

if($nAction_email){ include_once("phpmailer/class.phpmailer.php"); }
if($nRC4Key){ include_once("rc4.php"); }

// Get pre-defined variables, then remove them from the POST array
$nProcess = $nPOST["nProcess"]; unset($nPOST["nProcess"]);

// Set error codes
$nRequiredError = 0;
$nRequiredErrorText = "Please fill in ALL required fields (marked in RED).";
$nValEmailError = 0;
$nValEmailErrorText = "The EMAIL address you entered appears to be in an incorrect format. Please try again.";
$nValNumericError = 0;
$nValNumericErrorText = "The value you entered must be a NUMBER. Please try again.";
$nValPhoneError = 0;
$nValPhoneErrorText = "The PHONE number you entered appears to be in an incorrect format. Please try again.";
$nValDateError = 0;
$nValDateErrorText = "The value you entered must be a valid DATE. Please try again.";
$nValCCError = 0;
$nValCCErrorText = "The value you entered must be a valid CREDIT CARD number. Please try again.";
$nValMaxLengthError = 0;
$nValMaxLengthErrorText = "The value you entered must be LESS than [nLength] characters. Please try again.";
$nValMinLengthError = 0;
$nValMinLengthErrorText = "The value you entered must be MORE than [nLength] characters. Please try again.";
$nValCustomError = 0;
$nValCustomErrorText = "[nErrorMsg]";

// Styling
$nRequiredErrorText="<li class=\"red\"><span class=\"ico\"></span><strong class=\"system_title\">$nRequiredErrorText</strong></li>";
$nValEmailErrorText="<li class=\"red\"><span class=\"ico\"></span><strong class=\"system_title\">$nValEmailErrorText</strong></li>";
$nValNumericErrorText="<li class=\"red\"><span class=\"ico\"></span><strong class=\"system_title\">$nValNumericErrorText</strong></li>";
$nValPhoneErrorText="<li class=\"red\"><span class=\"ico\"></span><strong class=\"system_title\">$nValPhoneErrorText</strong></li>";
$nValDateErrorText="<li class=\"red\"><span class=\"ico\"></span><strong class=\"system_title\">$nValDateErrorText</strong></li>";
$nValCCErrorText="<li class=\"red\"><span class=\"ico\"></span><strong class=\"system_title\">$nValCCErrorText</strong></li>";
$nValMaxLengthErrorText="<li class=\"red\"><span class=\"ico\"></span><strong class=\"system_title\">$nValMaxLengthErrorText</strong></li>";
$nValMinLengthErrorText="<li class=\"red\"><span class=\"ico\"></span><strong class=\"system_title\">$nValMinLengthErrorText</strong></li>";
$nValCustomErrorText="<li class=\"red\"><span class=\"ico\"></span><strong class=\"system_title\">$nValCustomErrorText</strong></li>";

$nError = "";

if($nProcess){
	
	$nDontProcessARRAY = array();$nDontProcessARRAY=explode(",",$nDontProcess);
	$nSQLNoQuotesARRAY = array();$nSQLNoQuotesARRAY=explode(",",$nSQLNoQuotes);
	$nRequiredARRAY = array();$nRequiredARRAY=explode(",",$nRequired);
	$nValidate_emailARRAY = array();$nValidate_emailARRAY=explode(",",$nValidate_email);
	$nValidate_numericARRAY = array();$nValidate_numericARRAY=explode(",",$nValidate_numeric);
	$nValidate_phoneARRAY = array();$nValidate_phoneARRAY=explode(",",$nValidate_phone);
	$nValidate_dateARRAY = array();$nValidate_dateARRAY=explode(",",$nValidate_date);
	$nValidate_ccARRAY = array();$nValidate_ccARRAY=explode(",",$nValidate_cc);
	$nValidate_maxlengthARRAY = array();$nValidate_maxlengthARRAY=explode(",",$nValidate_maxlength);
	$nValidate_minlengthARRAY = array();$nValidate_minlengthARRAY=explode(",",$nValidate_minlength);
	$nValidate_customARRAY = array();$nValidate_customARRAY=explode(",",$nValidate_custom);
	$nEncode_RC4ARRAY = array();$nEncode_RC4ARRAY=explode(",",$nEncode_RC4);
	$nAction_emailARRAY = array();$nAction_emailARRAY=explode(",",$nAction_email);
	$nTranslateARRAY = array();$nTranslateARRAY=explode(",",$nTranslate);
	
	// Get passed-in variables
	foreach($nPOST as $key => $val) {
		
		// Watch for special cases
		if(!in_array($key,$nDontProcessARRAY)){
			
			// Required fields
			if(in_array($key,$nRequiredARRAY) && $val==""){ $nRequiredError = 1; }
			
			// Validations
			if(in_array($key,$nValidate_emailARRAY) && $val!="" && !validate_email($val)){ $nValEmailError = 1; }
			if(in_array($key,$nValidate_numericARRAY) && $val!="" && !validate_num($val)){ $nValNumericError = 1; }
			if(in_array($key,$nValidate_phoneARRAY) && $val!="" && !validate_phone($val)){ $nValPhoneError = 1; }
			if(in_array($key,$nValidate_dateARRAY) && $val!="" && !validate_date($val)){ $nValDateError = 1; }
			if(in_array($key,$nValidate_ccARRAY) && $val!="" && !validate_cc($val)){ $nValCCError = 1; }
			if(in_array($key,$nValidate_maxlengthARRAY) && $val!="" && !validate_maxlength($val,$nValParam_maxlengthARRAY[$key])){ $nValMaxLengthError = 1; $nValMaxLengthErrorTextFinal = str_replace("[nLength]",$nValParam_maxlengthARRAY[$key],$nValMaxLengthErrorText); }
			if(in_array($key,$nValidate_minlengthARRAY) && $val!="" && !validate_minlength($val,$nValParam_minlengthARRAY[$key])){ $nValMinLengthError = 1; $nValMinLengthErrorTextFinal = str_replace("[nLength]",$nValParam_minlengthARRAY[$key],$nValMinLengthErrorText); }
			if(in_array($key,$nValidate_customARRAY) && $val!=""){
				$nFunctionName = $nValParam_customARRAY[$key];
				if(!validate_custom($val,$nFunctionName)){
					$nValCustomError = 1;
					$nValCustomErrorMsg = "";
					eval("\$nValCustomErrorMsg = ".$nFunctionName."_errormsg('$val');");
					$nValCustomErrorTextFinal = str_replace("[nErrorMsg]",$nValCustomErrorMsg,$nValCustomErrorText);
				}
			}
		} else {
			unset($nPOST["$key"]);
		}
	}
	
	// Manage errors
	if($nRequiredError){ $nError.=$nRequiredErrorText;}
	if($nValEmailError){ $nError.=$nValEmailErrorText;}
	if($nValNumericError){ $nError.=$nValNumericErrorText;}
	if($nValPhoneError){ $nError.=$nValPhoneErrorText;}
	if($nValDateError){ $nError.=$nValDateErrorText;}
	if($nValCCError){ $nError.=$nValCCErrorText;}
	if($nValMaxLengthError){ $nError.=$nValMaxLengthErrorTextFinal;}
	if($nValMinLengthError){ $nError.=$nValMinLengthErrorTextFinal;}
	if($nValCustomError){ $nError.=$nValCustomErrorTextFinal;}
	
	// Final processing
	if(!$nError){
		// Save to database
		if($nAction_addtodb){
			$nQuerySet1ARRAY = array(); $nQuerySet2ARRAY = array();
			foreach($nPOST as $key => $val) {
				// Encoding
				if(in_array($key,$nEncode_RC4ARRAY) && $val!="" && $nRC4Key!=""){ $val = trim(rc4Encrypt("$nRC4Key",$val)); }
				// add to query set array
				$nQuerySet1ARRAY[] = "$key";
				if(!in_array($key,$nSQLNoQuotesARRAY)){ $nQuerySet2ARRAY[] = "'$val'"; } else { $nQuerySet2ARRAY[] = "$val"; }
			}
			$nQuerySet1 = implode(",",$nQuerySet1ARRAY); $nQuerySet2 = implode(",",$nQuerySet2ARRAY);
			if($nQuerySet1 && $nQuerySet2){
				$Query = "INSERT INTO $nAction_addtodb ($nQuerySet1) VALUES ($nQuerySet2)";
				if($nDEBUG){ print "$Query<BR>"; }
				if($nAction_use_adodb){
					$Link->Execute($Query) or die("An error occured while adding item to database: ".$Link->ErrorMsg());
					$nMySQLInsertID = "";
				} else {
					mysql_select_db($DBName);
					mysql_query($Query, $Link) or die("An error occured while adding item to database: ".mysql_error());
					$nMySQLInsertID = mysql_insert_id();
					if($nDEBUG){ print "Last inserted ID is available in variable 'formObject->InsertID' with value '$nMySQLInsertID'<BR>"; }
				}
			}
		}
		if($nAction_modifydb && $nAction_modifydb_id && $nAction_modifydb_field){
			$nQuerySetARRAY = array();
			foreach($nPOST as $key => $val) {
				// Encoding
				if(in_array($key,$nEncode_RC4ARRAY) && $val!="" && $nRC4Key!=""){ $val = trim(rc4Encrypt("$nRC4Key",$val)); }
				// add to query set array
				if(!in_array($key,$nSQLNoQuotesARRAY)){ $nQuerySetARRAY[] = "$key='$val'"; } else { $nQuerySetARRAY[] = "$key=$val"; }
			}
			$nQuerySet = implode(",",$nQuerySetARRAY);
			if($nQuerySet){
				$Query = "UPDATE $nAction_modifydb SET $nQuerySet WHERE $nAction_modifydb_field=$nAction_modifydb_id";
				if($nDEBUG){ print "$Query<BR>"; }
				if($nAction_use_adodb){
					$Link->Execute($Query) or die("An error occured while editing item in database: ".$Link->ErrorMsg());
				} else {
					mysql_select_db($DBName);
					mysql_query($Query, $Link) or die("An error occured while editing item in database: ".mysql_error());
				}
			}
		}
		// Make any database translations prior to emailing
		foreach($nPOST as $key => $val) {
			foreach($nTranslateARRAY as $nToBeTranslated) {
				$nToBeTranslatedARRAY = array();
				$nToBeTranslatedARRAY = explode("_",$nToBeTranslated);
				$nFieldToBeTranslated = $nToBeTranslatedARRAY[0];
				if($key == $nFieldToBeTranslated){
					$nDBTableToBeTranslated = $nToBeTranslatedARRAY[1];
					$nDBFieldToBeTranslated = $nToBeTranslatedARRAY[2];
					if($val){ $nPOST["$key"] = nTranslate($val,$nDBTableToBeTranslated,$nDBFieldToBeTranslated); }
				}
			}
		}
		// Email any recipients
		foreach($nAction_emailARRAY as $nEmailRecipient) {
			$nEmailRecipient = str_replace("(at)","@",$nEmailRecipient);
			if(validate_email($nEmailRecipient)){
				////////////////////////////// (inline nSendHTMLEmail function)
				$mail = new PHPMailer();
				$mail->IsHTML(true);
				$mail->SetLanguage( 'en', 'phpmailer/language/' );
				if($nUseSendMail){
					$mail->isSendMail();
				} else {
					$mail->IsSMTP(); // telling the class to use SMTP
					$mail->SMTPAuth = "true";
				}
				if($nMailHost){ $mail->Host = $nMailHost; } // SMTP server
				if($nMailHost && $nMailUser){ $mail->Username = $nMailUser; } //valid email id of the domain
				if($nMailHost && $nMailPass){ $mail->Password = $nMailPass; } //password for abc@xyz
				$mail->From = $nMailFrom;
				$mail->FromName = $nMailFromName;
				$mail->AddAddress($nEmailRecipient);
				$mail->Subject = $nEmailSubject;
				$mail->Body = parseBodyFile($nAction_email_bodyFile);
				if($nDEBUG){ $mail->SMTPDebug = true; }
				if(!$mail->Send()) {
					$nError.= $mail->ErrorInfo;
					if($nDEBUG){ $nRedirect = "$nRedirect?$nError"; }
					$mailProgression.= date('m/d/Y h:i:s A')." - Email sent to '<b>$to</b>' - Status: <span style=\"color:red;\">ERROR</span> ($nError)<BR>";
				} else {
					$to = str_replace("<","&lt;",$to);
					$to = str_replace(">","&gt;",$to);
					$mailProgression.= date('m/d/Y h:i:s A')." - Email sent to '<b>$to</b>' - Status: <span style=\"color:green;\">SUCCESSFUL</span><BR>";
				}
				//////////////////////////////
			}
		}
		if(!$nDEBUG){ $nFormProcessed = 1; } else { print "<BR>Form successfully processed!"; }
	} else {
		//$nError = "<ul>$nError</ul>";
		$nError = "<div align=\"left\"><ul class=\"system_messages\">$nError</ul></div>";
	}
}

function parseBodyFile($nBodyFile){
	global $_POST;
	if(!$nBodyFile){ return ""; }
	// Pull in file
	$nDBConnFile = fopen($nBodyFile,"r");
	if($nDBConnFile){
		$nFileCode = fread($nDBConnFile,filesize($nBodyFile));
		fclose($nDBConnFile);
	} else { return ""; }
	// Parse file
	foreach($_POST as $key => $val) {
		$nFileCode = str_replace("[$key]","$val",$nFileCode);
	}
	// Cleans up untouched elements
	do{
		$nOpenerTag = "["; $nCloserTag = "]"; $nTagParamDelim="_";
		$nOpenerPos = strpos($nFileCode,$nOpenerTag);
		$nCloserPos = strpos($nFileCode,$nCloserTag,$nOpenerPos);
		if($nOpenerPos!==false && $nCloserPos!==false){
			$nInnerTag = substr($nFileCode,($nOpenerPos+strlen($nOpenerTag)),($nCloserPos-strlen($nCloserTag)-$nOpenerPos));
			$nReplacement = "";
			$nInnerTagARRAY = explode($nTagParamDelim,$nInnerTag);
			$nTemplateItem = $nInnerTagARRAY[0];
			unset($nInnerTagARRAY[0]);
			// add any additional replacements here
			switch($nTemplateItem){
				case "fill_with_replacement":
					$nReplacement = "";
					break;
			}
			$nFileCode = str_replace(($nOpenerTag.$nInnerTag.$nCloserTag),$nReplacement,$nFileCode);
		}
	} while($nOpenerPos!==false);
	return $nFileCode;
}

function nTranslate($nFieldToBeTranslated,$nDBTableToBeTranslated,$nDBFieldToBeTranslated){
	global $DBName, $Link;
	$nTable= "";
	$Query = "SELECT $nDBFieldToBeTranslated AS nTranslated FROM $nDBTableToBeTranslated WHERE nID='$nFieldToBeTranslated'";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	while ($Row = mysql_fetch_array($Result)) {
		$nTranslated = $Row["nTranslated"];
	}
	return $nTranslated;
}
?>