Jump to content

Payment Gateway - Wordpress E-Commerce/Worldpay


freshkid

Recommended Posts

Hello, first post as this is the first time I've made a concerted effort to try and understand PHP...I use the 'paste and hope' method.

 

I've been struggling to make this 'inherited' file work for two days...and my lack of PHP ability is taking me down a joyless path.

 

The script works up to a point, but then I get this:

 

Fatal error: Call to a member function on a non-object in /nfs/c05/h02/mnt/73229/domains/http:myurlheregoeshere.com/html/wp-content/plugins/wp-e-commerce/wpsc-includes/processing.functions.php on line 198

 

Does anyone have any experience with getting Worldpay to work with WP Ecommerce?

 

<?php
$nzshpcrt_gateways[$num]['name'] = 'worldpay';
$nzshpcrt_gateways[$num]['internalname'] = 'worldpay';
$nzshpcrt_gateways[$num]['function'] = 'gateway_worldpay';
$nzshpcrt_gateways[$num]['form'] = "form_worldpay";
$nzshpcrt_gateways[$num]['submit_function'] = "submit_worldpay";


function gateway_worldpay($seperator, $sessionid)
{


global $wpdb;
$purchase_log_sql = "SELECT * FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `sessionid`= ".$sessionid." LIMIT 1";
$purchase_log = $wpdb->get_results($purchase_log_sql,ARRAY_A) ;

$cart_sql = "SELECT * FROM `".WPSC_TABLE_CART_CONTENTS."` WHERE `purchaseid`='".$purchase_log[0]['id']."'";
$cart = $wpdb->get_results($cart_sql,ARRAY_A) ; 
  
// worldpay post variables
$worldpay_url = get_option('worldpay_url');

$data['instId'] = get_option('worldpay_product_id');
$data['cartId'] = get_option('worldpay_product_name');
$data['currency'] = get_option('worldpay_curcode');
$data['language'] = get_option('worldpay_language');
$data['testMode'] = get_option('worldpay_testmode');
$data['cb_url'] = get_option('siteurl')."/?worldpay_callback=true";
$data['cb_type'] = 'P';
$data['decline_url'] = get_option('siteurl')."/?worldpay_callback=true";
$data['cs1'] = $sessionid;
$data['cs2'] = 'worldpay';
$salt = get_option('worldpay_salt');
$data['cs3'] = md5($salt . md5($sessionid . $salt));	// placed in here for security so that the return call can be validated as 'real'	

// User details   
if($_POST['collected_data'][get_option('worldpay_form_first_name')] != '')
    {   
    	$data['f_name'] = $_POST['collected_data'][get_option('worldpay_form_first_name')];
    }
if($_POST['collected_data'][get_option('worldpay_form_last_name')] != "")
    {   
    	$data['s_name'] = $_POST['collected_data'][get_option('worldpay_form_last_name')];
    }
  	if($_POST['collected_data'][get_option('worldpay_form_address')] != '')
    {   
    	$data['street'] = str_replace("\n",', ', $_POST['collected_data'][get_option('worldpay_form_address')]); 
    }
   	if($_POST['collected_data'][get_option('worldpay_form_city')] != '')
    {
    	$data['city'] = $_POST['collected_data'][get_option('worldpay_form_city')]; 
    }
  	if(preg_match("/^[a-zA-Z]{2}$/",$_SESSION['selected_country']))
    {   
    	$data['country'] = $_SESSION['selected_country'];
    }    

  	// Change suggested by waxfeet@gmail.com, if email to be sent is not there, dont send an email address        
    	$email_data = $wpdb->get_results("SELECT `id`,`type` FROM `".WPSC_TABLE_CHECKOUT_FORMS."` WHERE `type` IN ('email') AND `active` = '1'",ARRAY_A);
  	foreach((array)$email_data as $email)
    {
    	$data['email'] = $_POST['collected_data'][$email['id']];
    }
  	if(($_POST['collected_data'][get_option('email_form_field')] != null) && ($data['email'] == null))
    {
    	$data['email'] = $_POST['collected_data'][get_option('email_form_field')];
    }


// Get Currency details abd price
$currency_code = $wpdb->get_results("SELECT `code` FROM `".WPSC_TABLE_CURRENCY_LIST."` WHERE `id`='".get_option('currency_type')."' LIMIT 1",ARRAY_A);
$local_currency_code = $currency_code[0]['code'];
$worldpay_currency_code = get_option('worldpay_curcode');
  
// worldpay only processes in the set currency.  This is USD or EUR dependent on what the Chornopay account is set up with.  
// This must match the worldpay settings set up in wordpress.  Convert to the worldpay currency and calculate total.
$curr=new CURRENCYCONVERTER();
$decimal_places = 2;
$total_price = 0;
  
$i = 1;
  
$all_donations = true;
$all_no_shipping = true;

foreach($cart as $item)
{
$product_data = $wpdb->get_results("SELECT * FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `id`='".$item['prodid']."' LIMIT 1",ARRAY_A);
	$product_data = $product_data[0];
	$variation_count = count($product_variations);
    
	$variation_sql = "SELECT * FROM `".WPSC_TABLE_CART_ITEM_VARIATIONS."` WHERE `cart_id`='".$item['id']."'";
	$variation_data = $wpdb->get_results($variation_sql,ARRAY_A);
	$variation_count = count($variation_data);

	if($variation_count >= 1)
      	{
      		$variation_list = " (";
      		$j = 0;
      		foreach($variation_data as $variation)
        	{
        		if($j > 0)
          		{
          			$variation_list .= ", ";
          		}
        		$value_id = $variation['venue_id'];
        		$value_data = $wpdb->get_results("SELECT * FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `id`='".$value_id."' LIMIT 1",ARRAY_A);
        		$variation_list .= $value_data[0]['name'];              
        		$j++;
        	}
      		$variation_list .= ")";
      	}
      	else
        {
        	$variation_list = '';
        }
    
    	$local_currency_productprice = $item['price'];

	$local_currency_shipping = nzshpcrt_determine_item_shipping($item['prodid'], 1, $_SESSION['delivery_country']);
    	

      		$worldpay_currency_productprice = $local_currency_productprice;
      		$worldpay_currency_shipping = $local_currency_shipping;
  
    	$data['item_name_'.$i] = $product_data['name'].$variation_list;
    	$data['amount_'.$i] = number_format(sprintf("%01.2f", $worldpay_currency_productprice),$decimal_places,'.','');
    	$data['quantity_'.$i] = $item['quantity'];
    	$data['item_number_'.$i] = $product_data['id'];
    	
	if($item['donation'] !=1)
      	{
      		$all_donations = false;
      		$data['shipping_'.$i] = number_format($worldpay_currency_shipping,$decimal_places,'.','');
      		$data['shipping2_'.$i] = number_format($worldpay_currency_shipping,$decimal_places,'.','');      
      	}
      	else
      	{
      		$data['shipping_'.$i] = number_format(0,$decimal_places,'.','');
      		$data['shipping2_'.$i] = number_format(0,$decimal_places,'.','');
      	}
        
    	if($product_data['no_shipping'] != 1) {
      		$all_no_shipping = false;
      	}
    

	$total_price = $total_price + ($data['amount_'.$i] * $data['quantity_'.$i]);

	if( $all_no_shipping != false )
		$total_price = $total_price + $data['shipping_'.$i] + $data['shipping2_'.$i];

    	$i++;
}
   
  	$base_shipping = nzshpcrt_determine_base_shipping(0, $_SESSION['delivery_country']);
  	if(($base_shipping > 0) && ($all_donations == false) && ($all_no_shipping == false))
    {
	$data['handling_cart'] = number_format($base_shipping,$decimal_places,'.','');
	$total_price += number_format($base_shipping,$decimal_places,'.','');
    }

$data['amount'] = $total_price;


// Create Form to post to worldpay
$output = "
	<form id=\"worldpay_form\" name=\"worldpay_form\" method=\"post\" action=\"$worldpay_url\">\n";

foreach($data as $n=>$v) {
		$output .= "			<input type=\"hidden\" name=\"$n\" value=\"$v\" />\n";
}

$output .= "			<input type=\"submit\" value=\"Continue to worldpay\" />
	</form>
";

// echo form.. 
if( get_option('worldpay_debug') == 1)
{
	echo ("DEBUG MODE ON!!<br/>");
	echo("The following form is created and would be posted to worldpay for processing.  Press submit to continue:<br/>");
	echo("<pre>".htmlspecialchars($output)."</pre>");
}

echo($output);

if(get_option('worldpay_debug') == 0)
{
	echo "<script language=\"javascript\" type=\"text/javascript\">document.getElementById('worldpay_form').submit();</script>";
}

  	exit();
}
  
function nzshpcrt_worldpay_callback()
{
global $wpdb;
// needs to execute on page start
// look at page 36
if($_GET['worldpay_callback'] == 'true' && $_POST['cs2'] == 'worldpay')
{
    	// This is a call from worldpay.  validate that it is from a worldpay server in the and process.
	// validate cs3 variable to see if it makes sense for security
	$salt = get_option('worldpay_salt');
	$gen_hash = md5($salt . md5($_POST['cs1'] . $salt));	

	if($gen_hash == $_POST['cs3'])
	{


		// process response.
	    $sessionid = trim(stripslashes($_POST['cs1']));
		$transaction_id = trim(stripslashes($_POST['transaction_id']));
		$verification_data['trans_id'] = trim(stripslashes($_POST['transaction_id']));
		$verification_data['trans_type'] = trim(stripslashes($_POST['transaction_type']));

		switch($verification_data['trans_type'])
		{
			case 'onetime': // All successful processing statuses.
            case 'initial':
			case 'rebill':
            	$wpdb->query("UPDATE `".$wpdb->prefix."purchase_logs` SET 
									`processed` = '2', 
									`transactid` = '".$transaction_id."', 
									`date` = '".time()."'
								WHERE `sessionid` = ".$sessionid." LIMIT 1");

				transaction_results($sessionid, false, $transaction_id);
            	break;                        
            
            case 'decline': // if it fails, delete it
            	$log_id = $wpdb->get_var("SELECT `id` FROM `".$wpdb->prefix."purchase_logs` WHERE `sessionid`='$sessionid' LIMIT 1");
            	$delete_log_form_sql = "SELECT * FROM `".$wpdb->prefix."cart_contents` WHERE `purchaseid`='$log_id'";
            	$cart_content = $wpdb->get_results($delete_log_form_sql,ARRAY_A);
            	foreach((array)$cart_content as $cart_item)
              	{
              		$cart_item_variations = $wpdb->query("DELETE FROM `".$wpdb->prefix."cart_item_variations` WHERE `cart_id` = '".$cart_item['id']."'", ARRAY_A);
              	}
            	$wpdb->query("DELETE FROM `".$wpdb->prefix."cart_contents` WHERE `purchaseid`='$log_id'");
            	$wpdb->query("DELETE FROM `".$wpdb->prefix."submited_form_data` WHERE `log_id` IN ('$log_id')");
            	$wpdb->query("DELETE FROM `".$wpdb->prefix."purchase_logs` WHERE `id`='$log_id' LIMIT 1");
            	break;
            
            case 'Pending':      // need to wait for "Completed" before processing
            	$sql = "UPDATE `".$wpdb->prefix."purchase_logs` SET `transactid` = '".$transaction_id."', `date` = '".time()."'  WHERE `sessionid` = ".$sessionid." LIMIT 1";
            	$wpdb->query($sql) ;
            	break;
            
            default: // if nothing, do nothing, safest course of action here.
            	break;
            
		}
	}
	else
	{
		// Security Hash failed!!.. notify someone.. 
		$message = "This message has been sent because a call to your worldpay function was made by a server that did not have the correct security key.  This could mean someone is trying to hack your payment site.  The details of the call are below.\n\r\n\r";
		$message .= "OUR_POST:\n\r".print_r($header . $req,true)."\n\r\n\r";
		$message .= "THEIR_POST:\n\r".print_r($_POST,true)."\n\r\n\r";
		$message .= "GET:\n\r".print_r($_GET,true)."\n\r\n\r";
		$message .= "SERVER:\n\r".print_r($_SERVER,true)."\n\r\n\r";
		mail(get_option('purch_log_email'), "worldpay Security Key Failed!", $message);
	}

	// If in debug, email details
	if(get_option('worldpay_debug') == 1)
	{
		$message = "This is a debugging message sent because it appears that you are in debug mode.\n\rEnsure worldpay debug is turned off once you are happy with the function.\n\r\n\r";
		$message .= "OUR_POST:\n\r".print_r($header . $req,true)."\n\r\n\r";
		$message .= "THEIR_POST:\n\r".print_r($_POST,true)."\n\r\n\r";
		$message .= "GET:\n\r".print_r($_GET,true)."\n\r\n\r";
		$message .= "SERVER:\n\r".print_r($_SERVER,true)."\n\r\n\r";
		mail(get_option('purch_log_email'), "worldpay Data", $message);
	}

} 
}

function nzshpcrt_worldpay_results()
{
// Function used to translate the worldpay returned cs1=sessionid POST variable into the recognised GET variable for the transaction results page.
if($_POST['cs1'] !='' && $_GET['sessionid'] == '')
{
	$_GET['sessionid'] = $_POST['cs1'];
}
}

function submit_worldpay()
{  
if($_POST['worldpay_product_id'] != null)
    {
    	update_option('worldpay_product_id', $_POST['worldpay_product_id']);
    }
    
  	if($_POST['worldpay_product_name'] != null)
    {
    	update_option('worldpay_product_name', $_POST['worldpay_product_name']);
    }
    
  	if($_POST['worldpay_curcode'] != null)
    {
    	update_option('worldpay_curcode', $_POST['worldpay_curcode']);
    }
    
  	if($_POST['worldpay_language'] != null)
    {
    	update_option('worldpay_language', $_POST['worldpay_language']);
    }
    
  	if($_POST['worldpay_url'] != null)
    {
    	update_option('worldpay_url', $_POST['worldpay_url']);
    }

	if($_POST['worldpay_testmode'] != null)
    {
    	update_option('worldpay_testmode', $_POST['worldpay_testmode']);
    }

  	if($_POST['worldpay_debug'] != null)
    {
    	update_option('worldpay_debug', $_POST['worldpay_debug']);
    }
    
foreach((array)$_POST['worldpay_form'] as $form => $value)
    {
    	update_option(('worldpay_form_'.$form), $value);
    }
return true;
}

function form_worldpay()
{	
$select_currency[get_option('worldpay_curcode')] = "selected='true'";
$select_language[get_option('worldpay_language')] = "selected='true'";
$worldpay_url = ( get_option('worldpay_url')=='' ? 'https://select.worldpay.com/wcc/purchase' : get_option('worldpay_url') );
$worldpay_testmode = ( get_option('worldpay_testmode')=='' ? '100' : get_option('worldpay_testmode') );

$worldpay_debug = get_option('worldpay_debug');
$worldpay_debug1 = "";
$worldpay_debug2 = "";
switch($worldpay_debug)
{
	case 0:
		$worldpay_debug2 = "checked ='true'";
		break;
	case 1:
		$worldpay_debug1 = "checked ='true'";
		break;
}

$output = "
	<tr>
		<td>worldpay Product ID</td>
		<td><input type='text' size='40' value='".get_option('worldpay_product_id')."' name='worldpay_product_id' /></td>
	</tr>
	<tr>
		<td> </td>
		<td><small>This should be set to your product ID that has been set up in the worldpay client interface.
		This is the worldpay product that all purchases will be processed against. The cost will be changed depending on the grand total of the users cart.</small></td>
	</tr>
	<tr>
		<td>worldpay Product Name</td>
		<td><input type='text' size='40' value='".get_option('worldpay_product_name')."' name='worldpay_product_name' /></td>
	</tr>
	<tr>
		<td> </td>
		<td><small>This is not important and is usually set to the name of the web shop. It is displayed on the worldpay secure processing page.</small></td>
	</tr>
	<tr>
		<td>worldpay Accepted Currency (USD, EUR)</td>
		<td><select name='worldpay_curcode'>
				<option ".$select_currency['USD']." value='USD'>USD - U.S. Dollar</option>
				<option ".$select_currency['EUR']." value='EUR'>EUR - Euros</option>
				<option ".$select_currency['GBP']." value='GBP'>GBP - UK Sterling</option>
			</select> 
		</td>
	</tr>
	<tr>
		<td> </td>
		<td><small>The currency code that worldpay will process the payment in. All products must be set up in this currency.</small></td>
	</tr>
	<tr>
		<td>worldpay Language</td>
		<td><select name='worldpay_language'>
				<option ".$select_language['EN']." value='EN'>Engish</option>
				<option ".$select_language['ES']." value='ES'>Spanish</option>
				<option ".$select_language['NL']." value='NL'>Dutch</option>
				<option ".$select_language['RU']." value='RU'>Russian</option>
			</select> 
		</td>
	</tr>
	<tr>
		<td> </td>
		<td><small>The language that the worldpay secure processing page will be displayed in.</small></td>
	</tr>
	<tr>
		<td>worldpay processing URL</td>
		<td><input type='text' size='40' value='".$worldpay_url."' name='worldpay_url' /></td>
	</tr>
	<tr>
		<td> </td>
		<td><small>URL of the secure payment page customers are sent to for payment processing. If unsure leave at default setting.</small></td>
	</tr>
	<tr>
		<td>worldpay return URL</td>
		<td><input type='text' size='40' value='".get_option('transact_url')."' name='worldpay_return_url' /></td>
	</tr>
	<tr>
		<td> </td>
		<td><small></small></td>
	</tr>
	<tr>
		<td>worldpay Test Mode</td>
		<td><input type='text' size='40' value='".$worldpay_testmode."' name='worldpay_testmode' /></td>
	</tr>
	<tr>
		<td> </td>
		<td><small>A bit of security... This is a keyword that is used to ensure transaction approval calls from worldpay to this application are real and were instigated from this server.  Enter a unique word into this field.</small></td>
	</tr>
	<tr>
		<td>worldpay Debug Mode</td>
		<td>
			<input type='radio' value='1' name='worldpay_debug' id='worldpay_debug1' ".$worldpay_debug1." /> <label for='worldpay_debug1'>".TXT_WPSC_YES."</label>  
			<input type='radio' value='0' name='worldpay_debug' id='worldpay_debug2' ".$worldpay_debug2." /> <label for='worldpay_debug2'>".TXT_WPSC_NO."</label>
		</td>
	</tr>
	<tr>
		<td> </td>
		<td><small>Debug mode is used to write HTTP communications between the worldpay server and your host to a log file.  This should only be activated for testing!</small></td>
	</tr>

   
<tr class='update_gateway' >
	<td colspan='2'>
		<div class='submit'>
		<input type='submit' value='Update »' name='updateoption'/>
	</div>
	</td>
</tr>

<tr class='firstrowth'>
	<td style='border-bottom: medium none;' colspan='2'>
		<strong class='form_group'>Forms Sent to Gateway</strong>
	</td>
</tr>

	<tr>
		<td>First Name Field</td>
		<td><select name='worldpay_form[first_name]'>
			".nzshpcrt_form_field_list(get_option('worldpay_form_first_name'))."
			</select>
		</td>
	</tr>
	<tr>
		<td>Last Name Field</td>
		<td><select name='worldpay_form[last_name]'>
			".nzshpcrt_form_field_list(get_option('worldpay_form_last_name'))."
			</select>
		</td>
	</tr>
	<tr>
		<td>Address Field</td>
		<td><select name='worldpay_form[address]'>
			".nzshpcrt_form_field_list(get_option('worldpay_form_address'))."
			</select>
		</td>
	</tr>
	<tr>
		<td>City Field</td>
		<td><select name='worldpay_form[city]'>
			".nzshpcrt_form_field_list(get_option('worldpay_form_city'))."
			</select>
		</td>
	</tr>
	<tr>
		<td>State Field</td>
		<td><select name='worldpay_form[state]'>
			".nzshpcrt_form_field_list(get_option('worldpay_form_state'))."
			</select>
		</td>
	</tr>
	<tr>
		<td>Postal code/Zip code Field</td>
		<td><select name='worldpay_form[post_code]'>
			".nzshpcrt_form_field_list(get_option('worldpay_form_post_code'))."
			</select>
		</td>
	</tr>
	<tr>
		<td>Country Field</td>
		<td><select name='worldpay_form[country]'>
			".nzshpcrt_form_field_list(get_option('worldpay_form_country'))."
			</select>
		</td>
	</tr>
";
return $output;
}
  
  
add_action('init', 'nzshpcrt_worldpay_callback');
add_action('init', 'nzshpcrt_worldpay_results');

?>

Link to comment
Share on other sites

That processing functions file.

 

<?php	
/**
* wpsc_decrement_claimed_stock method 
*
* @param float a price
* @return string a price with a currency sign
*/
function wpsc_decrement_claimed_stock($purchase_log_id) {
  global $wpdb;
  $all_claimed_stock = $wpdb->get_results($wpdb->prepare("SELECT * FROM `".WPSC_TABLE_CLAIMED_STOCK."` WHERE `cart_id` IN('%s') AND `cart_submitted` IN('1')", $purchase_log_id), ARRAY_A);

foreach((array)$all_claimed_stock as $claimed_stock) {
  // for people to have claimed stock, it must have been available to take, no need to look at the existing stock, just subtract from it
  // If this is ever wrong, and you get negative stock, do not fix it here, go find the real cause of the problem 
	if($claimed_stock['variation_stock_id'] > 0) {
		$wpdb->query($wpdb->prepare("UPDATE `".WPSC_TABLE_VARIATION_PROPERTIES."` SET `stock` = (`stock` - %s)  WHERE `id` = '%d' LIMIT 1", $claimed_stock['stock_claimed'], $claimed_stock['variation_stock_id']));
	} else {
		$wpdb->query($wpdb->prepare("UPDATE `".WPSC_TABLE_PRODUCT_LIST."` SET `quantity` = (`quantity` - %s)  WHERE `id` = '%d' LIMIT 1", $claimed_stock['stock_claimed'], $claimed_stock['product_id']));
	}
}
$wpdb->query($wpdb->prepare("DELETE FROM `".WPSC_TABLE_CLAIMED_STOCK."` WHERE `cart_id` IN ('%s')", $purchase_log_id));
}
  
/**
*	wpsc_get_currency_symbol
*	@param does not receive anything
*  @return returns the currency symbol used for the shop
*/  
function wpsc_get_currency_symbol(){
global $wpdb;
$currency_type = get_option('currency_type');
$wpsc_currency_data = $wpdb->get_var("SELECT `symbol` FROM `".WPSC_TABLE_CURRENCY_LIST."` WHERE `id`='".$currency_type."' LIMIT 1") ;
return  $wpsc_currency_data;}  
  
/**
* All the code below here needs commenting and looking at to see if it needs to be altered or disposed of.
* Correspondingly, all the code above here has been commented, uses the wpsc prefix, and has been made for or modified to work with the object oriented cart code.
*/


function nzshpcrt_currency_display($price_in, $tax_status, $nohtml = false, $id = false, $no_dollar_sign = false) {
  global $wpdb, $wpsc_currency_data;
  $currency_sign_location = get_option('currency_sign_location');
  $currency_type = get_option('currency_type');
  if(count($wpsc_currency_data) < 3) {
	$wpsc_currency_data = $wpdb->get_row("SELECT `symbol`,`symbol_html`,`code` FROM `".WPSC_TABLE_CURRENCY_LIST."` WHERE `id`='".$currency_type."' LIMIT 1",ARRAY_A) ;
  }
  $price_out = null;

  $price_out =  number_format($price_in, 2, '.', ',');

  if($wpsc_currency_data['symbol'] != '') {
    if($nohtml == false) {
      $currency_sign = $wpsc_currency_data['symbol_html'];
	} else {
		$currency_sign = $wpsc_currency_data['symbol'];
	}
} else {
	$currency_sign = $wpsc_currency_data['code'];
}

  switch($currency_sign_location) {
    case 1:
    $output = $price_out.$currency_sign;
    break;

    case 2:
    $output = $price_out.' '.$currency_sign;
    break;

    case 4:
    $output = $currency_sign.'  '.$price_out;
    break;
    
    case 3:
    default:
    $output = $currency_sign.$price_out;
    break;
}

  if($nohtml == true) {
    $output = "".$output."";
} else {
	$output = "<span class='pricedisplay'>".$output."</span>";
    //$output = "".$output."";
}
      
  if($no_dollar_sign == true) {
    return $price_out;
}
  return $output;
}
  
  
  function nzshpcrt_find_total_price($purchase_id,$country_code) {
    global $wpdb;
    if(is_numeric($purchase_id)) {
      $purch_sql = "SELECT * FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `id`='".$purchase_id."'";
      $purch_data = $wpdb->get_row($purch_sql,ARRAY_A) ;

      $cartsql = "SELECT * FROM `".WPSC_TABLE_CART_CONTENTS."` WHERE `purchaseid`=".$purchase_id."";
      $cart_log = $wpdb->get_results($cartsql,ARRAY_A) ; 
      if($cart_log != null) {
        $all_donations = true;
        $all_no_shipping = true;
        foreach($cart_log as $cart_row) {
          $productsql= "SELECT * FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `id`=".$cart_row['prodid']."";
          $product_data = $wpdb->get_results($productsql,ARRAY_A); 
        
          $variation_sql = "SELECT * FROM `".WPSC_TABLE_CART_ITEM_VARIATIONS."` WHERE `cart_id`='".$cart_row['id']."'";
          $variation_data = $wpdb->get_results($variation_sql,ARRAY_A); 
          $variation_count = count($variation_data);
          $price = ($cart_row['price'] * $cart_row['quantity']);          
          
          if($purch_data['shipping_country'] != '') {
            $country_code = $purch_data['shipping_country'];
				}
            
          if($cart_row['donation'] == 1) {
            $shipping = 0;
				} else {
            $all_donations = false;
				}
          
          if($cart_row['no_shipping'] == 1) {
            $shipping = 0;
				} else {
            $all_no_shipping = false;
				}

          if(($cart_row['donation'] != 1) && ($cart_row['no_shipping'] != 1)) {
            $shipping = nzshpcrt_determine_item_shipping($cart_row['prodid'], $cart_row['quantity'], $country_code);
				}
          $endtotal += $shipping + $price;
			}
        if(($all_donations == false) && ($all_no_shipping == false)){
          if($purch_data['base_shipping'] > 0) {
					$base_shipping = $purch_data['base_shipping'];
				} else {
					$base_shipping = nzshpcrt_determine_base_shipping(0, $country_code);
				}
				$endtotal += $base_shipping;
			}
        
        if($purch_data['discount_value'] > 0) {
				$endtotal -= $purch_data['discount_value'];
				if($endtotal < 0) {
					$endtotal = 0;
				}
        }
          
		}
      return $endtotal;
	}
}

function nzshpcrt_determine_item_shipping($product_id, $quantity, $country_code) {    
    global $wpdb;
    if(is_numeric($product_id) && (get_option('do_not_use_shipping') != 1) && ($_SESSION['quote_shipping_method'] == 'flatrate')) {
      $sql = "SELECT * FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `id`='$product_id' LIMIT 1";
      $product_list = $wpdb->get_row($sql,ARRAY_A) ;
      if($product_list['no_shipping'] == 0) {
        //if the item has shipping
        if($country_code == get_option('base_country')) {
          $additional_shipping = $product_list['pnp'];
			} else {
          $additional_shipping = $product_list['international_pnp'];
			}          
        $shipping = $quantity * $additional_shipping;
		} else {
        //if the item does not have shipping
        $shipping = 0;
		}
	} else {
      //if the item is invalid or all items do not have shipping
		$shipping = 0;
	}
    return $shipping;    
}
  function nzshpcrt_determine_base_shipping($per_item_shipping, $country_code) {    
    global $wpdb, $wpsc_shipping_modules;
	$custom_shipping = get_option('custom_shipping_options');
    if((get_option('do_not_use_shipping') != 1) && (count($custom_shipping) > 0)) {
		if(array_search($_SESSION['quote_shipping_method'], (array)$custom_shipping) === false) {
		  //unset($_SESSION['quote_shipping_method']);
		}

		$shipping_quotes = null;
		if($_SESSION['quote_shipping_method'] != null) {
			// use the selected shipping module
		  $shipping_quotes = $wpsc_shipping_modules[$_SESSION['quote_shipping_method']]->getQuote();
		} else {
		  // otherwise select the first one with any quotes
			foreach((array)$custom_shipping as $shipping_module) {
				// if the shipping module does not require a weight, or requires one and the weight is larger than zero
				if(($custom_shipping[$shipping_module]->requires_weight != true) or (($custom_shipping[$shipping_module]->requires_weight == true) and (shopping_cart_total_weight() > 0))) {
					$_SESSION['quote_shipping_method'] = $shipping_module;
					$shipping_quotes = $wpsc_shipping_modules[$_SESSION['quote_shipping_method']]->getQuote();
					if(count($shipping_quotes) > 0) { // if we have any shipping quotes, break the loop.
						break;
					}
				}
			}
		}

		//echo "<pre>".print_r($_SESSION['quote_shipping_method'],true)."</pre>";
		if(count($shipping_quotes) < 1) {
		$_SESSION['quote_shipping_option'] = '';
		}
		if(($_SESSION['quote_shipping_option'] == null) && ($shipping_quotes != null)) {
			$_SESSION['quote_shipping_option'] = array_pop(array_keys(array_slice($shipping_quotes,0,1)));
		}
		foreach((array)$shipping_quotes as $shipping_quote) {
			foreach((array)$shipping_quote as $key=>$quote) {
				if($key == $_SESSION['quote_shipping_option']) {
				  $shipping = $quote;
				}
			}
		}
	} else {
      $shipping = 0;
	}
    return $shipping;
}
  
function admin_display_total_price($start_timestamp = '', $end_timestamp = '') {
  global $wpdb;
  if(($start_timestamp != '') && ($end_timestamp != '')) {
    $sql = "SELECT SUM(`totalprice`) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `processed` > '1' AND `date` BETWEEN '$start_timestamp' AND '$end_timestamp'";
} else {
	$sql = "SELECT SUM(`totalprice`) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `processed` > '1' AND `date` != ''";
}
  $total = $wpdb->get_var($sql);
  return $total;
}
  

function calculate_product_price($product_id, $variations = false, $no_special=false) {
  global $wpdb;
  if(is_numeric($product_id)) {
    if(is_array($variations) && (count($variations) >= 1)) {
      $variation_count = count($variations);
      $variations = array_values($variations);
      array_walk($variations, 'wpsc_sanitise_keys');
	}

    /// the start of the normal price determining code.
    if($variation_count >= 1) {
      // if we have variations, grab the individual price for them. 
      $variation_ids = $wpdb->get_col("SELECT `variation_id` FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `id` IN ('".implode("','",$variations)."')");
      asort($variation_ids);         
      $all_variation_ids = implode(",", $variation_ids);
      
      
      $priceandstock_id = $wpdb->get_var("SELECT `priceandstock_id` FROM `".WPSC_TABLE_VARIATION_COMBINATIONS."` WHERE `product_id` = '$product_id' AND `value_id` IN ( '".implode("', '",$variations )."' ) AND `all_variation_ids` IN('$all_variation_ids') GROUP BY `priceandstock_id` HAVING COUNT( `priceandstock_id` ) = '".count($variations)."' LIMIT 1");
      
      
      $price = $wpdb->get_var("SELECT `price` FROM `".WPSC_TABLE_VARIATION_PROPERTIES."` WHERE `id` = '{$priceandstock_id}' LIMIT 1");
    } else {	
      $product_data = $wpdb->get_row("SELECT `price`,`special`,`special_price` FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `id`='".$product_id."' LIMIT 1",ARRAY_A);
     // echo '<span style="color:#f00;">'.print_r($product_data, true).'</span><br />'.;

     
      if(($product_data['special_price'] > 0) && (($product_data['price'] - $product_data['special_price']) >= 0) && ($no_special == false)) {
        $price = $product_data['price'] - $product_data['special_price'];
      } else {
        $price = $product_data['price'];
       
      }
    }
} else {
	$price = false;
}

  return $price;
}
  
function check_in_stock($product_id, $variations, $item_quantity = 1) {
  global $wpdb;
  $product_id = (int)$product_id;
  $item_data = $wpdb->get_row("SELECT * FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `id`='{$product_id}' LIMIT 1",ARRAY_A);
  
  $item_stock = null;
  $variation_count = count($variations);
  if($variation_count > 0) {
    foreach($variations as $variation_id) {
      if(is_numeric($variation_id)) {
        $variation_ids[] = $variation_id;
		}
	}
    if(count($variation_ids) > 0) {
      
        $actual_variation_ids = $wpdb->get_col("SELECT `variation_id` FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `id` IN ('".implode("','",$variation_ids)."')");
        asort($actual_variation_ids);         
        $all_variation_ids = implode(",", $actual_variation_ids);
    
    
      $priceandstock_id = $wpdb->get_var("SELECT `priceandstock_id` FROM `".WPSC_TABLE_VARIATION_COMBINATIONS."` WHERE `product_id` = '{$product_id}' AND `value_id` IN ( '".implode("', '",$variation_ids )."' ) AND `all_variation_ids` IN('$all_variation_ids') GROUP BY `priceandstock_id` HAVING COUNT( `priceandstock_id` ) = '".count($variation_ids)."' LIMIT 1");
      
      $variation_stock_data = $wpdb->get_row("SELECT * FROM `".WPSC_TABLE_VARIATION_PROPERTIES."` WHERE `id` = '{$priceandstock_id}' LIMIT 1", ARRAY_A);
      
      $item_stock = $variation_stock_data['stock'];
	}
}
    
  if($item_stock === null) {
    $item_stock = $item_data['quantity'];
}
  
  if((($item_data['quantity_limited'] == 1) && ($item_stock > 0) && ($item_stock >= $item_quantity)) || ($item_data['quantity_limited'] == 0))  {
    $output = true;
} else {
	$output = false;
}
  return $output;
}

  
  
function wpsc_item_process_image($id, $input_file, $output_filename, $width = 0, $height = 0, $resize_method = 1) {
//  the function for processing images, takes a product_id, input_file outout file name, height and width
global $wpdb;
//$_FILES['image']['tmp_name']
//$_FILES['image']['name']
if(preg_match("/\.(gif|jp(e)*g|png){1}$/i",$output_filename) && apply_filters( 'wpsc_filter_file', $input_file )) {
	//$active_signup = apply_filters( 'wpsc_filter_file', $_FILES['image']['tmp_name'] );
	if(function_exists("getimagesize")) {
		$image_name = basename($output_filename);
		if(is_file((WPSC_IMAGE_DIR.$image_name))) {
			$name_parts = explode('.',basename($image_name));
			$extension = array_pop($name_parts);
			$name_base = implode('.',$name_parts);
			$dir = glob(WPSC_IMAGE_DIR."$name_base*");

			foreach($dir as $file) {
				$matching_files[] = basename($file);
			}
			$image_name = null;
			$num = 2;
			//  loop till we find a free file name, first time I get to do a do loop in yonks
			do {
				$test_name = "{$name_base}-{$num}.{$extension}";
				if(!file_exists(WPSC_IMAGE_DIR.$test_name)) {
					$image_name = $test_name;
				}
				$num++;
			} while ($image_name == null);
		}			

		//exit("<pre>".print_r($image_name,true)."</pre>");

		$new_image_path = WPSC_IMAGE_DIR.$image_name;

		// sometimes rename doesn't work, if the file is recently uploaded, use move_uploaded_file instead
		if(is_uploaded_file($input_file)) {
			move_uploaded_file($input_file, $new_image_path);
		} else {
			rename($input_file, $new_image_path);
		}
		$stat = stat( dirname( $new_image_path ));
		$perms = $stat['mode'] & 0000775;
		@ chmod( $new_image_path, $perms );

		switch($resize_method) {
			case 2:
			if($height < 1) {
				$height = get_option('product_image_height');
			}
			if($width < 1) {
				$width  = get_option('product_image_width');
			}
			break;


			case 0:
			$height = (int)null;
			$width  = (int)null;
			break;

			case 1:
			default:
			$height = (int)get_option('product_image_height');
			$width  = (int)get_option('product_image_width');
			break;
		}
				if($width < 1) {
					$width = 96;
				}
				if($height < 1) {
					$height = 96;
				}	     
			image_processing($new_image_path, (WPSC_THUMBNAIL_DIR.$image_name), $width, $height);
// 			}
		$sql = "INSERT INTO `".WPSC_TABLE_PRODUCT_IMAGES."` (`product_id`, `image`, `width`, `height`) VALUES ('{$id}', '{$image_name}', '{$width}', '{$height}' )";
		$wpdb->query($sql);
		$image_id = (int) $wpdb->insert_id;			
		$updatelink_sql = "UPDATE `".WPSC_TABLE_PRODUCT_LIST."` SET `image` = '".$image_id."', `thumbnail_image` = '".$thumbnail_image."'  WHERE `id` = '$id'";
		$wpdb->query($updatelink_sql);
		//exit($sql.'<br />image is about to be stored in the DB<br />'.$updatelink_sql);

		if(function_exists('getimagesize')) {
			$imagetype = getimagesize(WPSC_THUMBNAIL_DIR.$image_name);
			update_product_meta($id, 'thumbnail_width', $imagetype[0]);
			update_product_meta($id, 'thumbnail_height', $imagetype[1]);
		}


		$image = $wpdb->escape($image_name);
	} else {
		$image_name = basename($output_filename);
		if(is_file((WPSC_IMAGE_DIR.$image_name))) {
			$name_parts = explode('.',basename($image_name));
			$extension = array_pop($name_parts);
			$name_base = implode('.',$name_parts);
			$dir = glob(WPSC_IMAGE_DIR."$name_base*");

			foreach($dir as $file) {
				$matching_files[] = basename($file);
			}
			$image_name = null;
			$num = 2;
			//  loop till we find a free file name
			do {
				$test_name = "{$name_base}-{$num}.{$extension}";
				if(!file_exists(WPSC_IMAGE_DIR.$test_name)) {
					$image_name = $test_name;
				}
				$num++;
			} while ($image_name == null);
		}
		$new_image_path = WPSC_IMAGE_DIR.$image_name;
		move_uploaded_file($input_file, $new_image_path);
		$stat = stat( dirname( $new_image_path ));
		$perms = $stat['mode'] & 0000775;
		@ chmod( $new_image_path, $perms );
		$image = $wpdb->escape($image_name);
	}
} else {
		$image_data = $wpdb->get_row("SELECT `id`,`image` FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `id`='".(int)$id."' LIMIT 1",ARRAY_A);

	$image = false;
}
  return $image;
}

function old_wpsc_item_process_file($mode = 'add') {
  global $wpdb;
  	$files = $wpdb->get_results("SELECT * FROM ".WPSC_TABLE_PRODUCT_FILES." ORDER BY id ASC", ARRAY_A);
	if (is_array($files)){
		foreach($files as $file){
			$file_names[] = $file['filename'];
			$file_hashes[] = $file['idhash'];
		}
	}

if(apply_filters( 'wpsc_filter_file', $_FILES['file']['tmp_name'] )) {
  // initialise $idhash to null to prevent issues with undefined variables and error logs
  $idhash = null;
	switch($mode) {
		case 'edit':
   		/* if we are editing, grab the current file and ID hash */ 
		$product_id = $_POST['prodid'];
		$fileid_data = $wpdb->get_results("SELECT `file` FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `id` = '$product_id' LIMIT 1",ARRAY_A);

		case 'add':
		default:
		/* if we are adding, make a new file row and get the ID of it */
		$timestamp = time();
		$query_results = $wpdb->query("INSERT INTO `".WPSC_TABLE_PRODUCT_FILES."` ( `filename`  , `mimetype` , `idhash` , `date` ) VALUES ( '', '', '', '$timestamp');");
		$fileid = $wpdb->get_var("SELECT LAST_INSERT_ID() FROM `".WPSC_TABLE_PRODUCT_FILES."`");
		break;
	}

	/* if there is no idhash, generate it */
	if($idhash == null) {
		$idhash = sha1($fileid);
		if($idhash == '') {
		  // if sha1 doesnt spit an error, but doesnt return anything either (it has done so on some servers)
			$idhash = md5($fileid);
		}
	}
	// if needed, we can add code here to stop hash doubleups in the unlikely event that they shoud occur

	$mimetype = wpsc_get_mimetype($_FILES['file']['tmp_name']);

	$filename = basename($_FILES['file']['name']);


	if (in_array($_FILES['file']['name'],(array)$file_names)){
		$i=0;
		$new_name = $_FILES['file']['name'].".old";
		while(file_exists(WPSC_FILE_DIR.$new_name)){
			$new_name = $_FILES['file']['name'].".old_".$i;
			$i++;
		}
		$old_idhash_id = array_search($_FILES['file']['name'],(array)$file_names);
		$old_idhash = $file_hashes[$old_idhash_id];
		while(!file_exists(WPSC_FILE_DIR.$old_idhash)){
			unset($file_hashes[$old_idhash_id]);
			unset($file_names[$old_idhash_id]);

			$old_idhash_id = array_search($_FILES['file']['name'],(array)$file_names);
			$old_idhash = $file_hashes[$old_idhash_id];
		}
		copy(WPSC_FILE_DIR.$old_idhash, WPSC_FILE_DIR.$new_name);
		unlink(WPSC_FILE_DIR.$old_idhash);
	}
	if(move_uploaded_file($_FILES['file']['tmp_name'],(WPSC_FILE_DIR.$idhash)))	{
		$stat = stat( dirname( (WPSC_FILE_DIR.$idhash) ));
		$perms = $stat['mode'] & 0000666;
		@ chmod( (WPSC_FILE_DIR.$idhash), $perms );	
		if(function_exists("make_mp3_preview"))	{
			if($mimetype == "audio/mpeg" && (!isset($_FILES['preview_file']['tmp_name']))) {
			  // if we can generate a preview file, generate it (most can't due to sox being rare on servers and sox with MP3 support being even rarer), thus this needs to be enabled by editing code
				make_mp3_preview((WPSC_FILE_DIR.$idhash), (WPSC_PREVIEW_DIR.$idhash.".mp3"));
				$preview_filepath = (WPSC_PREVIEW_DIR.$idhash.".mp3");
			} else if(file_exists($_FILES['preview_file']['tmp_name'])) {    
				$preview_filename = basename($_FILES['preview_file']['name']);
				$preview_mimetype = wpsc_get_mimetype($_FILES['preview_file']['tmp_name']);
				copy($_FILES['preview_file']['tmp_name'], (WPSC_PREVIEW_DIR.$preview_filename));
				$preview_filepath = (WPSC_PREVIEW_DIR.$preview_filename);
				$wpdb->query("UPDATE `".WPSC_TABLE_PRODUCT_FILES."` SET `preview` = '".$wpdb->escape($preview_filename)."', `preview_mimetype` = '".$preview_mimetype."' WHERE `id` = '$fileid' LIMIT 1");
			}
			$stat = stat( dirname($preview_filepath));
			$perms = $stat['mode'] & 0000666;
			@ chmod( $preview_filepath, $perms );	
		}
		$wpdb->query("UPDATE `".WPSC_TABLE_PRODUCT_FILES."` SET `filename` = '".$wpdb->escape($filename)."', `mimetype` = '$mimetype', `idhash` = '$idhash' WHERE `id` = '$fileid' LIMIT 1");
	}
	if($mode == 'edit') {			
      //if we are editing, update the file ID in the product row, this cannot be done for add because the row does not exist yet.
      $wpdb->query("UPDATE `".WPSC_TABLE_PRODUCT_LIST."` SET `file` = '$fileid' WHERE `id` = '$product_id' LIMIT 1");
	}
	return $fileid;
  } else {
	return false;
  }
}

function old_wpsc_item_reassign_file($selected_product_file, $mode = 'add') {
  global $wpdb;
// initialise $idhash to null to prevent issues with undefined variables and error logs
$idhash = null;
if($mode == 'edit') {
	/* if we are editing, grab the current file and ID hash */ 
	$product_id = (int)$_POST['prodid'];
	if($selected_product_file == '.none.') {
		// unlikely that anyone will ever upload a file called .none., so its the value used to signify clearing the product association
		$wpdb->query("UPDATE `".WPSC_TABLE_PRODUCT_LIST."` SET `file` = '0' WHERE `id` = '$product_id' LIMIT 1");
		return null;
	}

	// if we already use this file, there is no point doing anything more.
	$current_fileid = $wpdb->get_var("SELECT `file` FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `id` = '$product_id' LIMIT 1",ARRAY_A);
	if($current_fileid > 0) {
		$current_file_data = $wpdb->get_row("SELECT `id`,`idhash` FROM `".WPSC_TABLE_PRODUCT_FILES."` WHERE `id` = '$current_fileid' LIMIT 1",ARRAY_A);
		if(basename($selected_product_file) == $file_data['idhash']) {
			return $current_fileid;
		}
	}
}


$selected_product_file = basename($selected_product_file);
if(file_exists(WPSC_FILE_DIR.$selected_product_file)) {
	$timestamp = time();
	$file_data = $wpdb->get_row("SELECT * FROM `".WPSC_TABLE_PRODUCT_FILES."` WHERE `idhash` IN('".$wpdb->escape($selected_product_file)."') LIMIT 1", ARRAY_A);
	$fileid = (int)$file_data['id'];
	if($fileid < 1) { // if the file does not have a database row, add one.
	  $mimetype = wpsc_get_mimetype(WPSC_FILE_DIR.$selected_product_file);
	  $filename = $idhash = $selected_product_file;
		$timestamp = time();
		$wpdb->query("INSERT INTO `".WPSC_TABLE_PRODUCT_FILES."` ( `filename`  , `mimetype` , `idhash` , `date` ) VALUES ( '{$filename}', '{$mimetype}', '{$idhash}', '{$timestamp}');");
		$fileid = $wpdb->get_var("SELECT `id` FROM `".WPSC_TABLE_PRODUCT_FILES."` WHERE `date` = '{$timestamp}' AND `filename` IN ('{$filename}')");
	}
	if($mode == 'edit') {
      //if we are editing, update the file ID in the product row, this cannot be done for add because the row does not exist yet.
      $wpdb->query("UPDATE `".WPSC_TABLE_PRODUCT_LIST."` SET `file` = '$fileid' WHERE `id` = '$product_id' LIMIT 1");
	}
}	
return $fileid;
}

function wpsc_get_mimetype($file, $check_reliability = false) {
  // Sometimes we need to know how useless the result from this is, hence the "check_reliability" parameter
if(file_exists($file)) {
	if(function_exists('finfo_open') && function_exists('finfo_file')) { 
		// fileinfo apparently works best, wish it was included with PHP by default
		$finfo_handle = finfo_open(FILEINFO_MIME);
		$mimetype = finfo_file($finfo_handle,$file);
		$is_reliable = true;
	} else if(function_exists('mime_content_type') && (mime_content_type($file) != '')) {
		//obsolete, but probably second best due to completeness
		$mimetype = mime_content_type($file);
		$is_reliable = true;
	} else {
		//included with plugin, uses the extention, limited and odd list, last option
		$mimetype_class = new mimetype();
		$mimetype = $mimetype_class->getType($file);
		$is_reliable = false;
	}
} else {
	$mimetype = false;
	$is_reliable = false;
}
if($check_reliability == true) {
	return array('mime_type' =>$mimetype, 'is_reliable' => $is_reliable );
} else {
	return $mimetype;
}
}


function shopping_cart_total_weight() {
global $wpdb;
$cart = $_SESSION['nzshpcrt_cart'];
$total_weight=0;
foreach((array)$cart as $item) {
  $weight = array();
	$variations = $item->product_variations;
	if(count($variations) > 0) {
		$variation_ids = $wpdb->get_col("SELECT `variation_id` FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `id` IN ('".implode("','",$variations)."')");
		asort($variation_ids);
		$all_variation_ids = implode(",", $variation_ids);
		$priceandstock_id = $wpdb->get_var("SELECT `priceandstock_id` FROM `".WPSC_TABLE_VARIATION_COMBINATIONS."` WHERE `product_id` = '".(int)$item->product_id."' AND `value_id` IN ( '".implode("', '",$variations )."' ) AND `all_variation_ids` IN('{$all_variation_ids}') GROUP BY `priceandstock_id` HAVING COUNT( `priceandstock_id` ) = '".count($variations)."' LIMIT 1");
		$weight = $wpdb->get_row("SELECT `weight`, `weight_unit` FROM `".WPSC_TABLE_VARIATION_PROPERTIES."` WHERE `id` = '{$priceandstock_id}' LIMIT 1", ARRAY_A);

	}

	if(($weight == null) || ($weight['weight'] == null) && ($weight['weight_unit'] == null)) {
		$weight=$wpdb->get_row("SELECT `weight`, `weight_unit` FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE id='{$item->product_id}'", ARRAY_A);
	}

	switch($weight['weight_unit']) {
		case "kilogram":
		$weight = $weight['weight'] / 0.45359237;
		break;

		case "gram":
		$weight = $weight['weight'] / 453.59237;
		break;

		case "once":
		case "ounce":
		$weight = $weight['weight'] / 16;
		break;

		default:
		$weight = $weight['weight'];
		break;
	}
	$subweight = $weight*$item->quantity;
	$total_weight+=$subweight;
}
return $total_weight;
}

function wpsc_convert_weights($weight, $unit) {
if (is_array($weight)) {
	$weight = $weight['weight'];
}
switch($unit) {
	case "kilogram":
	$weight = $weight / 0.45359237;
	break;

	case "gram":
	$weight = $weight / 453.59237;
	break;

	case "once":
	case "ounce":
	$weight = $weight / 16;
	break;

	default:
	$weight = $weight;
	break;
}
return $weight;
}



function wpsc_ping() {
$services = get_option('ping_sites');
$services = explode("\n", $services);
foreach ( (array) $services as $service ) {
	$service = trim($service);
	if($service != '' ) {
		wpsc_send_ping($service);
	}
}
}

function wpsc_send_ping($server) {
global $wp_version;
include_once(ABSPATH . WPINC . '/class-IXR.php');

// using a timeout of 3 seconds should be enough to cover slow servers
$client = new IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
$client->timeout = 3;
$client->useragent .= ' -- WordPress/'.$wp_version;

// when set to true, this outputs debug messages by itself
$client->debug = false;
$home = trailingslashit( get_option('product_list_url') );
$rss_url = get_option('siteurl')."/index.php?rss=true&action=product_list";
if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, $rss_url ) ) {
	$client->query('weblogUpdates.ping', get_option('blogname'), $home);
}
}





function wpsc_add_product($product_values) {
    global $wpdb;
	// takes an array, inserts it into the database as a product
	$success = false;


	$insertsql = "INSERT INTO `".WPSC_TABLE_PRODUCT_LIST."` SET";
	$insertsql .= "`name` = '".$wpdb->escape($product_values['name'])."',";
	$insertsql .= "`description`  = '".$wpdb->escape($product_values['description'])."',";
	$insertsql .= "`additional_description`  = '".$wpdb->escape($product_values['additional_description'])."',";

	$insertsql .= "`price` = '".$wpdb->escape($product_values['price'])."',";

	$insertsql .= "`quantity_limited` = '".$wpdb->escape($product_values['quantity_limited'])."',";
	$insertsql .= "`quantity` = '".$wpdb->escape($product_values['quantity'])."',";

	$insertsql .= "`special` = '".$wpdb->escape($product_values['special'])."',";
	$insertsql .= "`special_price` = '".$wpdb->escape($product_values['special_price'])."',";

	$insertsql .= "`weight` = '".$wpdb->escape($product_values['weight'])."',";
	$insertsql .= "`weight_unit` = '".$wpdb->escape($product_values['weight_unit'])."',";

	$insertsql .= "`no_shipping` = '".$wpdb->escape($product_values['no_shipping'])."',";	
	$insertsql .= "`pnp` = '".$wpdb->escape($product_values['pnp'])."',";
	$insertsql .= "`international_pnp` = '".$wpdb->escape($product_values['international_pnp'])."',";

	$insertsql .= "`donation` = '".$wpdb->escape($product_values['donation'])."',";
	$insertsql .= "`display_frontpage` = '".$wpdb->escape($product_values['display_frontpage'])."',";
	$insertsql .= "`notax` = '".$wpdb->escape($product_values['notax'])."',";

	$insertsql .= "`image` = '0',";
	$insertsql .= "`file` = '0',";
	$insertsql .= "`thumbnail_state` = '0' ;";


	//Insert the data
	if($wpdb->query($insertsql)) {  
	  // if we succeeded, we have a product id, we wants it for the next stuff
		$product_id = $wpdb->get_var("SELECT LAST_INSERT_ID() AS `id` FROM `".WPSC_TABLE_PRODUCT_LIST."` LIMIT 1");

		// add the tags
		if(function_exists('wp_insert_term')) {
			product_tag_init();
			$tags = $product_values['product_tag'];
			if ($tags!="") {
				$tags = explode(',',$tags);
				foreach($tags as $tag) {
					$tt = wp_insert_term((string)$tag, 'product_tag');
				}
				$return = wp_set_object_terms($product_id, $tags, 'product_tag');
			}
		}

		$image = wpsc_item_process_image($product_id, $product_values['image_path'], basename($product_values['image_path']), $product_values['width'], $product_values['height'], $product_values['image_resize']);

		if(($image != null)) {
			$wpdb->query("UPDATE `".WPSC_TABLE_PRODUCT_LIST."` SET `image` = '".$wpdb->escape($image)."' WHERE `id`='".$product_id."' LIMIT 1");
		}


		// add the product meta values
		if($product_values['productmeta_values'] != null) {
			foreach((array)$product_values['productmeta_values'] as $key => $value) {
				if(get_product_meta($product_id, $key) != false) {
					update_product_meta($product_id, $key, $value);
				} else {
					add_product_meta($product_id, $key, $value);
				}
			}
		}

		// and the custom meta values		
		if($product_values['new_custom_meta'] != null) {
			foreach((array)$product_values['new_custom_meta']['name'] as $key => $name) {
				$value = $product_values['new_custom_meta']['value'][(int)$key];
				if(($name != '') && ($value != '')) {
					add_product_meta($product_id, $name, $value, false, true);
				}
			}
		}

		// Add the tidy url name 
		$tidied_name = trim($product_values['name']);
		$tidied_name = strtolower($tidied_name);
		$url_name = preg_replace(array("/(\s)+/","/[^\w-]+/i"), array("-", ''), $tidied_name);
		$similar_names = $wpdb->get_row("SELECT COUNT(*) AS `count`, MAX(REPLACE(`meta_value`, '".$wpdb->escape($url_name)."', '')) AS `max_number` FROM `".WPSC_TABLE_PRODUCTMETA."` WHERE `meta_key` IN ('url_name') AND `meta_value` REGEXP '^(".$wpdb->escape($url_name)."){1}(\d)*$' ",ARRAY_A);
		$extension_number = '';
		if($similar_names['count'] > 0) {
			$extension_number = (int)$similar_names['max_number']+1;
		}
		$url_name .= $extension_number;
		add_product_meta($product_id, 'url_name', $url_name,true);

		// Add the varations and associated values
		$variations_procesor = new nzshpcrt_variations;
		if($product_values['variation_values'] != null) {
			$variations_procesor->add_to_existing_product($product_id,$product_values['variation_values']);
		}

		if($product_values['variation_priceandstock'] != null) {
			$variations_procesor->update_variation_values($product_id, $product_values['variation_priceandstock']);
		}

		// Add the selelcted categories
		$item_list = '';
		if(count($product_values['category']) > 0) {
			foreach($product_values['category'] as $category_id) {
			  $category_id = (int)$category_id;
				$check_existing = $wpdb->get_var("SELECT `id` FROM `".WPSC_TABLE_ITEM_CATEGORY_ASSOC."` WHERE `product_id` = ".$product_id." AND `category_id` = '$category_id' LIMIT 1");
				if($check_existing == null) {
					$wpdb->query("INSERT INTO `".WPSC_TABLE_ITEM_CATEGORY_ASSOC."` ( `product_id` , `category_id` ) VALUES ( '".$product_id."', '".$category_id."');");        
				}
			}
		}
	$success = true;
	}
return $success;
}

function wpsc_sanitise_keys($value) {
  /// Function used to cast array items to integer.
  return (int)$value;
}



/*
* this function checks every product on the products page to see if it has any stock remaining
* it is executed through the wpsc_product_alert filter
*/
function wpsc_check_stock($state, $product) {
global $wpdb;
// if quantity is enabled and is zero
$out_of_stock = false;
// only do anything if the quantity is limited.
if($product['quantity_limited'] == 1) {
  $excluded_values = '';
  // get the variation IDs  associated with this product
	$variation_ids = $wpdb->get_col("SELECT `variation_id` FROM `".WPSC_TABLE_VARIATION_ASSOC."` WHERE `type` IN ('product') AND `associated_id` IN ('{$product['id']}')");
	// if there are any, look through them for items out of stock
	if(count($variation_ids) > 0) { 
	  // sort and comma seperate them
		asort($variation_ids);
		$all_variation_ids = implode(",", $variation_ids);

		// get the visible variation values associated with this product
		$enabled_values = $wpdb->get_col("SELECT `value_id` FROM `".WPSC_TABLE_VARIATION_VALUES_ASSOC."` WHERE `product_id` IN('{$product['id']}') AND `visible` IN ('1')");

		// get the priceandstock IDs using the variation and variation value IDs
		$priceandstock_ids = $wpdb->get_col("SELECT `priceandstock_id` FROM `".WPSC_TABLE_VARIATION_COMBINATIONS."` WHERE `product_id` = '{$product['id']}'  AND `all_variation_ids` IN('$all_variation_ids') AND `value_id` IN (".implode(",", $enabled_values).")  GROUP BY `priceandstock_id` HAVING COUNT( `priceandstock_id` ) = '".count($variation_ids)."'");

		// count the variation combinations with a stock of zero
		if(count($priceandstock_ids) > 0) {
			$items_out_of_stock = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_VARIATION_PROPERTIES."` WHERE `id` IN(".implode(",", $priceandstock_ids).") AND `stock` IN (0)");
		}
		if($items_out_of_stock > 0) {
			$out_of_stock = true;
		}
	} else if(($product['quantity'] == 0)) { // otherwise, use the stock from the products list table
	  $out_of_stock = true;
	}
}
	if($out_of_stock === true) {
		$state['state'] = true;
		$state['messages'][] = TXT_WPSC_OUT_OF_STOCK_ERROR_MESSAGE;
	}

return array('state' => $state['state'], 'messages' => $state['messages']);
}


/*
* if UPS is on, this function checks every product on the products page to see if it has a weight
* it is executed through the wpsc_product_alert filter
*/
function wpsc_check_weight($state, $product) {
global $wpdb;
$custom_shipping = (array)get_option('custom_shipping_options');
$has_no_weight = false;
// only do anything if UPS is on and shipping is used
if((array_search('ups', $custom_shipping) !== false) && ($product['no_shipping'] != 1)) {
	$excluded_values = '';
	// get the variation IDs  associated with this product
	$variation_ids = $wpdb->get_col("SELECT `variation_id` FROM `".WPSC_TABLE_VARIATION_ASSOC."` WHERE `type` IN ('product') AND `associated_id` IN ('{$product['id']}')");
	// if there are any, look through them for itemswith no weight
	if(count($variation_ids) > 0) { 
		// sort and comma seperate them
		asort($variation_ids);
		$all_variation_ids = implode(",", $variation_ids);

		// get the visible variation values associated with this product
		$enabled_values = $wpdb->get_col("SELECT `value_id` FROM `".WPSC_TABLE_VARIATION_VALUES_ASSOC."` WHERE `product_id` IN('{$product['id']}') AND `visible` IN ('1')");

		// get the priceandstock IDs using the variation and variation value IDs
		$priceandstock_ids = $wpdb->get_col("SELECT `priceandstock_id` FROM `".WPSC_TABLE_VARIATION_COMBINATIONS."` WHERE `product_id` = '{$product['id']}'  AND `all_variation_ids` IN('$all_variation_ids') AND `value_id` IN (".implode(",", $enabled_values).")  GROUP BY `priceandstock_id` HAVING COUNT( `priceandstock_id` ) = '".count($variation_ids)."'");

		// count the variation combinations with a weight of zero
		$unweighted_items = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_VARIATION_PROPERTIES."` WHERE `id` IN(".implode(",", $priceandstock_ids).") AND `weight` IN (0)");
		if($unweighted_items > 0) {
			$has_no_weight = true;
		}
	} else if(($product['weight'] == 0)) { // otherwise, use the stock from the products list table
		$has_no_weight = true;
		//echo "<pre>".print_r($product,true)."</pre>";
	}
	if($has_no_weight === true) {
		$state['state'] = true;
		$state['messages'][] = TXT_WPSC_UPS_AND_WEIGHT_ERROR_MESSAGE;
	}
}
return array('state' => $state['state'], 'messages' => $state['messages']);
}

add_filter('wpsc_product_alert', 'wpsc_check_stock', 10, 2);
add_filter('wpsc_product_alert', 'wpsc_check_weight', 10, 2);


?>

Link to comment
Share on other sites

  • 1 year later...

Beware of the evil venue_id!

 

Is your payment module sending in the main product names and SKU okay but not any product variations?

 

If you are developing or debugging payment modules for WP e-commerce, and you are tearing out your hair because the product variations aren't being passed through, the solution is to rename venue_id to value_id in the following code:

 

if($variation_count >= 1)
      	{
      		$variation_list = " (";
      		$j = 0;
      		foreach($variation_data as $variation)
        	{
        		if($j > 0)
          		{
          			$variation_list .= " ";
          		}
        		$value_id = $variation['venue_id'];
        		$value_data = $wpdb->get_results("SELECT * FROM <code>".WPSC_TABLE_VARIATION_VALUES."</code> WHERE <code>id</code>='".$value_id."' LIMIT 1",ARRAY_A);
        		$variation_list .= $value_data[0]['name'];
        		$j++;
        	}
      		$variation_list .= ")";
      	}

ie. $value_id = $variation['venue_id']; to


$value_id = $variation['value_id'];

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.