[Pro] FormsToGo and Shopping Cart Script Conflict

Hello Everyone,

As you may already be aware we are implementing a shopping cart script into Freeway. I’ve run into an issue with a PHP FormsToGo submit form and my shopping cart script being on the same page. I have already reached out and waiting to hear from FormsToGo and thought I would try here.

I’ve tested several things and found out the if I delete a section of my shopping cart script, the submit form works. Below I’ve listed the error message I get, problematic code from shopping cart and FormsToGo code. Does anyone have any suggestions.

ERROR MESSAGE:
Could not execute SQL query:
SElECT * FROM WHERE products_id = 18

CODE FROM SCRIPT (IF REMOVED SUMBIT FOR WORKS):

<?php
// using list because we want to control the layouts just in css
    $pages = buildPageNumbers(mysql_num_rows($sql_result), $SETTINGS_DB['products_per_page'], $current, $SETTINGS["pages_delta"], $SETTINGS["pages_first_last"]);
    
    $sql_result = mysql_query($sql, $connection) or die ('Could not execute SQL query:<br />'.$sql.'<br /><strong>'.mysql_error().'</strong>');
    
    $rowCounter = 1;
    $js = '';
    
    while ($product = mysql_fetch_assoc($sql_result)) {
        $pav = getAvailableProductAttributes($product['products_id']);
        
        foreach ($pav as $key => $attr) {
            asort($attr['values']);
            $pav[$key] = $attr;
        }			
        
        if ($SETTINGS_DB['products_layout'] == 1) { // LIST VIEW
?>


<?php
if ($rowCounter == $SETTINGS_DB['grid_columns']) {
        echo '<div class="clear"></div>';
        $rowCounter = 0;
    }
}

$rowCounter++;
if (intval($product['digital']) != 1) {
    $js .= 'getPrice(document.getElementById("productForm_'.intval($product['products_id']).'"), "selectClass_'.intval($product['products_id']).'", "'.$SETTINGS["installFolder"].'frontend/include/ajax_price.php");'."n";
}
}
?>

CODE FROM FORMS TO GO:

<?PHP
######################################################
#                                                    #
#                Forms To Go 4.5.4                   #
#             http://www.bebosoft.com/               #
#                                                    #
######################################################




define('kOptional', true);
define('kMandatory', false);

define('kStringRangeFrom', 1);
define('kStringRangeTo', 2);
define('kStringRangeBetween', 3);
        
define('kYes', 'yes');
define('kNo', 'no');




error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('track_errors', true);

function ListArray($theArray) {
 return @implode(", ", $theArray);
}

function DoStripSlashes($fieldValue)  { 
// temporary fix for PHP6 compatibility - magic quotes deprecated in PHP6
 if ( function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc() ) { 
  if (is_array($fieldValue) ) { 
   return array_map('DoStripSlashes', $fieldValue); 
  } else { 
   return trim(stripslashes($fieldValue)); 
  } 
 } else { 
  return $fieldValue; 
 } 
}

function FilterCChars($theString) {
 return preg_replace('/[x00-x1F]/', '', $theString);
}

function ProcessTextField(&$codeHtmlForm, $fieldName, $fieldValue) {

 $tagPattern = '/(<input[^>]+name=['"]?Q' . $fieldName . 'E['"s]+[^>]*>)/i';
 preg_match($tagPattern, $codeHtmlForm, $matches);

 $htmlTag = $matches[1];
 $valuePattern = '/value=['"]?[^'"]*['"]+/i';
 $replacementPattern = 'value="' . $fieldValue . '" ';
 
 if (preg_match($valuePattern, $htmlTag)) {
  $htmlTagToReplace = preg_replace($valuePattern, $replacementPattern, $htmlTag);
 } else {
  $valuePattern = '/([^>/]*)([/]?>)/';
  $replacementPattern = '1 value="' . $fieldValue . '" 2';
  $htmlTagToReplace = preg_replace($valuePattern, $replacementPattern, $htmlTag);
 }

 $codeHtmlForm = preg_replace($tagPattern, $htmlTagToReplace, $codeHtmlForm);

}

function ProcessTextArea(&$codeHtmlForm, $fieldName, $fieldValue) {

 $tagPattern = '/(<textarea[^>]+name=['"]?Q' . $fieldName . 'E['"s]+[^>]*)>(.*?)(</textarea>)/is';
 $replacementPattern = '1>' . $fieldValue . '3';

 $codeHtmlForm = preg_replace($tagPattern, $replacementPattern, $codeHtmlForm);

}

function ProcessCheckBoxes(&$codeHtmlForm, $fieldName, $fieldValues) {

 # Get all check boxes tags with the fieldname
 $tagPattern = '/(<input[^>]+name=['"]?Q' . $fieldName . 'E([]|)['"s]+[^>]*>)/i';

 $numMatches = preg_match_all($tagPattern, $codeHtmlForm, $matches);

 #Strip all the 'checked' attributes previously set
 for ($cnt = 0; $cnt < $numMatches; $cnt++) {

  $checkedPattern = '/([s]+checked="checked"|[s]+checked)([^>]*)>/i';
  $replacementPattern = '2>';
  
  $htmlTag = $matches[1][$cnt];

  if (preg_match($checkedPattern, $htmlTag)) {
   $htmlTagToUncheck = preg_replace($checkedPattern, $replacementPattern, $htmlTag);
   $matches[1][$cnt] = $htmlTagToUncheck;

   $codeHtmlForm = str_replace($htmlTag, $htmlTagToUncheck, $codeHtmlForm);
  }

 }

 # Find the tags that must be checked
 
 if (!is_array($fieldValues)) {
  if (strlen($fieldValues) > 0) {
   $fieldValues = array($fieldValues);
  } else {
   return;
  }
 }

 foreach ($fieldValues as $fieldValue) {
  $valuePattern = '/value=['"]?Q' . $fieldValue . 'E['"]+/i';
 
  for ($cnt = 0; $cnt < $numMatches; $cnt++) {

   $htmlTag = $matches[1][$cnt];

   if ( preg_match($valuePattern, $htmlTag) ) {
    break;
   }

  }

  $checkedPattern = '/([s]*)([/]?)>$/i';
  $replacementPattern = ' checked="checked"12>';
  $htmlTagToCheck = preg_replace($checkedPattern, $replacementPattern, $htmlTag);

  $codeHtmlForm = str_replace($htmlTag, $htmlTagToCheck, $codeHtmlForm);
 }

}

function ProcessPHPFile($PHPFile) {
 
 ob_start();
 
 if (file_exists($PHPFile)) {
  require $PHPFile;
 } else {
  echo '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>Error</title></head><body>Forms To Go - Error: Unable to load HTML form: ' . $PHPFile . '</body></html>';
  exit;
 }
 
 return ob_get_clean();
}

function CheckString($value, $low, $high, $mode, $limitAlpha, $limitNumbers, $limitEmptySpaces, $limitExtraChars, $optional) {

 $regEx = '';

 if ($limitAlpha == kYes) {
  $regExp = 'A-Za-z';
 }
 
 if ($limitNumbers == kYes) {
  $regExp .= '0-9'; 
 }
 
 if ($limitEmptySpaces == kYes) {
  $regExp .= ' '; 
 }

 if (strlen($limitExtraChars) > 0) {
 
  $search = array('', '[', ']', '-', '$', '.', '*', '(', ')', '?', '+', '^', '{', '}', '|', '/');
  $replace = array('', '[', ']', '-', '$', '.', '*', '(', ')', '?', '+', '^', '{', '}', '|', '/');

  $regExp .= str_replace($search, $replace, $limitExtraChars);

 }

 if ( (strlen($regExp) > 0) && (strlen($value) > 0) ){
  if (preg_match('/[^' . $regExp . ']/', $value)) {
   return false;
  }
 }

 if ( (strlen($value) == 0) && ($optional === kOptional) ) {
  return true;
 } elseif ( (strlen($value) >= $low) && ($mode == kStringRangeFrom) ) {
  return true;
 } elseif ( (strlen($value) <= $high) && ($mode == kStringRangeTo) ) {
  return true;
 } elseif ( (strlen($value) >= $low) && (strlen($value) <= $high) && ($mode == kStringRangeBetween) ) {
  return true;
 } else {
  return false;
 }

}


function CheckEmail($email, $optional) {
 if ( (strlen($email) == 0) && ($optional === kOptional) ) {
  return true;
  } elseif ( preg_match("/^([w!#$%&'*+-/=?^`{|}~]+.)*[w!#$%&'*+-/=?^`{|}~]+@((((([a-z0-9]{1}[a-z0-9-]{0,62}[a-z0-9]{1})|[a-z]).)+[a-z]{2,6})|(d{1,3}.){3}d{1,3}(:d{1,5})?)$/i", $email) == 1 ) {
  return true;
 } else {
  return false;
 }
}




if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
 $clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
 $clientIP = $_SERVER['REMOTE_ADDR'];
}

$FTGContactName = DoStripSlashes( $_POST['ContactName'] );
$FTGContactEmail = DoStripSlashes( $_POST['ContactEmail'] );
$FTGContactPhone = DoStripSlashes( $_POST['ContactPhone'] );
$FTGContactInterest = DoStripSlashes( $_POST['ContactInterest'] );
$FTGContactComments = DoStripSlashes( $_POST['ContactComments'] );
$FTGContactSubmit = DoStripSlashes( $_POST['ContactSubmit'] );

$List_ContactInterest = ListArray($FTGContactInterest);


$validationFailed = false;

# Fields Validations


if (!CheckString($FTGContactName, 1, 0, kStringRangeFrom, kNo, kNo, kNo, '', kMandatory)) {
 $FTGErrorMessage['ContactName'] = 'Enter Your Name';
 $validationFailed = true;
}

if (!CheckEmail($FTGContactEmail, kMandatory)) {
 $FTGErrorMessage['ContactEmail'] = 'Enter Valid Email Address';
 $validationFailed = true;
}

if (!CheckString($FTGContactPhone, 1, 0, kStringRangeFrom, kNo, kNo, kNo, '', kMandatory)) {
 $FTGErrorMessage['ContactPhone'] = 'Enter Your Phone Number';
 $validationFailed = true;
}

if (!CheckString($List_ContactInterest, 1, 0, kStringRangeFrom, kNo, kNo, kNo, '', kMandatory)) {
 $FTGErrorMessage['ContactInterest'] = 'Select Your Interest';
 $validationFailed = true;
}



# Display HTML form with filled values

if ($validationFailed === true) {

 $fileHtmlForm = '/vservers/example/htdocs/contact.php';
 
 $codeHtmlForm = ProcessPHPFile($fileHtmlForm);

 ProcessTextField($codeHtmlForm, 'ContactName', $FTGContactName);
 ProcessTextField($codeHtmlForm, 'ContactEmail', $FTGContactEmail);
 ProcessTextField($codeHtmlForm, 'ContactPhone', $FTGContactPhone);
 ProcessCheckBoxes($codeHtmlForm, 'ContactInterest', $FTGContactInterest);
 ProcessTextArea($codeHtmlForm, 'ContactComments', $FTGContactComments);


 $errorList = @implode("<br />n", $FTGErrorMessage);
 $codeHtmlForm = str_replace('<!--VALIDATIONERROR-->', $errorList, $codeHtmlForm);

 $codeHtmlForm = str_replace('<!--FIELDVALUE:ContactName-->', $FTGContactName, $codeHtmlForm);
 $codeHtmlForm = str_replace('<!--FIELDVALUE:ContactEmail-->', $FTGContactEmail, $codeHtmlForm);
 $codeHtmlForm = str_replace('<!--FIELDVALUE:ContactPhone-->', $FTGContactPhone, $codeHtmlForm);
 $codeHtmlForm = str_replace('<!--FIELDVALUE:ContactInterest-->', $List_ContactInterest, $codeHtmlForm);
 $codeHtmlForm = str_replace('<!--FIELDVALUE:ContactComments-->', $FTGContactComments, $codeHtmlForm);
 $codeHtmlForm = str_replace('<!--FIELDVALUE:ContactSubmit-->', $FTGContactSubmit, $codeHtmlForm);
 $codeHtmlForm = str_replace('<!--ERRORMSG:ContactName-->', $FTGErrorMessage['ContactName'], $codeHtmlForm);
 $codeHtmlForm = str_replace('<!--ERRORMSG:ContactEmail-->', $FTGErrorMessage['ContactEmail'], $codeHtmlForm);
 $codeHtmlForm = str_replace('<!--ERRORMSG:ContactPhone-->', $FTGErrorMessage['ContactPhone'], $codeHtmlForm);
 $codeHtmlForm = str_replace('<!--ERRORMSG:ContactInterest-->', $FTGErrorMessage['ContactInterest'], $codeHtmlForm);


 if (count( array_filter( $FTGErrorMessage ) ) > 0 ) {
  
  foreach( $FTGErrorMessage as $key => $message ) {
   $ErrorMessage .= trim( str_replace("'", "'", $message ) ) . 'n';
  }
  $alertJSErrorMessage = "window.alert('" . $ErrorMessage . "');";
  
  $onloadPattern = '/(<body[^>]+onload=["]*)"([^>]*)>/i';
  
  if ( preg_match( $onloadPattern, $codeHtmlForm ) ) {
   $replacementPattern = '1"' . $alertJSErrorMessage . '2>';
  } else {
   $onloadPattern = '/(<body[^>]*)>/i';
   $replacementPattern = '1 onload="' . $alertJSErrorMessage . '">';
  }
  
  $codeHtmlForm = preg_replace( $onloadPattern, $replacementPattern, $codeHtmlForm);
  
 }
 echo $codeHtmlForm;

}

if ( $validationFailed === false ) {

 # Email to Form Owner
  
 $emailSubject = FilterCChars("Inquiry From Contact Page");
  
 $emailBody = "You have received an inquiry on your Contact page. Below is the information given:n"
  . "n"
  . "n"
  . "Name : $FTGContactNamen"
  . "n"
  . "Phone : $FTGContactPhonen"
  . "Email : $FTGContactEmailn"
  . "n"
  . "n"
  . "Interested In : $List_ContactInterestn"
  . "n"
  . "Comments : n"
  . "n"
  . "$FTGContactCommentsn"
  . "";
  $emailTo = 'Christian Balmer <email@hidden>';
   
  $emailFrom = FilterCChars("email@hidden");
   
  $emailHeader = "From: $emailFromn"
   . "MIME-Version: 1.0n"
   . "Content-type: text/plain; charset="UTF-8"n"
   . "Content-transfer-encoding: 8bitn";
   
  mail($emailTo, $emailSubject, $emailBody, $emailHeader);
  
  
 # Confirmation Email to User
  
 $confEmailTo = FilterCChars($FTGContactEmail);
  
 $confEmailSubject = FilterCChars("Thank You For Your Inquiry");
  
 $confEmailBody = "Hi #Name#,n"
  . "n"
  . "Thank you for your inquiry in Xtremity Beauty Supply. We have received your information and someone will respond shortly.n"
  . "n"
  . "n"
  . "Sincerly,n"
  . "n"
  . "Xtremity Beauty Supply";
  
 $confEmailHeader = "From: email@hidden"
  . "MIME-Version: 1.0n"
  . "Content-type: text/plain; charset="UTF-8"n"
  . "Content-transfer-encoding: 8bitn";
  
 mail($confEmailTo, $confEmailSubject, $confEmailBody, $confEmailHeader);
  


# Embed success page and dump it to the browser

$fileSuccessPage = '/vservers/example/htdocs/contact.php';

if (file_exists($fileSuccessPage) === false) {
 echo '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>Error</title></head><body>The success page: <b> ' . $fileSuccessPage . '</b> cannot be found on the server.</body></html>';
 exit;
}

$successPage = ProcessPHPFile($fileSuccessPage);

$successPage = str_replace('<!--FIELDVALUE:ContactName-->', $FTGContactName, $successPage);
$successPage = str_replace('<!--FIELDVALUE:ContactEmail-->', $FTGContactEmail, $successPage);
$successPage = str_replace('<!--FIELDVALUE:ContactPhone-->', $FTGContactPhone, $successPage);
$successPage = str_replace('<!--FIELDVALUE:ContactInterest-->', $List_ContactInterest, $successPage);
$successPage = str_replace('<!--FIELDVALUE:ContactComments-->', $FTGContactComments, $successPage);
$successPage = str_replace('<!--FIELDVALUE:ContactSubmit-->', $FTGContactSubmit, $successPage);


echo $successPage;

}

?>

TeamSDA_Christian


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

It sounds a lot like you have nested forms in your layout. Have you applied the Multiple Forms Action suite to your page and forms?

Walter

On Nov 29, 2011, at 9:26 PM, TeamSDA wrote:

Hello Everyone,

As you may already be aware we are implementing a shopping cart script into Freeway. I’ve run into an issue with a PHP FormsToGo submit form and my shopping cart script being on the same page. I have already reached out and waiting to hear from FormsToGo and thought I would try here.


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

Hi Walt,

Yeah that was my first though up the Multiple Form action is already applied to the container on my form. As well as “No Form” action is on the page.

Christian


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

Can you post a link to the page? If not, can you run it through the W3 validator and see what moles raise their heads to be whacked?

Walter

On Nov 29, 2011, at 9:37 PM, TeamSDA wrote:

Hi Walt,

Yeah that was my first though up the Multiple Form action is already applied to the container on my form. As well as “No Form” action is on the page.

Christian


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

That SQL error is coming up because your query is missing the name of the table it’s supposed to be searching. I can see that from the raw query dumped out by the error message. But I can’t see what created that SQL, so I don’t know why it’s happening. It seems, though, as if one form is submitting to another form’s handler.

Walter

On Nov 29, 2011, at 9:37 PM, TeamSDA wrote:

Hi Walt,

Yeah that was my first though up the Multiple Form action is already applied to the container on my form. As well as “No Form” action is on the page.

Christian


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options

The code passed the validation. Below I have included more of my script. The form is on the contact.php page. Above the opening tag it requires the load.php page. At the bottom of the load.php code the is a require for include/products.php. That is were the code that breaks the form is located.

If you would like I could email you a link but I don’t feel comfurtable putting a link on Freeway.

ON THE TOP OF contact.php (Page with form):

<?php
session_start();
ob_start();
require_once ("/vservers/example/htdocs/Script_Shopping/frontend/load.php");
$content = ob_get_contents();
ob_end_clean();
?>

REQUIRES load.php (Code Below):

<?php
require_once (dirname(__FILE__).'/../include.php');
require_once (dirname(__FILE__).'/../include/functions.php');
require_once (dirname(__FILE__).'/lang/lang_en.php');

?>
<script>
var _data = {
	installFolder: '<?php echo $SETTINGS["installFolder"]; ?>',
	URL: '<?php echo $SETTINGS["URL"]; ?>'
};
</script>
<?php

// Set the action if needed
$_REQUEST['ac'] = (empty($_REQUEST['ac'])) ? 'products' : $_REQUEST['ac'];

// Assign the system messages to a variable and clear the $_SESSION['cartSysMessage']
if (!empty($_SESSION['ssc_msg'])) {
	$sys_message = $_SESSION['ssc_msg'];
	
	unset($_SESSION['ssc_msg']);
} else {
	$sys_message = '';
}

if ($_REQUEST['ac'] == 'addToCart') {
	$_REQUEST['attributes'] = (empty($_REQUEST['attributes'])) ? array() : $_REQUEST['attributes'];

	$result = getProductPrice($_REQUEST['id'], $_REQUEST['attributes']);
	
	// if product has valid quantity and price
	if ($result) {
		// add new cart entry
		if (is_array($_SESSION['ssc_products']) && array_key_exists($result['pav_id'], $_SESSION['ssc_products'])) {
			$_SESSION['ssc_products'][$result['pav_id']] += 1;
		} else {
			$_SESSION['ssc_products'][$result['pav_id']] = 1;
		}
		
		$_SESSION['ssc_msg'] = $SC_LANG['sys_msg_7'];
		redirect('viewcart.php?ac=shoppingCart');
	} else {
		$_SESSION['ssc_msg'] = $SC_LANG['sys_msg_8'];
		redirect('viewcart.php?ac=shoppingCart');
	}
} elseif ($_REQUEST['ac'] == 'updateShoppingCart') {
	$message = '';
	
	foreach ($_REQUEST['quantity'] as $key => $val) {
		$val = intval($val);
		
		if ($val > 0) {
			// for each product in the cart check if inserted quantity is equal or less then the available qunatity
			$sql = "SELECT * FROM ".$TABLES['PRODUCT_ATTRIBUTE_VALUES']." AS pav LEFT JOIN ".$TABLES['PRODUCTS']." AS p ON pav.products_id = p.products_id  WHERE pav.pav_id = ".intval($key)." LIMIT 1";
			$sql_result = mysql_query($sql, $connection) or die ('Could not execute SQL query:<br />'.$sql.'<br /><strong>'.mysql_error().'</strong>');
			$result = mysql_fetch_assoc($sql_result);
			
			if (!empty($result)) {
				if (intval($result['digital']) != 1 && intval($result['quantity']) < $val) {
					if (empty($message)) {
						if (count($_REQUEST['quantity']) > 1) {
							$message = $SC_LANG['sys_msg_2'];
						} else {
							$message = $SC_LANG['sys_msg_4'];
						}
					}
				} else {
					$_SESSION['ssc_products'][$key] = $val;
				}
			} else {
				unset($_SESSION['ssc_products'][$key]);
				$message = $SC_LANG['sys_msg_3'];
			}
		}
	}
	
	if (empty($message)) { $message = $SC_LANG['sys_msg_1']; }
	
	$_SESSION['ssc_msg'] = $message;
	redirect('viewcart.php?ac=shoppingCart');
} elseif ($_REQUEST['ac'] == 'removeProduct') {
	unset($_SESSION['ssc_products'][intval($_REQUEST['id'])]);
	
	$_SESSION['ssc_msg'] = $SC_LANG['sys_msg_5'];
	redirect('viewcart.php?ac=shoppingCart');
} elseif ($_REQUEST['ac'] == 'checkoutComplete') {
	
	if (isClientLogged()) {
		$email = saveToDB($_SESSION['ssc_login']['email']);
		$pass = saveToDB($_SESSION['ssc_login']['password']);
	} else {
		$email = saveToDB($_REQUEST['email']);
		$pass = saveToDB($_REQUEST['pass']);
	}
	
	$sql = "SELECT * FROM ".$TABLES['CLIENTS']." WHERE email = '".saveToDB($_REQUEST['email'])."'";
	$sql_result = mysql_query($sql, $connection) or die ('Could not execute SQL query:<br />'.$sql.'<br /><strong>'.mysql_error().'</strong>');
	$userData = mysql_fetch_assoc($sql_result);
	
	if (!isClientLogged() && $userData) {
		$_SESSION['ssc_msg'] = $SC_LANG['sys_msg_15'];
		redirect(_SELF_.'?ac=login');
	} else {
		
		if (!isClientLogged()) {
			$sql = "INSERT INTO ".$TABLES["CLIENTS"]."
					SET is_tax_exempt = 0,
						client_discount = 0,
						name = '".saveToDB($_REQUEST['name'])."',
						phone = '".saveToDB($_REQUEST['phone'])."',
						email = '".$email."',
						password = '".$pass."',
						web = '".saveToDB($_REQUEST['web'])."',
						address_1 = '".saveToDB($_REQUEST['address_1'])."',
						address_2 = '".saveToDB($_REQUEST['address_2'])."',
						city = '".saveToDB($_REQUEST['city'])."',
						state = '".saveToDB($_REQUEST['state'])."',
						zip = '".saveToDB($_REQUEST['zip'])."',
						country = '".saveToDB($_REQUEST['country'])."'";
			$sql_result = mysql_query($sql, $connection) or die ('Could not execute SQL query:<br />'.$sql.'<br /><strong>'.mysql_error().'</strong>');
			$client_id = mysql_insert_id();
		} else {
			$client_id = $_SESSION['ssc_login']['id'];
		}
		
		// add order
		$number = time();
		$prices = caculateShoppingPrice();
		
		$sql = "INSERT INTO ".$TABLES["ORDERS"]."
				SET client_id = '".intval($client_id)."',
					locations_id = '".intval($_REQUEST['locations_id'])."',
					number = '".saveToDB($number)."',
					status = 1,
					price = ".floatval($prices['basis_price']).",
					discount = ".floatval($prices['discount_price']).",
					discount_customer = ".floatval($prices['discount_price_customer']).",
					shipping = ".floatval($prices['shipping_price']).",
					tax = ".floatval($prices['tax_price']).",
					used_promo_code = '".saveToDB($_REQUEST['promo_code'])."',
					name = '".saveToDB($_REQUEST['name'])."',
					phone = '".saveToDB($_REQUEST['phone'])."',
					email = '".$email."',
					password = '".$pass."',
					web = '".saveToDB($_REQUEST['web'])."',
					address_1 = '".saveToDB($_REQUEST['address_1'])."',
					address_2 = '".saveToDB($_REQUEST['address_2'])."',
					city = '".saveToDB($_REQUEST['city'])."',
					state = '".saveToDB($_REQUEST['state'])."',
					zip = '".saveToDB($_REQUEST['zip'])."',
					country = '".saveToDB($_REQUEST['country'])."',
					notes = '".saveToDB($_REQUEST['notes'])."',
					payment_processing = '".saveToDB($_REQUEST['payment_processing'])."',
					cc_type = ".intval($_REQUEST['cc_type']).",
					cc_number = '".saveToDB($_REQUEST['cc_number'])."',
					cc_exp_date = '".saveToDB($_REQUEST['cc_exp_date'])."',
					cc_security_code = '".saveToDB($_REQUEST['cc_security_code'])."',
					date_added = NOW()";
		$sql_result = mysql_query($sql, $connection) or die ('Could not execute SQL query:<br />'.$sql.'<br /><strong>'.mysql_error().'</strong>');
		$id = mysql_insert_id();
		
		//set as logged in
		$sql = "SELECT * FROM ".$TABLES['CLIENTS']." WHERE id = ".intval($client_id)." LIMIT 1";
		$sql_result = mysql_query($sql, $connection) or die ('Could not execute SQL query:<br />'.$sql.'<br /><strong>'.mysql_error().'</strong>');
		$client = mysql_fetch_assoc($sql_result);
		$_SESSION['ssc_login'] = (!empty($client) && is_array($client)) ? $client : array();
		
		// add order products
		$valueTitles = getValuesTitles();
		$forEmail = '';
		
		foreach ($_SESSION['ssc_products'] as $key => $val) {
			$sql = "SELECT * FROM ".$TABLES['PRODUCT_ATTRIBUTE_VALUES']." AS pav LEFT JOIN ".$TABLES['PRODUCTS']." AS p ON pav.products_id = p.products_id WHERE pav.pav_id = ".intval($key)." LIMIT 1";
			$sql_result = mysql_query($sql, $connection) or die ('Could not execute SQL query:<br />'.$sql.'<br /><strong>'.mysql_error().'</strong>');
			$product = mysql_fetch_assoc($sql_result);
			
			$implode = array();
			for ($i = 1; $i <= 10; $i++) {
				if ($product['av_id_'.$i] > 0) {
					$implode[] = $valueTitles[$product['av_id_'.$i]]['attribute_title'].': '.$valueTitles[$product['av_id_'.$i]]['value_title'];
				}
			}
			
			// insert order product
			$sql = "INSERT INTO ".$TABLES['ORDER_PRODUCTS']."
					SET client_id = ".intval($client_id).",
						orders_id = ".intval($id).",
						pav_id = ".intval($key).",
						attributes_string = '".saveToDB(implode(', ', $implode))."',
						quantity = ".intval($val).",
						price = ".floatval($product['price'])."";
			$sql_result = mysql_query($sql, $connection) or die ('Could not execute SQL query:<br />'.$sql.'<br /><strong>'.mysql_error().'</strong>');
			
			$forEmail .= $val.' X '.$product['product_title'].' - '.implode(', ', $implode)."<br/>";
			
			// update product attribute value quantity
			if (intval($product['digital'])) {
				$quantity = '0';
			} else {
				$quantity = "quantity - ".intval($val);
			}
			
			$sql = "UPDATE ".$TABLES['PRODUCT_ATTRIBUTE_VALUES']." SET quantity = ".$quantity." WHERE pav_id = ".intval($key);
			$sql_result = mysql_query($sql, $connection) or die ('Could not execute SQL query:<br />'.$sql.'<br /><strong>'.mysql_error().'</strong>');
		}
		
		// send confimation email
		$formFields = unserialize($SETTINGS_DB['booking_form_fileds']);
		
		$subject = "Order Received [ID: ".$number."]";
		$mailheader = "From: ".stripslashes($SETTINGS_DB["admin_email"])."rn";
		$mailheader .= "Reply-To: ".stripslashes($SETTINGS_DB["admin_email"])."rn";
		$mailheader .= "Content-type: text/html; charset=UTF-8rnrnrn";
	
		$Message_body = "Order ID: ".$number."<br /><br />";
		
		foreach ($formFields as $key => $val) {
			if (!empty($_REQUEST[$val])) {
				$Message_body .= $OPTIONS_FORM_FIELDS[$val]['label'].': '.$_REQUEST[$val]."<br />";
			}
		}
		
		$Message_body .= "<br />Price: ".formatPrice($prices['basis_price'])."<br />";
		$Message_body .= "Discount: ".formatPrice($prices['discount_price'])."<br />";
		$Message_body .= "Shipping: ".formatPrice(floatval($prices['shipping_price']))."<br />";
		$Message_body .= "Tax: ".formatPrice(floatval($prices['tax_price']))."<br />";
		$Message_body .= "Total: ".formatPrice($prices['total_price'])."<br /><br />";
		$Message_body .= "Products:<br />";
		$Message_body .= $forEmail;
		
		mail(stripslashes($SETTINGS_DB["admin_email"]), $subject, $Message_body, $mailheader);
		
		if ($email != '') {
			//mail($email, $subject, $Message_body, $mailheader);
		}
		
		// remove the products from session
		unset($_SESSION['ssc_products']);
		
		if (!empty($_REQUEST["payment_processing"]) && $_REQUEST["payment_processing"] != 'credit_card') {
			$_SESSION['ssc_msg'] = $SC_LANG['sys_msg_6'];
			redirect(_SELF_.'?ac=gotoPayment&id='.$id);
		} else {
			$_SESSION['ssc_msg'] = $SC_LANG['sys_msg_6'];
			redirect($SETTINGS_DB['thank_you_page']);
		}
	
	} 
	
} elseif ($_REQUEST['ac'] == 'addToFavourites') {
	
	setcookie('StivaShoppingCartFavourites['.intval($_REQUEST['id']).']', intval($_REQUEST['id']), time()+36000);
	$_SESSION['ssc_msg'] = $SC_LANG['sys_msg_10'];
	redirect(_SELF_.'?ac=viewProduct&id='.intval($_REQUEST['id']));
	
} elseif ($_REQUEST['ac'] == 'removeFromFavourites') {
	
	setcookie('StivaShoppingCartFavourites['.intval($_REQUEST['id']).']', intval($_REQUEST['id']), time()-36000);
	
	$_SESSION['ssc_msg'] = $SC_LANG['sys_msg_11'];
	redirect(_SELF_.'?ac=viewProduct&id='.intval($_REQUEST['id']));
	
} elseif ($_REQUEST['ac'] == 'clearFavourites') {
	foreach ($_COOKIE['StivaShoppingCartFavourites'] as $key => $val) {
		setcookie('StivaShoppingCartFavourites['.intval($val).']', intval($val), time()-36000);
	}
	
	$_SESSION['ssc_msg'] = $SC_LANG['sys_msg_12'];
	redirect(_SELF_.'?ac=products');
	
} elseif ($_REQUEST['ac'] == 'sendItToFriend') {
	
	if (!empty($_REQUEST['your_name']) || !empty($_REQUEST['your_email']) || !empty($_REQUEST['friend_name']) || !empty($_REQUEST['friend_email'])) {
		$subject = '';
		$body = '';
		$pattern = array('{YOUR_NAME}', '{FRIEND_NAME}');
		$replacement = array($_REQUEST['your_name'], $_REQUEST['friend_name']);
		
		$mailheader = "From: ".stripslashes($_REQUEST["your_email"])."rn";
		$mailheader .= "Reply-To: ".stripslashes($_REQUEST["your_email"])."rn";
		$mailheader .= "Content-type: text/html; charset=UTF-8rnrnrn";
		
		$subject .= str_replace($pattern, $replacement, $SC_LANG['stf_email_subject']);

		if (!empty($_REQUEST['message'])) {
			$body .= nl2br($_REQUEST['message'])."<br/><br/>";
		}
		
		$body .= '<a href="'.currentPageURL().'?ac=viewProduct&id='.intval($_REQUEST['id']).'">'.currentPageURL().'?ac=viewProduct&id='.intval($_REQUEST['id']).'</a>';
		
		if (mail(stripslashes($_REQUEST["friend_email"]), $subject, $body, $mailheader)) {
			$_SESSION['ssc_msg'] = $SC_LANG['stf_msg_sent'];
			redirect(_SELF_.'?ac=viewProduct&id='.intval($_REQUEST['id']));
		} else {
			$_SESSION['ssc_msg'] = $SC_LANG['stf_msg_not_sent'];
			redirect(_SELF_.'?ac=viewProduct&id='.intval($_REQUEST['id']));
		}
	} else {
		$_SESSION['ssc_msg'] = $SC_LANG['stf_err_incorrect_data'];
		redirect(_SELF_.'?ac=viewProduct&id='.intval($_REQUEST['id']));
	}
	
} elseif ($_REQUEST['ac'] == 'logMeIn') {

	$sql = "SELECT * FROM ".$TABLES['CLIENTS']." WHERE email = '".saveToDB($_REQUEST['email'])."' AND password = '".saveToDB($_REQUEST['pass'])."' LIMIT 1";
	$sql_result = mysql_query($sql, $connection) or die ('Could not execute SQL query:<br />'.$sql.'<br /><strong>'.mysql_error().'</strong>');
	$userData = mysql_fetch_assoc($sql_result);
	
	if ($userData) {
		// loged in
		$_SESSION['ssc_login'] = $userData;
		
		$_SESSION['ssc_msg'] = $SC_LANG['sys_msg_14'];
		redirect(_SELF_.'?ac=login');
	} else {
		$_SESSION['ssc_msg'] = $SC_LANG['sys_msg_13'];
		redirect(_SELF_.'?ac=login');
	}
	
} elseif ($_REQUEST['ac'] == 'sendPassword') {

	$sql = "SELECT * FROM ".$TABLES['CLIENTS']." WHERE id = ".intval($_SESSION['ssc_login']['users_id'])." LIMIT 1";
	$sql_result = mysql_query($sql, $connection) or die ('Could not execute SQL query:<br />'.$sql.'<br /><strong>'.mysql_error().'</strong>');
	$userData = mysql_fetch_assoc($sql_result);
	
	if (!empty($userData)) {
		$mailheader = "From: ".stripslashes($SETTINGS_DB["admin_email"])."rn";
		$mailheader .= "Reply-To: ".stripslashes($SETTINGS_DB["admin_email"])."rn";
		$mailheader .= "Content-type: text/html; charset=UTF-8rn";
		
		$pattern = array('{PASSWORD}');
		$replacement = array($userData['password']);
		
		$body = str_replace($pattern, $replacement, $SC_LANG['lp_body']);
		
		if (mail(stripslashes($userData["email"]), $SC_LANG['lp_subject'], $body, $mailheader)) {
			$_SESSION['ssc_msg'] = $SC_LANG['lp_msg_sent'];
			redirect(_SELF_.'?ac=login');
		} else {
			$_SESSION['ssc_msg'] = $SC_LANG['lp_msg_not_sent'];
			redirect(_SELF_.'?ac=login');
		}
		
	} else {
		$_SESSION['ssc_msg'] = $SC_LANG['lp_msg_not_found'];
		redirect(_SELF_.'?ac=lostPassword');
	}
	
} elseif ($_REQUEST['ac'] == 'logout') {
	
	unset($_SESSION['ssc_login']);
	redirect(_SELF_.'?ac=products');
	
}

// echo starting wrapper
echo '<div id="cart">';

// load header
//require_once (dirname(__FILE__).'/include/header.php');

if ($_REQUEST['ac'] == 'shoppingCart') { // shopping cart
	require_once (dirname(__FILE__).'/include/shopping_cart.php');
} elseif ($_REQUEST['ac'] == 'checkout') { // checkout
	require_once (dirname(__FILE__).'/include/checkout.php');
} elseif ($_REQUEST['ac'] == 'viewProduct') { // view product
	require_once (dirname(__FILE__).'/include/view_product.php');
} elseif ($_REQUEST['ac'] == 'gotoPayment') {
	require_once (dirname(__FILE__).'/include/goto_payment.php');
} elseif ($_REQUEST['ac'] == 'sendToFriend') {
	require_once (dirname(__FILE__).'/include/send_to_friend.php');
} elseif ($_REQUEST['ac'] == 'login') {
	require_once (dirname(__FILE__).'/include/login.php');
} elseif ($_REQUEST['ac'] == 'lostPassword') {
	require_once (dirname(__FILE__).'/include/lost_password.php');
} elseif ($_REQUEST['ac'] == 'pastOrders') {
	require_once (dirname(__FILE__).'/include/past_orders.php');
} else { // show products
	require_once (dirname(__FILE__).'/include/products.php');
}

// echo ending wrapper
echo '</div>';

Christian


freewaytalk mailing list
email@hidden
Update your subscriptions at:
http://freewaytalk.net/person/options