<?php
if(@$_GET['action']!='centinel2'){
	@include 'adminsession.php';
	session_cache_limiter('none');
	session_start();
}
ob_start();
header('Cache-Control: no-cache');
header('Pragma: no-cache');
//This code is copyright (c) ViciSoft SL, all rights reserved.
//The contents of this file are protected under law as the intellectual property
//of ViciSoft SL. Any use, reproduction, disclosure or copying
//of any kind without the express and written permission of ViciSoft SL is forbidden.
//Author: Vince Reid, vincereid@gmail.com
$GLOBALS['isvsadmindir']=TRUE;
include 'db_conn_open.php';
include 'inc/languageadmin.php';
include 'inc/languagefile.php';
include 'includes.php';
include 'inc/incemail.php';
include 'inc/incfunctions.php';
ob_clean();
if(@$storesessionvalue=='') $storesessionvalue='virtualstore';
if(! ( (getget('SS-UserName')!='' && getget('SS-Password')!='') || getget('opayo')!='' || getget('action')=='vieworder' || getget('action')=='pay360' || getget('action')=='globalpayments' || getget('action')=='squareup' || getget('action')=='imageupload' || getget('action')=='autosearch' || getget('action')=='appstatus' || getget('action')=='screlated' || getget('action')=='execppsale' || getget('action')=='createppsale' || getget('action')=='termsandconditions' || getget('action')=='logoutaccount' || getget('action')=='loginaccount' || getget('action')=='createaccount' || getget('action')=='contactus'|| @$_GET['action']=='ipnarrived' || @$_GET['action']=='notifystock' || @$_GET['action']=='clord' || @$_GET['action']=='applycert' || @$_GET['action']=='centinel' || @$_GET['action']=='centinel2')){
	if(!@$GLOBALS['disallowlogin']) include 'inc/incloginfunctions.php';
	if(@$_SESSION['loggedon']!=$storesessionvalue || @$GLOBALS['disallowlogin']){
		if(@$_SERVER['HTTPS']=='on' || @$_SERVER['SERVER_PORT']=='443')$prot='https://';else $prot='http://';
		header('Location: '.$prot.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']).'/login.php');
		exit;
	}
}
$GLOBALS['usewordpressphpmailer']=FALSE;
$alreadygotadmin=getadminsettings();
if(@$dateadjust=='') $dateadjust=0;
if(@$dateformatstr=='') $dateformatstr='m/d/Y';
$admindatestr='Y-m-d';
if(@$admindateformat=='') $admindateformat=0;
if($admindateformat==1)
	$admindatestr='m/d/Y';
elseif($admindateformat==2)
	$admindatestr='d/m/Y';
function sendmessagewithbasicauth($themessage){
	global $googledata1,$googledata2,$googledemomode,$curlproxy,$success;
	$cfurl='https://' . ($googledemomode ? 'sandbox' : 'checkout') . '.google.com' . ($googledemomode ? '/checkout' : '') . '/api/checkout/v2/request/Merchant/' . $googledata1;
	$success=TRUE;
	if(@$pathtocurl != ''){
		exec($pathtocurl . ' -H \'Authorization: Basic ' . base64_encode($googledata1 . ':' . $googledata2) . '\' -H \'Content-Type: application/xml\' -H \'Accept: application/xml\' --data-binary ' . escapeshellarg('<?xml version="1.0" encoding="UTF-8"?>' . $themessage) . ' ' . $cfurl, $cfres, $retvar);
		$cfres=implode("\n",$cfres);
	}else{
		if(!$ch=curl_init()) {
			print "cURL package not installed in PHP. Set \$pathtocurl parameter.";
			$success=FALSE;
		}else{
			curl_setopt($ch, CURLOPT_URL, $cfurl);
			$headers=array('Authorization: Basic ' . base64_encode($googledata1 . ":" . $googledata2), 'Content-Type: application/xml', 'Accept: application/xml');
			curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_POSTFIELDS, '<?xml version="1.0" encoding="UTF-8"?>' . $themessage);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			if(@$curlproxy!=''){
				curl_setopt($ch, CURLOPT_PROXY, $curlproxy);
			}
			$cfres=curl_exec($ch);
			if(curl_error($ch)!=''){
				print 'cURL error: ' . curl_error($ch) . '<br />';
				$success=FALSE;
			}else{
				curl_close($ch);
			}
		}
	}
	return($cfres);
}
if(@$_SESSION['clientLoginLevel']!='') $minloglevel=$_SESSION['clientLoginLevel']; else $minloglevel=0;
function saveimageupload($ordid){
	$retvals='';
	$imagesperitem=1;
	$maximages=0;
	$maxfilesize=2*1024*1024;
	$filetypes='.bmp,.gif,.jpe,.jpeg,.jpg,.pdf,.png,.tif,.tiff,.webp';
	if(@$GLOBALS['uploadfilenametemplate']=='') $GLOBALS['uploadfilenametemplate']='i%ordid%_%imagenum%'; // %ordid% %imagenum% %filename%
	if(@$GLOBALS['uploaditemsperorder']!='') $imagesperitem=$GLOBALS['uploaditemsperorder'];
	if(@$GLOBALS['uploadmaxfilesize']!='') $maxfilesize=$GLOBALS['uploadmaxfilesize'];
	if(@$GLOBALS['uploadfiletypes']!='') $filetypes=$GLOBALS['uploadfiletypes'];
	$sSQL="SELECT " . (@$GLOBALS['uploaditemsbyquantity']?'SUM(cartQuantity)':'COUNT(cartID)') . " AS sumquant FROM cart INNER JOIN products ON cart.cartProdID=products.pID WHERE cartOrderID='" . escape_string($ordid) . "' AND products.pUpload<>0";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$maximages=$rs['sumquant']*$imagesperitem;
		if($maximages>100) $maximages=100;
	}
	ect_free_result($result);
	$sSQL="SELECT uploadDir FROM admin WHERE adminID=1";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)) $imageuploaddir=trim_($rs['uploadDir']);
	ect_free_result($result);
	if(!file_exists($imageuploaddir))
		$imageuploaddir='';
	if($imageuploaddir=='')
		return 'NOUPLOADDIR';
	for($i=0;$i < $maximages;$i++){
		if(@$_FILES['myFiles'.$i]){
			$retval='';
			$extension=pathinfo(getpost('filename'.$i),PATHINFO_EXTENSION);
			$origfilename=pathinfo(getpost('filename'.$i),PATHINFO_FILENAME);
			$origfilename=preg_replace('/[^a-z0-9_]+/','',strtolower($origfilename));
			$origfilename=substr_($origfilename,0,18);
			if(strlen($extension)<2||strpos(strtolower($filetypes),'.'.strtolower($extension))===FALSE)
				$retval='ILLEGALEXTENSION';
			$imgnum=0;
			if($retval==''){
				$sSQL="SELECT COUNT(*) AS countups FROM imageuploads WHERE upOrderID='" . escape_string($ordid) . "'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if($rs['countups']>$maximages)
						$retval='MAXIMAGES';
				}
				ect_free_result($result);
			}
			$freeimageslot=FALSE;
			if($retval==''){
				while($imgnum<100&&!$freeimageslot){
					$imagefilename=strreplace(array('%ordid%','%imagenum%','%filename%'),array(sprintf('%06d',getpost('orderid')),sprintf('%02d',$imgnum),$origfilename),$GLOBALS['uploadfilenametemplate'].($imgnum>0&&(strpos($GLOBALS['uploadfilenametemplate'],'%imagenum%')===FALSE)?'_%imagenum%':'')) . '.' . $extension;
					$freeimageslot=!file_exists($imageuploaddir . DIRECTORY_SEPARATOR . $imagefilename);
					$imgnum++;
				}
			}
			if($retval!=''){
			}elseif($freeimageslot){
				$retval='SUCCESS';
				$comments=substr_(strip_tags(getpost('comments')),0,1024);
				if(!@$GLOBALS['uploadnousemultipart']){
					if(!move_uploaded_file($_FILES['myFiles'.$i]['tmp_name'], $imageuploaddir . DIRECTORY_SEPARATOR . $imagefilename))
						$retval='NOMOVEFILE';
				}else{
					if($fd=@fopen($imageuploaddir . DIRECTORY_SEPARATOR . $imagefilename,'wb')){
						$imgsrcarr=explode('base64,',getpost('imgsrc'),2);
						$imgsrc=base64_decode($imgsrcarr[1]);
						if(strlen($imgsrc)>$maxfilesize)
							$retval='MAXFILESIZE';
						else{
							if(fwrite($fd,$imgsrc)===FALSE) $retval='NOWRITEFILE';
							fclose($fd);
						}
					}else
						$retval='NOOPENFILE';
				}
				if($retval=='SUCCESS'){
					$sSQL="INSERT INTO imageuploads (upOrderID,upFilename,upComments) VALUES ('" . escape_string($ordid) . "','" . escape_string($imagefilename) . "','" . escape_string($comments) . "')";
					ect_query($sSQL) or ect_error();
				}
			}else
				$retval='MAXIMAGES';
			$retvals.=($retvals!=''?':':'').$retval;
		}
	}
	return $retvals;
}
function checkemfuserblock(){
	$multiemfblocked=FALSE;
	$theip=$GLOBALS['REMOTE_ADDR'];
	if($theip=='') $theip='none';
	if($GLOBALS['blockcontactemails']!=0){
		ect_query("DELETE FROM multibuyblock WHERE lastaccess<'" . date('Y-m-d H:i:s', time()-(60*60*24)) . "'") or ect_error();
		$sSQL="SELECT ssdenyid,sstimesaccess FROM multibuyblock WHERE ssdenyip='EMF " . trim_(escape_string($theip)) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			ect_query("UPDATE multibuyblock SET sstimesaccess=sstimesaccess+1,lastaccess='" . date('Y-m-d H:i:s', time()) . "' WHERE ssdenyid=" . $rs['ssdenyid']) or ect_error();
			if($rs['sstimesaccess']>=$GLOBALS['blockcontactemails']) $multiemfblocked=TRUE;
		}else{
			ect_query("INSERT INTO multibuyblock (ssdenyip,lastaccess) VALUES ('EMF " . trim_(escape_string($theip)) . "','" . date('Y-m-d H:i:s', time()) . "')") or ect_error();
		}
		ect_free_result($result);
	}
	if($theip=='none' || ip2long($theip)==FALSE)
		$sSQL='SELECT dcid FROM ipblocking LIMIT 0,1';
	else
		$sSQL='SELECT dcid FROM ipblocking WHERE (dcip1=' . ip2long($theip) . ' AND dcip2=0) OR (dcip1 <= ' . ip2long($theip) . ' AND ' . ip2long($theip) . ' <= dcip2 AND dcip2 <> 0)';
	$result=ect_query($sSQL) or ect_error();
	if(ect_num_rows($result) > 0)
		$multiemfblocked=TRUE;
	return($multiemfblocked);
}
if(getget('action')=='getevent'&&is_numeric(getget('eventid'))){
	$sSQL = "SELECT eventText FROM auditlog WHERE logID='" . escape_string(getget('eventid')) . "'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result))
		print strreplace(array("\r","\n"),array('','<br>'),htmlspecials($rs['eventText']));
	else
		print 'Event not found';
}elseif(getget('action')=='avataxping'){
	$avalarastate=getpost('avalarastate');
	$avalaraacctno=getpost('avalaraacctno');
	$avalaralicensekey=getpost('avalaralicensekey');
	$authtext=$avalaraacctno.":".$avalaralicensekey;
	$authtext64=base64_encode($authtext);

	$GLOBALS['xmlfnheaders']=array("Authorization: Basic " . $authtext64,"Content-Type: application/json");

	if(callcurlfunction('https://' . (abs($avalarastate)=='1'?'sandbox-':'') . 'rest.avatax.com/api/v2/utilities/ping','',$jres,'',$errormsg,FALSE)){
		$jsarray=json_decode((string)$jres);
		if($jsarray->{'authenticated'})
			print 'Connection Successful!';
		else
			print 'Connection failed! Please check the Username, Password and Environment';
	}else
		print 'Could not connect to Avalara server.';
}elseif(getget('action')=='pponboard'){
	$demomode=@$paypal_sandbox!='';
	//$seller_nonce=uniqid(date('Ymd'),TRUE);
	//$seller_nonce=strreplace('.','_',$seller_nonce);
	$seller_nonce=$_SESSION['seller_nonce'];
	$access_token="";
	//$xmlfnuser=getpost("sharedId");
	$xmlfnheaders=array('Authorization: Basic ' . base64_encode(getpost("sharedId") . ":"));
	$data="grant_type=authorization_code&code=".getpost("authCode").'&code_verifier='.$seller_nonce;
	if(callcurlfunction('https://api-m.' . $paypal_sandbox . 'paypal.com/v1/oauth2/token',$data,$jres,'',$errormsg,FALSE)){
		$jsarray=json_decode((string)$jres);
		$access_token=@$jsarray->{'access_token'};
		$xmlfnheaders=array("Content-Type: application/json","Authorization: Bearer " . $access_token);
		if(callcurlfunction('https://api-m.' . $paypal_sandbox . 'paypal.com/v1/customer/partners/' . $paypal_merchant_id . '/merchant-integrations/credentials/','',$jres,'',$errormsg,FALSE)){
			$jsarray=json_decode((string)$jres);
			$client_id=@$jsarray->{'client_id'};
			$client_secret=@$jsarray->{'client_secret'};
			$payer_id=@$jsarray->{'payer_id'};
			if($client_id!=''&&$client_secret!=''){
				$access_token="";
				$xmlfnheaders=array('Authorization: Basic ' . base64_encode($client_id . ":" . $client_secret), 'Content-Type: application/json', 'PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP');
				if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v1/oauth2/token',"grant_type=client_credentials",$jres,'',$errormsg,FALSE)){
					$jsarray=json_decode($jres);
					$access_token=@$jsarray->{'access_token'};
					if($access_token=='')
						print 'Error: No Access Token';
					else{
						$sJSON='{"url":"'.$storeurlssl.'vsadmin/ppwebhook.php","event_types":[
							{"name":"PAYMENT.CAPTURE.COMPLETED"},
							{"name":"PAYMENT.CAPTURE.DENIED"},
							{"name":"PAYMENT.CAPTURE.REVERSED"},
							{"name":"PAYMENT.CAPTURE.REFUNDED"},
							{"name":"PAYMENT.CAPTURE.PENDING"},
							{"name":"CHECKOUT.ORDER.COMPLETED"},
							{"name":"CHECKOUT.ORDER.APPROVED"},
							{"name":"CHECKOUT.ORDER.PROCESSED"},
							{"name":"PAYMENT.AUTHORIZATION.CREATED"},
							{"name":"PAYMENT.AUTHORIZATION.VOIDED"}
						]}';
						$xmlfnheaders=array("Content-Type: application/json","Authorization: Bearer " . $access_token);
						if(callcurlfunction('https://api-m.' . $paypal_sandbox . 'paypal.com/v1/notifications/webhooks',$sJSON,$jres,'',$errormsg,FALSE)){
							$jsarray=json_decode($jres);
							$webhook_id=@$jsarray->{'id'};
							$sSQL="UPDATE payprovider SET payProvData1='".escape_string($client_id)."',payProvData2='".escape_string($client_secret)."',payProvData4='".escape_string($payer_id)."',payProvData5='".escape_string($webhook_id)."',payProvFlag1=1,payProvFlag2=0 WHERE payProvID=27";
							ect_query($sSQL) or ect_error();
							print 'SUCCESS';
						}else
							print 'Error: ' . $jres;
					}
				}else
					print "Error: " . $errormsg;
			}else
				print 'Error retrieving credentials: ' . $jres;
		}
	}
}elseif(getget('action')=='vieworder'){
	$GLOBALS['fromajaxservice']=TRUE;
	$ordID=strreplace("'",'',getpost('theid'));
	if(is_numeric($ordID)&&is_numeric(@$_SESSION['clientID'])) $success=TRUE; else $success=FALSE;
	if($success){
		$sSQL="SELECT ordID FROM orders WHERE ordID=" . $ordID . " AND ordClientID=" . $_SESSION['clientID'];
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)==0) $success=FALSE;
		ect_free_result($result);
	}
	if($success){
		$GLOBALS['xxThkYou']=imageorbutton(@$imgbackacct,$GLOBALS['xxBack'],'backacct','history.go(-1)',TRUE);
		$GLOBALS['xxRecEml']='';
		$thankspagecontinue='javascript:hideviewimage()';
		$GLOBALS['xxCntShp']=$GLOBALS['xxBack'];
		$imgcontinueshopping=@$imgbackacct;
		do_order_success($ordID,$emailAddr,FALSE,TRUE,FALSE,FALSE,FALSE);
	}else{
		print '<div style="margin:50px;text-align:center">Sorry, could not find a matching order.</div>';
	}
}elseif(getget('opayo')!=''){
	$opayosuccess=TRUE;
	$opayoreason='';
	$ordID=explode('-',getpost('VendorTxCode'));
	$ordID=$ordID[0];
	if(getpost('Status')=='OK'){
		if(getpayprovdetails(24,$data1,$data2,$data3,$demomode,$ppmethod)&&is_numeric($ordID)){
			$hashstr=$SecurityKey='';
			$sSQL="SELECT ordTransSession FROM orders WHERE ordStatus=2 AND ordID='" . escape_string($ordID) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$SecurityKey=$rs['ordTransSession'];
			}
			ect_free_result($result);
			$hashstr=getpost('VPSTxId') . getpost('VendorTxCode') . getpost('Status') . getpost('TxAuthNo') . strtolower($data1) . getpost('AVSCV2') . $SecurityKey . getpost('AddressResult') . getpost('PostCodeResult') . 
				getpost('CV2Result') . getpost('GiftAid') . getpost('3DSecureStatus') . getpost('CAVV') . getpost('AddressStatus') . getpost('PayerStatus') . getpost('CardType') . getpost('Last4Digits') . 
				getpost('DeclineCode') . getpost('ExpiryDate') . getpost('FraudResponse') . getpost('BankAuthCode') . getpost('ACSTransID') . getpost('DSTransID') . getpost('SchemeTraceID');
			$hashstr=md5($hashstr);
			$hashstrupper=getpost('VPSTxId') . getpost('VendorTxCode') . getpost('Status') . getpost('TxAuthNo') . strtoupper($data1) . getpost('AVSCV2') . $SecurityKey . getpost('AddressResult') . getpost('PostCodeResult') . 
				getpost('CV2Result') . getpost('GiftAid') . getpost('3DSecureStatus') . getpost('CAVV') . getpost('AddressStatus') . getpost('PayerStatus') . getpost('CardType') . getpost('Last4Digits') . 
				getpost('DeclineCode') . getpost('ExpiryDate') . getpost('FraudResponse') . getpost('BankAuthCode') . getpost('ACSTransID') . getpost('DSTransID') . getpost('SchemeTraceID');
			$hashstrupper=md5($hashstrupper);
			//if(strtoupper($hashstr)==getpost('VPSSignature')||strtoupper($hashstrupper)==getpost('VPSSignature')){
			if(getget('opayo')==strtolower(md5($ordID.$GLOBALS['adminSecret'].'opayoisrubbish'))){
				if(getpost('3DSecureStatus')=='NOTAUTHED'){
					$opayosuccess=FALSE;
					$opayoreason='3D Secure Authentication Failure';
				}else{
					print 'Status=OK' . "\r\n";
					print 'StatusDetail=Hashes match - proceeding' . "\r\n";
					print 'RedirectURL=' . $storeurlssl . 'thanks' . $extension . '?action=opayoserver&orderid=' . $ordID . '&checksum=' . md5($SecurityKey.$GLOBALS['adminSecret'].'opayoserver');
					ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'") or ect_error();
					ect_query("UPDATE orders SET ordStatus=3,ordAVS='".escape_string(checkcrossentity(getpost('AddressResult')=='MATCHED').':'.checkcrossentity(getpost('PostCodeResult')=='MATCHED'))."',ordCVV='".escape_string(checkcrossentity(getpost('CV2Result')=='MATCHED'))."',ordAuthNumber='".escape_string(getpost('BankAuthCode'))."',ordTransID='".escape_string(getpost('TxAuthNo'))."' WHERE ordPayProvider=24 AND ordID='" . escape_string($ordID) . "'") or ect_error();
					do_order_success($ordID,$emailAddr,$sendEmail,FALSE,TRUE,TRUE,TRUE);
				}
			}else{
				$opayosuccess=FALSE;
				$opayoreason='Hash mismatch';
			}
		}
	}else{
		$opayosuccess=FALSE;
		$opayoreason=getpost('Status');
	}
	if(!$opayosuccess){
		print 'Status=FAILED' . "\r\n";
		print 'StatusDetail=' . $opayoreason . "\r\n";
		print 'RedirectURL=' . $storeurlssl . 'cart' . $extension . '?action=opayo&reason=' . urlencode($opayoreason);
	}
}elseif(getget('action')=='shiptheory'){
	if(@$GLOBALS['shiptheoryshippedstatus']=='') $GLOBALS['shiptheoryshippedstatus']=4;
	if(@$GLOBALS['shiptheorytrackingstatus']=='') $GLOBALS['shiptheorytrackingstatus']=4;
	$shipTheoryUser=$shipTheoryPass='';
	$sSQL="SELECT adminPacking,shipTheoryUser,shipTheoryPass FROM adminshipping WHERE adminShipID=1";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$GLOBALS['packtogether']=((int)$rs['adminPacking']==1);
		$shipTheoryUser=trim_($rs['shipTheoryUser']);
		$shipTheoryPass=trim_($rs['shipTheoryPass']);
	}
	ect_free_result($result);
	if($shipTheoryUser!=''&&$shipTheoryPass!=''){
		$sSQL='SELECT orderstatussubject,orderstatussubject2,orderstatussubject3,orderstatusemail,orderstatusemail2,orderstatusemail3 FROM emailmessages WHERE emailID=1';
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$ordstatussubject[1]=$rs['orderstatussubject'];
			$ordstatusemail[1]=$rs['orderstatusemail'];
			$ordstatussubject[2]=$rs['orderstatussubject2'];
			$ordstatusemail[2]=$rs['orderstatusemail2'];
			$ordstatussubject[3]=$rs['orderstatussubject3'];
			$ordstatusemail[3]=$rs['orderstatusemail3'];
		}
		ect_free_result($result);

		$data=json_encode(array("email" => $shipTheoryUser,"password" => $shipTheoryPass));
		$GLOBALS['xmlfnheaders']=array("Accept: application/json","Content-Type: application/json");
		if(callcurlfunction('https://api.shiptheory.com/v1/token',$data,$jres,'',$errormsg,FALSE)){
			$jsarray=json_decode((string)$jres);
			$st_token=@$jsarray->{'data'}->{'token'};
		}
		if(getpost('shipids')==''){
			print 'ERROR:Nothing to ship';
		}elseif($st_token!=''){
			$sSQL="SELECT ordID,ordEmail,ordShipping,ordExtra1,ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordZip,ordPhone,ordCountry,ordShipExtra1,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipZip,ordShipPhone,ordShipCountry,ordShipType,ordAddInfo FROM orders WHERE ordID IN (" . getpost('shipids') . ")";
			$stresult=ect_query($sSQL) or ect_error();
			while($strs=ect_fetch_assoc($stresult)){
				$hasshipaddress=(trim_($strs['ordShipAddress'])!='');
				$sSQL="SELECT countryCode FROM countries WHERE countryName='" . escape_string($hasshipaddress ? $strs['ordShipCountry'] : $strs['ordCountry']) . "'";
				$result2=ect_query($sSQL) or ect_error();
				$countryCode='';
				if($rs2=ect_fetch_assoc($result2))
					$countryCode=$rs2['countryCode'];
				ect_free_result($result2);
				$products=[];
				$totprice=$totweight=$totquantity=0;
				$sSQL="SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartQuantity,pWeight FROM cart INNER JOIN products on cart.cartProdID=products.pID WHERE cartOrderID='" . escape_string($strs['ordID']) . "' ORDER BY cartID";
				$result2=ect_query($sSQL) or ect_error();
				while($rs2=ect_fetch_assoc($result2)){
					$optpricediff=0;
					$optweightdiff=0;
					$sSQL="SELECT coOptGroup,coCartOption,coPriceDiff,coWeightDiff FROM cartoptions WHERE coCartID='" . escape_string($rs2['cartID']) . "'";
					$result3=ect_query($sSQL) or ect_error();
					while($rs3=ect_fetch_assoc($result3)){
						$optpricediff+=$rs3['coPriceDiff'];
						$optweightdiff+=$rs3['coWeightDiff'];
					}
					$products[]=array("name" => $rs2['cartProdName'],"sku" => $rs2['cartProdID'],"qty" => $rs2['cartQuantity'],"value" => ($rs2['cartProdPrice']+$optpricediff),"weight" => ($rs2['pWeight']+$optweightdiff));
					$totprice+=($rs2['cartProdPrice']+$optpricediff)*$rs2['cartQuantity'];
					$totweight+=($rs2['pWeight']+$optweightdiff)*$rs2['cartQuantity'];
					$totquantity+=$rs2['cartQuantity'];
				}
				splitname($hasshipaddress?$strs['ordShipName'].' '.$strs['ordShipLastName']:$strs['ordName'].' '.$strs['ordLastName'],$firstname,$lastname);
				$data_array=array(
					"reference" => $strs['ordID'],
					"reference2" => @$GLOBALS['shiptheoryreference']!=''?$GLOBALS['shiptheoryreference']:'SHIPMENT',
					"shipment_detail" => array(
						"shipping_price" => $strs['ordShipping'],
						"channel_shipservice_name" => $strs['ordShipType'],
						"weight" => $totweight,
						"parcels" => $GLOBALS['packtogether']?1:$totquantity,
						"value" => $totprice
					),
					"recipient" => array(
						"company" => $hasshipaddress?$strs['ordShipExtra1']:$strs['ordExtra1'],
						"firstname" => $firstname,
						"lastname" => $lastname,
						"address_line_1" => $hasshipaddress?$strs['ordShipAddress']:$strs['ordAddress'],
						"address_line_2" => $hasshipaddress?$strs['ordShipAddress2']:$strs['ordAddress2'],
						"city" => $hasshipaddress?$strs['ordShipCity']:$strs['ordCity'],
						"county" => $hasshipaddress?$strs['ordShipState']:$strs['ordState'],
						"postcode" => $hasshipaddress?$strs['ordShipZip']:$strs['ordZip'],
						"telephone" => $hasshipaddress?$strs['ordShipPhone']:$strs['ordPhone'],
						"email" => $strs['ordEmail'],
						"country" => $countryCode
					),
					"products" => $products
				);
				if(is_array(@$GLOBALS['shiptheorysender']))
					$data_array['sender']=$GLOBALS['shiptheorysender'];
				if(trim_($strs['ordAddInfo'])!='')
					$data_array['shipment_detail']['instructions']=substr_($strs['ordAddInfo'],0,1000);
				$data = json_encode($data_array);

				$GLOBALS['xmlfnheaders']=array("Accept: application/json","Content-Type: application/json","Authorization: Bearer " . $st_token);
				if(callcurlfunction('https://api.shiptheory.com/v1/shipments',$data,$jres,'',$errormsg,FALSE)){
					$jsarray=json_decode((string)$jres);
					$trackingnum=@$jsarray->{'carrier_result'}->{'tracking'};
					if(@$jsarray->{'success'}){
						print 'Order ID ' . $strs['ordID'] . " created successfully\n";
						$sSQL="UPDATE orders SET ordTrackNum='" . escape_string($trackingnum) . "' WHERE ordID='" . $strs['ordID'] . "'";
						ect_query($sSQL) or ect_error();
						updateorderstatus($strs['ordID'], $trackingnum!=''?$GLOBALS['shiptheorytrackingstatus']:$GLOBALS['shiptheoryshippedstatus'], TRUE);
					}else{
						if(strpos($jres,'"_isUnique"')!==FALSE){
							$GLOBALS['xmlfnheaders']=array("Accept: application/json","Content-Type: application/json","Authorization: Bearer " . $st_token);
							if(callcurlfunction('https://api.shiptheory.com/v1/shipments/'.$strs['ordID'],'',$jres,'',$errormsg,FALSE)){
								$jsarray=json_decode((string)$jres);
								$trackingnum=@$jsarray->{'shipment'}->{'tracking_number'};
								if($trackingnum!=''){
									$sSQL="UPDATE orders SET ordTrackNum='" . escape_string($trackingnum) . "' WHERE ordID='" . $strs['ordID'] . "'";
									ect_query($sSQL) or ect_error();
									updateorderstatus($strs['ordID'], $GLOBALS['shiptheorytrackingstatus'], TRUE);
								}
								print 'Order ID ' . $strs['ordID'] . " updated successfully\n";
							}
						}else{
							$jsarray=json_decode($jres,true);
							$errobj=@$jsarray['error'];
							while(gettype($errobj)=='array'){
								$errobj=empty($errobj) ? '' : reset($errobj);
							}
							$errtxt=$errobj;
							print 'Order ID ' . $strs['ordID'] . ' failed: ' . $errtxt . "\n";
						}
					}
				}else
					print 'ERROR:Error connecting to ShipTheory -> ' . $errormsg;
			}
		}else
			print 'ERROR:Ship Theory no token returned -> ' . $errormsg;
	}else
		print 'ERROR:Ship Theory login / password not set.';
}elseif(getget('SS-UserName')!='' && getget('SS-Password')!=''){ // Ship Station
	$retval='';
	$username = getget('SS-UserName');
	$password = getget('SS-Password');
	$sSQL="SELECT adminShipID FROM adminshipping WHERE shipStationUser='" . escape_string($username) ."' AND shipStationPass='" . escape_string($password) ."'";
	$result=ect_query($sSQL) or ect_error();
	$loginsuccess=ect_num_rows($result)>0;
	ect_free_result($result);
	if(!$loginsuccess){
		$retval='Login Error';
	}elseif(getget('action')=='shipnotify'){
		if(is_numeric(getget('order_number'))){
			$sSQL='SELECT orderstatussubject,orderstatussubject2,orderstatussubject3,orderstatusemail,orderstatusemail2,orderstatusemail3 FROM emailmessages WHERE emailID=1';
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$ordstatussubject[1]=$rs['orderstatussubject'];
				$ordstatusemail[1]=$rs['orderstatusemail'];
				$ordstatussubject[2]=$rs['orderstatussubject2'];
				$ordstatusemail[2]=$rs['orderstatusemail2'];
				$ordstatussubject[3]=$rs['orderstatussubject3'];
				$ordstatusemail[3]=$rs['orderstatusemail3'];
			}
			ect_free_result($result);

			$shipcarrier='';
			if(@$GLOBALS['shipstationshippedstatus']=='') $GLOBALS['shipstationshippedstatus']=6;
			if(getget('carrier')=='USPS') $shipcarrier=3;
			if(getget('carrier')=='UPS') $shipcarrier=4;
			if(getget('carrier')=='CanadaPost') $shipcarrier=6;
			if(getget('carrier')=='FedEx') $shipcarrier=7;
			if(getget('carrier')=='DHL'||getget('carrier')=='DHLGlobalMail'||getget('carrier')=='DHLCanada') $shipcarrier=9;
			if(getget('carrier')=='AustraliaPost') $shipcarrier=10;
			
			$tracking_number=getget('tracking_number');
			$sSQL="SELECT ordTrackNum FROM orders WHERE ordID='" . escape_string(getget('order_number')) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if(trim_($rs['ordTrackNum'])!=''){
					if(strpos($rs['ordTrackNum'],$tracking_number)===FALSE)
						$tracking_number=$rs['ordTrackNum'].','.$tracking_number;
					else
						$tracking_number=$rs['ordTrackNum'];
				}
			}
			ect_free_result($result);
			
			$sSQL="UPDATE orders SET ordTrackNum='" . escape_string($tracking_number) . "'";
			if($shipcarrier!='') $sSQL.=",ordShipCarrier='" . escape_string($shipcarrier) . "'";
			$sSQL.=" WHERE ordID='" . escape_string(getget('order_number')) . "'";
			ect_query($sSQL) or ect_error();
			updateorderstatus(getget('order_number'), $GLOBALS['shipstationshippedstatus'], TRUE);
		}else
			$retval='Illegal Order Number';
	}elseif(getget('action')=='export'){
		$UTC = new DateTimeZone("UTC");
		$startdate=new DateTime(getget('start_date'), $UTC );
		$startdate=$startdate->modify('-1 day');
		$enddate=new DateTime(getget('end_date'), $UTC );
		
		$payproviders=[];
		$sSQL="SELECT payProvID,payProvName FROM payprovider ORDER BY payProvID";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result))
			$payproviders[$rs['payProvID']]=$rs['payProvName'];
		ect_free_result($result);
		
		if(($GLOBALS['adminUnits'] & 3)==1) $weightunits='Pounds'; else $weightunits='Grams';
		$sSQL="SELECT ordID,ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordZip,ordCountry,ordEmail,ordPhone,ordExtra1,ordExtra2,ordShipExtra1,ordShipExtra2,ordCheckoutExtra1,ordCheckoutExtra2,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipZip,ordShipCountry,ordShipPhone,ordPayProvider,ordAuthNumber,ordTotal,ordDate,ordStateTax,ordCountryTax,ordHSTTax,ordShipping,ordHandling,ordShipType,ordDiscount,ordAffiliate,ordDiscountText,ordStatus,ordStatusDate,statPrivate,ordAddInfo,ordPrivateStatus FROM orders INNER JOIN orderstatus ON orders.ordStatus=orderstatus.statID WHERE (ordDate>='" . date('Y-m-d H:i:s', $startdate->getTimestamp()+($dateadjust*60*60)) . "' AND ordDate<='" . date('Y-m-d H:i:s', $enddate->getTimestamp()+($dateadjust*60*60)) . "') OR (ordStatusDate>='" . date('Y-m-d H:i:s', $startdate->getTimestamp()+($dateadjust*60*60)) . "' AND ordStatusDate<='" . date('Y-m-d H:i:s', $enddate->getTimestamp()+($dateadjust*60*60)) . "' AND ordDate>='" . date('Y-m-d H:i:s', $startdate->getTimestamp()-(365*60*60*24)) . "')";
		$result=ect_query($sSQL) or ect_error();
		$retval='<?xml version="1.0" encoding="utf-8"?>
			<Orders pages="1">';
		while($rs=ect_fetch_assoc($result)){
			$hasshipaddress=(trim_($rs['ordShipAddress'])!='');
			$sSQL="SELECT countryCode FROM countries WHERE countryName='" . escape_string($hasshipaddress ? $rs['ordShipCountry'] : $rs['ordCountry']) . "'";
			$result2=ect_query($sSQL) or ect_error();
			$countryCode='';
			if($rs2=ect_fetch_assoc($result2))
				$countryCode=$rs2['countryCode'];
			ect_free_result($result2);
			if($countryCode!=''){
				$retval.='<Order>
				<OrderID><![CDATA[' . $rs['ordID'] . ']]></OrderID>
				<OrderNumber><![CDATA[' . $rs['ordID'] . ']]></OrderNumber>
				<OrderDate>' . gmdate('m/d/Y H:i:s', strtotime($rs['ordDate'])) . '</OrderDate>
				<OrderStatus><![CDATA[' . substr_(trim_($rs['statPrivate']),0,50) . ']]></OrderStatus>
				<LastModified>' . gmdate('m/d/Y H:i:s', strtotime($rs['ordStatusDate'])) . '</LastModified>
				<ShippingMethod><![CDATA[' . substr_(trim_($rs['ordShipType']),0,100) . ']]></ShippingMethod>
				<PaymentMethod><![CDATA[' . substr_(trim_($payproviders[$rs['ordPayProvider']]),0,50) . ']]></PaymentMethod>
				<OrderTotal>' . $rs['ordTotal'] . '</OrderTotal>
				<TaxAmount>' . ($rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']) . '</TaxAmount>
				<ShippingAmount>' . ($rs['ordShipping']+$rs['ordHandling']) . '</ShippingAmount>
				<CustomerNotes><![CDATA[' . substr_(trim_($rs['ordAddInfo']),0,1000) . ']]></CustomerNotes>
				<InternalNotes><![CDATA[' . substr_(trim_($rs['ordPrivateStatus']),0,1000) . ']]></InternalNotes>
				<Customer>
					<CustomerCode><![CDATA[' . substr_(trim_($rs['ordEmail']),0,50) . ']]></CustomerCode>
					<BillTo>
						<Name><![CDATA[' . substr_(trim_($rs['ordName'] . ' ' . $rs['ordLastName']),0,50) . ']]></Name>
						<Company><![CDATA[' . substr_(trim_($rs['ordExtra1']),0,50) . ']]></Company>
						<Phone><![CDATA[' . substr_(trim_($rs['ordPhone']),0,50) . ']]></Phone>
						<Email><![CDATA[' . substr_(trim_($rs['ordEmail']),0,50) . ']]></Email>
					</BillTo>
					<ShipTo>
						<Name><![CDATA[' . substr_(trim_($hasshipaddress ? trim_($rs['ordShipName'] . ' ' . $rs['ordShipLastName']) : trim_($rs['ordName'] . ' ' . $rs['ordLastName'])),0,50) . ']]></Name>
						<Company><![CDATA[' . substr_(trim_($hasshipaddress ? $rs['ordShipExtra1'] : $rs['ordExtra1']),0,50) . ']]></Company>
						<Address1><![CDATA[' . substr_(trim_($hasshipaddress ? $rs['ordShipAddress'] : $rs['ordAddress']),0,50) . ']]></Address1>
						<Address2><![CDATA[' . substr_(trim_($hasshipaddress ? $rs['ordShipAddress2'] : $rs['ordAddress2']),0,50) . ']]></Address2>
						<City><![CDATA[' . substr_(trim_($hasshipaddress ? $rs['ordShipCity'] : $rs['ordCity']),0,50) . ']]></City>
						<State><![CDATA[' . getstateorabbreviation(trim_($hasshipaddress ? $rs['ordShipState'] : $rs['ordState']),0,50) . ']]></State>
						<PostalCode><![CDATA[' . substr_(trim_($hasshipaddress ? $rs['ordShipZip'] : $rs['ordZip']),0,50) . ']]></PostalCode>
						<Country><![CDATA[' . $countryCode . ']]></Country>
						<Phone><![CDATA[' . substr_(trim_($hasshipaddress ? $rs['ordShipPhone'] : $rs['ordPhone']),0,50) . ']]></Phone>
					</ShipTo>
				</Customer>
				<Items>';
				$sSQL="SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartQuantity,pWeight FROM cart INNER JOIN products on cart.cartProdID=products.pID WHERE cartOrderID='" . escape_string($rs['ordID']) . "' ORDER BY cartID";
				$result2=ect_query($sSQL) or ect_error();
				while($rs2=ect_fetch_assoc($result2)){
					$optionpricediff=0;
					$optionretval='';
					$sSQL="SELECT coOptGroup,coCartOption,coPriceDiff,coWeightDiff FROM cartoptions WHERE coCartID='" . escape_string($rs2['cartID']) . "'";
					$result3=ect_query($sSQL) or ect_error();
					if(ect_num_rows($result3)>0){
						$optionretval='<Options>';
						while($rs3=ect_fetch_assoc($result3)){
							$optionretval.='<Option>
							<Name><![CDATA[' . $rs3['coOptGroup'] . ']]></Name>
							<Value><![CDATA[' . $rs3['coCartOption'] . ']]></Value>
							<Weight>' . ($weightunits=='Grams' ? ($rs3['coWeightDiff']*1000) : $rs3['coWeightDiff']) . '</Weight>
							</Option>';
							$optionpricediff+=$rs3['coPriceDiff'];
						}
						$optionretval.='</Options>';
					}
					$retval.='<Item>
					<SKU><![CDATA[' . $rs2['cartProdID'] . ']]></SKU>
					<Name><![CDATA[' . $rs2['cartProdName'] . ']]></Name>
					<Weight>' . ($weightunits=='Grams' ? ($rs2['pWeight']*1000) : $rs2['pWeight']) . '</Weight>
					<WeightUnits>' . $weightunits . '</WeightUnits>
					<Quantity>' . $rs2['cartQuantity'] . '</Quantity>
					<UnitPrice>' . ($rs2['cartProdPrice']+$optionpricediff) . '</UnitPrice>' .
					$optionretval .
					'</Item>';
				}
				ect_free_result($result2);
				if($rs['ordDiscount']>0){
					$retval.='<Item>
						<SKU></SKU>
						<Name><![CDATA[Discounts]]></Name>
						<Quantity>1</Quantity>
						<UnitPrice>-' . $rs['ordDiscount'] . '</UnitPrice>
						<Adjustment>true</Adjustment>
					</Item>';
				}
				$retval.='</Items>
				</Order>';
			}
		}
		$retval.='</Orders>';
		ect_free_result($result);
	}else
		$retval='Illegal Action';
	print $retval;
	if(@$debugmode||@$debugxmlemails){
		dosendemail($emailAddr,$emailAddr,'',"Shipstation Debug",$retval);
	}
}elseif(getget('action')=='pay360'){
	$ordID=getget('orderid');
	$GLOBALS['callcurlfunctionhttperrors']=TRUE;
	if(is_numeric($ordID)&&getpayprovdetails(31,$data1,$data2,$data3,$demomode,$ppmethod)){
		$sSQL="SELECT ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordTotal,ordHandling,ordDiscount,ordEmail,ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordCountry,ordZip,ordPhone FROM orders WHERE ordPayProvider=31 AND ordStatus=2 AND ordID='".escape_string($ordID)."'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$sSQL="SELECT countryID,countryCode,countryCode3,loadStates FROM countries WHERE countryName='" . escape_string($rs['ordCountry']) . "'";
			$result2=ect_query($sSQL) or ect_error();
			if($rs2=ect_fetch_assoc($result2)){
				$countryCode3=$rs2['countryCode3'];
			}
			$grandtotal=($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'];
			$signature=hash('sha256',$ordID.$adminSecret.'pay360');
			$url='https://api.' . ($demomode?'mite.':'') . 'pay360.com';
			$post = array("session" => array("returnUrl" => array("url" => $storeurlssl . 'thanks.php?pprov=31&ordid='.$ordID),"transactionNotification" => array("url" => $storeurlssl . 'vsadmin/stripewebhook.php?pprov=31&signature='.$signature,"format" => "REST_JSON")),
				"transaction" => array("merchantReference" => $ordID,"money" => array("amount" => array("fixed" => (string)round($grandtotal,2)),"currency" => $countryCurrency),"deferred" => ($ppmethod==1?true:false)),
				"customer" => array("registered" => false,
						"details" => array("name" => trim_($rs['ordName'] . ' ' . $rs['ordLastName']),
							"address" => array("line1" => $rs['ordAddress'],"line2" => $rs['ordAddress2'],"city" => $rs['ordCity'],"region" => $rs['ordState'],"postcode" => $rs['ordZip'],"countryCode" => $countryCode3),
							"telephone" => $rs['ordPhone'],
							"emailAddress" => $rs['ordEmail'],
							"ipAddress" => $_SERVER['REMOTE_ADDR'])
				)
			);
			$GLOBALS['xmlfnheaders']=array('Content-Type:application/json');
			$GLOBALS['xmlfnuser']=$data2;
			$GLOBALS['xmlfnpassword']=$data3;
			if(callcurlfunction($url . '/hosted/rest/sessions/' . $data1 . '/payments',json_encode($post),$jres,'',$errormsg,FALSE)){
				$jsarray=json_decode((string)$jres);
				if(@$jsarray->{'status'}!='SUCCESS'){
					$success=FALSE;
					print '0:' . @$jsarray->{'reasonMessage'};
				}else{
					$redirecturl=@$jsarray->{'redirectUrl'};
					$pay360sessid=$jsarray->{'sessionId'};
					if($redirecturl!=''&&$pay360sessid!=''){
						$sSQL="UPDATE orders SET ordTransID='',ordTransSession='" . escape_string($pay360sessid) . "' WHERE ordStatus<3 AND ordID='" . escape_string($ordID) . "'";
						ect_query($sSQL) or ect_error();
						print '1:'.$redirecturl;
					}else
						print '0:Redirect URL not returned';
				}
			}else
				print '0:' . $errormsg;
		}
	}
}elseif(getget('action')=='globalpayments'){ ?>
<style>
input.ectbutton,button.ectbutton{
background:#006ABA;
color:#FFF;
padding:6px 12px;
border:0;
border-radius:4px;
font-family:FontAwesome,sans-serif;
cursor:pointer;
font-weight:normal;
-webkit-appearance:none;
}
input.ectbutton:hover,button.ectbutton:hover{
background:#DDD;
color:#000;
}
</style>
<?php
	$errtext='';
	$ordID=getpost('ORDER_ID');
	$AUTHCODE=getpost('AUTHCODE');
	$RESULT=getpost('RESULT');
	$CVV2MATCH=getpost('CVNRESULT');
	$AVSADDR=getpost('AVSADDRESSRESULT');
	$AVSZIP=getpost('AVSPOSTCODERESULT');
	if(getpayprovdetx(32,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
		// timestamp.merchantid.orderid.result.message.pasref.authcode
		$hashstring=getpost('TIMESTAMP').'.'.$data1.'.'.$ordID.'.'.$RESULT.'.'.getpost('MESSAGE').'.'.getpost('PASREF').'.'.$AUTHCODE;
		$hashstring=sha1(sha1($hashstring).'.'.$data2);
		if($hashstring!=getpost('SHA1HASH'))
			$errtext='Invalid Hash Value';
		elseif($RESULT!=='00')
			$errtext=getpost('MESSAGE');
		else{?>
<script>
function globalpaymentscont(){
	window.top.location='<?php print $storeurlssl?>thanks<?php print $extension?>?method=globalpayments&TIMESTAMP=<?php print getpost('TIMESTAMP')?>&ORDER_ID=<?php print $ordID?>&RESULT=<?php print getpost('RESULT')?>&MESSAGE=<?php print urlencode(getpost('MESSAGE'))?>&PASREF=<?php print getpost('PASREF')?>&AUTHCODE=<?php print getpost('AUTHCODE')?>&SHA1HASH=<?php print getpost('SHA1HASH')?>';
}
</script>
<?php		$ordID=explode('-',$ordID);
			$ordID=$ordID[0];
			if(!is_numeric($ordID))
				$errtext='Invalid Order ID';
			else{
				$alreadysentemail=TRUE;
				$result2=ect_query("SELECT ordStatus FROM orders WHERE ordID='" . escape_string($ordID) . "'") or ect_error();
				if($rs=ect_fetch_assoc($result2)) $alreadysentemail=$rs['ordStatus']>=3;
				ect_free_result($result2);
				if(!$alreadysentemail){
					ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'") or ect_error();
					ect_query("UPDATE orders SET ordStatus=3,ordAVS='".escape_string($AVSADDR.$AVSZIP)."',ordCVV='".escape_string($CVV2MATCH)."',ordAuthNumber='".escape_string($AUTHCODE)."',ordTransID='".escape_string(getpost('PASREF'))."' WHERE ordPayProvider=32 AND ordID='" . escape_string($ordID) . "'") or ect_error();
					do_order_success($ordID,$emailAddr,$sendEmail,FALSE,TRUE,TRUE,TRUE);
				}
				print '<div style="text-align:center;font-family:sans-serif;margin-top:50px">';
				print '<div style="font-size:30px">Global Payments</div>';
				print '<div style="margin:50px 0;font-weight:bold">Your transaction has been processed successfully.</div>';
				print '<div>' . imageorbutton('','Please Click Here To View Your Receipt','gpaymentscont','globalpaymentscont()',TRUE) . '</div>';
				print '</div>';
			}
		}
	}else
		$errtext='Global Payments Not Enabled';
	if($errtext!=''){ ?>
<script>
function globalpaymentscont(){
	window.top.location='<?php print $storeurlssl?>cart<?php print $extension?>?mode=checkout';
}
</script>
	<div style="text-align:center;font-family:sans-serif;margin-top:50px"><?php
		print '<div style="font-size:30px;margin:50px 0">Global Payments</div>';
		print $GLOBALS['xxThkErr'];
		print '<div style="margin:50px 0;font-weight:bold">' . $errtext . '</div>';
		print '<div>' . imageorbutton('','Please Click Here To Go Back And Try Again','gpaymentsfail','globalpaymentscont()',TRUE) . '</div>';
?>	</div>
<?php
	}
}elseif(getget("processor")=="squareup"){
	$ordID=getget("gid");
	$payprov=$transid="";
	$success=TRUE;
	$errormsg="";
	$callxmlfunctionstatus=0;
	if(getpayprovdetx(28,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod) && is_numeric($ordID)){
		if(is_numeric($ordID)){
			$sSQL="SELECT ordTransID,ordPayProvider FROM orders WHERE ordID=" . $ordID;
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$transid=$rs['ordTransID'];
				$payprov=$rs['ordPayProvider'];
			}
		}
		if($payprov==28){
			$grandtotal=getpost("amount");
			if($grandtotal==''){
				$sSQL="SELECT ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordTotal,ordHandling,ordDiscount,ordEmail,ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordCountry,ordZip,ordPhone FROM orders WHERE ordID='".escape_string($ordID)."'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					$grandtotal=($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'];
				}
			}
			if(is_numeric($grandtotal)){
				$GLOBALS['callxmlfunctionforcemethod']='PUT';
				$sJSON='{"idempotency_key": "' . uniqid(date('Ymd'),TRUE) . '","payment": {' .
					'"amount_money": {"amount": ' . round(((float)$grandtotal)*100) . ',"currency": "' . $countryCurrency . '"}}}';
				$xmlfnheaders=array("Authorization: Bearer ".$data2,"Content-Type: application/json", "Accept: application/json");
				$success=callcurlfunction('https://connect.squareup' . ($demomode?'sandbox':'') . '.com/v2/payments/'.$transid,$sJSON,$jres,'',$errormsg,FALSE);
				if($GLOBALS['callxmlfunctionstatus']!=200){
					$success=FALSE;
					$jarray=json_decode($jres);
					$errormsg=@$jarray->{'errors'}[0]->{'detail'};
					if($errormsg=="") $errormsg="FAILURE";
				}
			}
			if($success){
				$xmlfnheaders=array("Authorization: Bearer ".$data2,"Content-Type: application/json");
				$success=callcurlfunction('https://connect.squareup' . ($demomode?'sandbox':'') . '.com/v2/payments/'.$transid.'/complete','{}',$jres,'',$errormsg,FALSE);
				if($callxmlfunctionstatus==200){
					ect_query("UPDATE orders SET ordAuthStatus='' WHERE ordID=" . $ordID);
					if(is_numeric(getpost("capstatus"))) ect_query("UPDATE orders SET ordStatus=" . escape_string(getpost("capstatus")) . ",ordStatusDate='" . date("Y-m-d H:i:s", time() + ($dateadjust*60*60)) . "' WHERE ordID=" . $ordID . " AND ordStatus<>" . getpost("capstatus"));
				}else{
					$success=FALSE;
					$jarray=json_decode($jres);
					$errormsg=@$jarray->{'errors'}[0]->{'detail'};
					if($errormsg=="") $errormsg="FAILURE";
				}
			}
		}
		if($success) print "Success"; else print "FAILURE: " . $errormsg;
	}
}elseif(getget('action')=='squareup'){
	$ordID=getpost('ordernumber');
	$btsessionid=getpost('sessionid');
	$success=TRUE;
	$GLOBALS['callxmlfunctionstatus']=0;
	if(getpayprovdetx(28,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod) && is_numeric($ordID)){
		$foundorder=FALSE;
		$grandtotal=0;
		$sJSON='';
		$sSQL="SELECT ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordTotal,ordHandling,ordDiscount,ordEmail,ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordCountry,ordZip,ordPhone FROM orders WHERE ordID='".escape_string($ordID)."'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$foundorder=TRUE;
			$sSQL="SELECT countryCode FROM countries WHERE countryName='" . escape_string($rs['ordCountry']) . "'";
			$result2=ect_query($sSQL) or ect_error();
			if($rs2=ect_fetch_assoc($result2))
				$countryCode=$rs2['countryCode'];
			ect_free_result($result2);
			$grandtotal=($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'];
			$firstname=$rs['ordName']; $lastname=$rs['ordLastName'];
			if(! @$GLOBALS['usefirstlastname']) splitname($rs['ordName'],$firstname,$lastname);
			$sJSON='{"idempotency_key": "' . uniqid(date('Ymd'),TRUE) . '",
				"amount_money": {"amount": ' . ((int)($grandtotal*100)) . ',"currency": "' . $countryCurrency . '"},
				"source_id":' . json_encode(getpost('nonce')) . ',';
			if($data3!='') $sJSON.='"location_id":' . json_encode($data3) . ',"verification_token":' . json_encode(getpost('verification')) . ',';
			$sJSON.='"autocomplete": ' . ($ppmethod==1?'false':'true') . ',
				"billing_address": {"first_name": ' . json_encode($firstname) . ', "last_name": ' . json_encode($lastname) . ', "address_line_1": ' . json_encode($rs['ordAddress']) . ', "address_line_2": ' . json_encode($rs['ordAddress2']) . ', "administrative_district_level_1": ' . json_encode($rs['ordState']) . ', "country": ' . json_encode($countryCode) . ', "postal_code": ' . json_encode($rs['ordZip']) . '},
				"buyer_email_address": ' . json_encode($rs['ordEmail']) . ',
				"reference_id": "' . $ordID . '",
				"note": "' . $ordID . '"
			}';
		}
		ect_free_result($result);
		if($foundorder){
			$xmlfnheaders=array("Authorization: Bearer ".$data2,"Content-Type: application/json");
			if($success=callcurlfunction('https://connect.squareup' . ($demomode?'sandbox':'') . '.com/v2/payments',$sJSON,$jres,'',$errormsg,FALSE)){
				$jarray=json_decode($jres);
				$txn_id='';
				if(@$jarray->{'payment'}->{'status'}=='COMPLETED'||(@$jarray->{'payment'}->{'status'}=='APPROVED'&&$ppmethod==1)){
					$ordcvv=$jarray->{'payment'}->{'card_details'}->{'cvv_status'}=='CVV_ACCEPTED'?1:0;
					$ordavs=$jarray->{'payment'}->{'card_details'}->{'avs_status'}=='AVS_ACCEPTED'?1:0;
					$pendingreason=($ppmethod==1?'Pending: Capture':'');
					$txn_id=$jarray->{'payment'}->{'id'};
					$order_id=$jarray->{'payment'}->{'order_id'};
					ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'") or ect_error();
					ect_query("UPDATE orders SET ordStatus=3,ordPrivateStatus='',ordAuthNumber='" . escape_string($order_id) . "',ordAuthStatus='" . escape_string($pendingreason) . "',ordTransID='" . escape_string($txn_id) . "',ordAVS='" . escape_string($ordavs) . "',ordCVV='" . escape_string($ordcvv) . "' WHERE ordPayProvider=28 AND ordID='" . escape_string($ordID) . "'") or ect_error();
					do_order_success($ordID,$emailAddr,$sendEmail,FALSE,TRUE,TRUE,TRUE);
					print '{"status":"SUCCESS","txn_id":"' . $txn_id . '"}';
				}else{
					$failurereason=@$jarray->{'errors'}[0]->{'detail'};
					if($failurereason!='')
						ect_query("UPDATE orders SET ordPrivateStatus='" . escape_string($failurereason) . "' WHERE ordPayProvider=28 AND ordID='" . escape_string($ordID) . "'") or ect_error();
					print '{"status":"FAILURE","reason":"' . $GLOBALS['xxCCErro'] . '"}';
				}
			}else
				print '{"status":"FAILURE","reason":"' . $errormsg . '"}';
		}else
			print '{"status":"FAILURE","reason":"Already Authorized"}';
	}
}elseif(getget('action')=='imageget'){
	$imagefilename='';
	$imageuploaddir='';
	if(is_numeric(getget('id'))){
		$sSQL="SELECT upFilename FROM imageuploads WHERE upID='" . escape_string(getget('id')) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$imagefilename=$rs['upFilename'];
		}
		ect_free_result($result);
	}
	$sSQL="SELECT uploadDir FROM admin WHERE adminID=1";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$imageuploaddir=$rs['uploadDir'];
	}
	ect_free_result($result);
	if($imageuploaddir!=''&&$imagefilename!=''){
		//ob_clean();
		$fullfilename=$imageuploaddir . DIRECTORY_SEPARATOR . $imagefilename;
		$extension=strtolower(pathinfo($imagefilename, PATHINFO_EXTENSION));
		$sendextension='jpg';
		if($extension=='bmp')
			$sendextension='bmp';
		elseif($extension=='gif')
			$sendextension='gif';
		elseif($extension=='tif'||$extension=='tiff')
			$sendextension='tif';
		if(getget('preview')=='true') print $sendextension.':';
		if($fd=@fopen($fullfilename,'rb')){
			$buffer=fread($fd, filesize($fullfilename));
			if(getget('preview')=='true'){
				$buffer=base64_encode($buffer);
			}else{
				header("Content-Type: application/save"); 
				header('Content-Disposition: attachment; filename="' . $imagefilename . '"');
			}
			print $buffer;
			fclose($fd);
		}
	}
}elseif(getget('action')=='imageupload'){
	if(is_numeric(getpost('orderid'))){
		$ordSessionID='none';
		$sSQL="SELECT ordSessionID FROM orders WHERE ordID='" . escape_string(getpost('orderid')) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$ordSessionID=$rs['ordSessionID'];
		}
		ect_free_result($result);
		$uploadcheck=sha1('imageupload^' . getpost('orderid') . '^' . $GLOBALS['adminSecret'] . '^fromect' . $ordSessionID);
		if($uploadcheck!=getpost('check'))
			print 'ILLEGAL';
		else
			print saveimageupload(getpost('orderid'));
	}else
		print 'ILLEGAL';
}elseif(getget('action')=='autosearch'){
	if(@$GLOBALS['noautosearch']!=TRUE){
		$rc=0;
		if(@$GLOBALS['maxautosearch']=='') $GLOBALS['maxautosearch']=14;
		$listtext=getpost('listtext');
		$listcat=getpost('listcat');
		$secids='';
		if(is_numeric($listcat)){
			$secids=getsectionids($listcat, FALSE);
		}
		for($index=0;$index<=1;$index++){
			if($index==1){
				if($rc==0 && strlen($listtext)>3 && strtolower(substr_($listtext,-1))=='s') $listtext=substr_($listtext,0,-1); else break;
			}
			$sSQL='SELECT pID,'.getlangid('pName',1).' FROM products INNER JOIN sections on products.pSection=sections.sectionID WHERE sectionDisabled<='.$minloglevel.' AND pDisplay<>0 AND ' . ($GLOBALS['useStockManagement'] && @$GLOBALS['noshowoutofstock'] ? 'pInStock>pMinQuant AND ' : '') . (@$GLOBALS['ectsiteid']!='' ? 'pSiteID='.$GLOBALS['ectsiteid'].' AND ' : '') . (@$GLOBALS['nosearcharticles'] ? 'pSchemaType=0 AND ' : '');
			$sSQL.="(" . (@$GLOBALS['nosearchprodid']?'':"pID LIKE '".escape_string($listtext)."%' OR ") . "pSKU LIKE '".escape_string($listtext)."%' OR ".getlangid('pName',1)." LIKE '".escape_string($listtext)."%') ";
			if($secids!='') $sSQL.='AND pSection IN (' . $secids . ') ';
			$sSQL.='ORDER BY '.getlangid('pName',1).' LIMIT 0,'.$GLOBALS['maxautosearch'];
			$result=ect_query($sSQL) or ect_error();
			while($rs=ect_fetch_assoc($result)){
				print rawurlencode($rs[getlangid('pName',1)]).'&';
				$rc++;
			}
			ect_free_result($result);
			if($rc < $GLOBALS['maxautosearch']-5){
				$sSQL='SELECT pID,'.getlangid('pName',1).' FROM products INNER JOIN sections on products.pSection=sections.sectionID WHERE sectionDisabled<='.$minloglevel.' AND pDisplay<>0 AND ' . ($GLOBALS['useStockManagement'] && @$GLOBALS['noshowoutofstock'] ? 'pInStock>pMinQuant AND ' : '') . (@$GLOBALS['ectsiteid']!='' ? 'pSiteID='.$GLOBALS['ectsiteid'].' AND ' : '') . (@$GLOBALS['nosearcharticles'] ? 'pSchemaType=0 AND ' : '');
				$sSQL.="(" . (@$GLOBALS['nosearchprodid']?'':"pID LIKE '%".escape_string($listtext)."%' OR ") . "pSKU LIKE '%".escape_string($listtext)."%' OR ".getlangid('pName',1)." LIKE '%".escape_string($listtext)."%') AND NOT (pID LIKE '".escape_string($listtext)."%' OR pSKU LIKE '".escape_string($listtext)."%' OR ".getlangid('pName',1)." LIKE '".escape_string($listtext)."%') ";
				if($secids!='') $sSQL.='AND pSection IN (' . $secids . ') ';
				$sSQL.='ORDER BY '.getlangid('pName',1).' LIMIT 0,'.($GLOBALS['maxautosearch']-$rc);
				$result=ect_query($sSQL) or ect_error();
				while($rs=ect_fetch_assoc($result)){
					print rawurlencode($rs[getlangid('pName',1)]).'&';
					$rc++;
				}
				ect_free_result($result);
			}
		}
	}
}elseif(getget('action')=='appstatus'){
	$newdeviceid=strreplace(array(' ',"'"),'',getpost("token"));
	if(@$GLOBALS['disallowlogin']){
		print "LOGINDISABLED";
	}elseif(getpost("subact")=="unregister"){
		$sSQL="DELETE FROM devicenotifications WHERE dnID='".escape_string($newdeviceid)."'";
		ect_query($sSQL) or ect_error();
		print "UNREGISTERED";
	}else{
		$dofloodcontrol=FALSE;
		$haspermissions=FALSE;
		if(getpost("subact")=="register"){
			ect_query("DELETE FROM ajaxfloodcontrol WHERE afcAction=5 AND afcDate<'" . date('Y-m-d H:i:s',time()-5) . "'") or ect_error();
			$sSQL="SELECT afcID FROM ajaxfloodcontrol WHERE afcAction=5 AND (afcIP='" . escape_string($REMOTE_ADDR) . "' OR afcSession='" . escape_string(session_id()) . "')";
			$result=ect_query($sSQL) or ect_error();
			$dofloodcontrol=ect_num_rows($result)>0;
			ect_free_result($result);
		}
		$hasgoodlogin=FALSE;
		if(! $dofloodcontrol){
			if(getpost("pw")!='') $hashedpw=dohashpw(getpost("pw")); else $hashedpw='           ';
			$sSQL="SELECT adminID FROM admin WHERE adminUser='".escape_string(getpost("id"))."' AND adminPassword='".escape_string($hashedpw)."'";
			$result=ect_query($sSQL) or ect_error();
			$hasgoodlogin=ect_num_rows($result)>0;
			if($hasgoodlogin) $haspermissions=TRUE;
			ect_free_result($result);
		}
		if(! $hasgoodlogin && ! $dofloodcontrol){
			$sSQL="SELECT adminloginid,adminloginpermissions FROM adminlogin WHERE adminloginname='".escape_string(getpost("id"))."' AND adminloginpassword='".escape_string($hashedpw)."'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$hasgoodlogin=TRUE;
				if(substr_($rs['adminloginpermissions'],14,1)=='X') $haspermissions=TRUE;
			}
			ect_free_result($result);
		}
		if($dofloodcontrol){
			print "FLOODCONTROL";
		}else{
			$sSQL="SELECT dnID FROM devicenotifications WHERE dnID='".escape_string($newdeviceid)."'";
			$result=ect_query($sSQL) or ect_error();
			$hasdeviceid=(ect_num_rows($result)>0);
			ect_free_result($result);
			if($newdeviceid=='' || ! $hasgoodlogin || (getpost('subact')!='register' && ! $hasdeviceid)){
				print 'INVALIDLOGIN';
			}elseif(! $haspermissions){
				print 'NOPERMISSIONS';
			}elseif(getpost('subact')=='clearsalecount'){
				ect_query("UPDATE devicenotifications SET dnLastUpdated='" . date('Y-m-d H:i:s', time()+($dateadjust*60*60)) . "' WHERE dnID='".escape_string($newdeviceid)."'") or ect_error();
				print 'DONECLEAR';
			}elseif(getpost('subact')=='register'){
				if($hasdeviceid){
					print 'ALREADYREGISTERED';
				}else{
					$sSQL="INSERT INTO devicenotifications (dnID,dnLastUpdated) VALUES ('".escape_string($newdeviceid)."','" . date('Y-m-d H:i:s', time()+($dateadjust*60*60)) . "')";
					ect_query($sSQL) or ect_error();
					print 'GOODCONNECT';
				}
			}elseif(getpost('subact')=='getdashboard'){
				if(@$homeordersstatus!='') $ordersstatus='ordStatus IN ('.$homeordersstatus.')'; else $ordersstatus='ordStatus>=3';
				
				$sSQL = " SELECT COUNT(*) AS totalorders, SUM(ordTotal-ordDiscount) AS totalvalue FROM orders WHERE ".$ordersstatus." AND YEAR(ordDate) = YEAR(CURRENT_DATE ) AND MONTH(ordDate) = MONTH(CURRENT_DATE)";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['totalorders'])){print $rs['totalorders'] . '&' . jsurlencode(jsenc(FormatEuroCurrency($rs['totalvalue'])));}else print '0&0';
				}
				$sSQL = " SELECT COUNT(*) AS totalorders, SUM(ordTotal-ordDiscount) AS totalvalue FROM orders WHERE ".$ordersstatus." AND YEAR(ordDate) = YEAR(CURRENT_DATE  - INTERVAL 12 MONTH) AND MONTH(ordDate) = MONTH(CURRENT_DATE - INTERVAL 12 MONTH)";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['totalorders'])){print '&' . $rs['totalorders'] . '&' . jsurlencode(jsenc(FormatEuroCurrency($rs['totalvalue'])));}else print '&0&0';
				}
				$sSQL = " SELECT COUNT(*) AS totalorders, SUM(ordTotal-ordDiscount) AS totalvalue FROM orders WHERE ".$ordersstatus." AND YEAR(ordDate) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)  AND MONTH(ordDate) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['totalorders'])){print '&' . $rs['totalorders'] . '&' . jsurlencode(jsenc(FormatEuroCurrency($rs['totalvalue'])));}else print '&0&0';
				}
				$sSQL = " SELECT COUNT(*) AS totalorders, SUM(ordTotal-ordDiscount) AS totalvalue FROM orders WHERE ".$ordersstatus." AND YEAR(ordDate) = YEAR(CURRENT_DATE - INTERVAL 13 MONTH)  AND MONTH(ordDate) = MONTH(CURRENT_DATE - INTERVAL 13 MONTH)";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['totalorders'])){print '&' . $rs['totalorders'] . '&' . jsurlencode(jsenc(FormatEuroCurrency($rs['totalvalue'])));}else print '&0&0';
				}
				$sSQL = " SELECT COUNT(*) AS totalorders, SUM(ordTotal-ordDiscount) AS totalvalue FROM orders WHERE ".$ordersstatus." AND ordDate BETWEEN '" . date("Y-01-01") . "' AND '" . date("Y-m-d",strtotime("+1 day")) . "'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['totalorders'])){print '&' . $rs['totalorders'] . '&' . jsurlencode(jsenc(FormatEuroCurrency($rs['totalvalue'])));}else print '&0&0';
				}
				$sSQL = " SELECT COUNT(*) AS totalorders, SUM(ordTotal-ordDiscount) AS totalvalue FROM orders WHERE ".$ordersstatus." AND ordDate BETWEEN '" . date("Y-01-01",strtotime("-1 year")) . "' AND '" . date("Y-m-d",strtotime("-1 year")) . "'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['totalorders'])){print '&' . $rs['totalorders'] . '&' . jsurlencode(jsenc(FormatEuroCurrency($rs['totalvalue'])));}else print '&0&0';
				}
				$sSQL = " SELECT COUNT(*) AS totalorders, SUM(ordTotal-ordDiscount) AS totalvalue FROM orders WHERE ".$ordersstatus." AND ordDate BETWEEN '" . date("Y-m-d",strtotime("-1 year")) . "' AND '" . date("Y-m-d",strtotime("+1 day")) . "'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['totalorders'])){print '&' . $rs['totalorders'] . '&' . jsurlencode(jsenc(FormatEuroCurrency($rs['totalvalue'])));}else print '&0&0';
				}
				$sSQL = " SELECT COUNT(*) AS totalorders, SUM(ordTotal-ordDiscount) AS totalvalue FROM orders WHERE ".$ordersstatus." AND ordDate BETWEEN '" . date("Y-m-d",strtotime("-2 year")) . "' AND '" . date("Y-m-d",strtotime("-1 year")) . "'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['totalorders'])){print '&' . $rs['totalorders'] . '&' . jsurlencode(jsenc(FormatEuroCurrency($rs['totalvalue'])));}else print '&0&0';
				}
				$sSQL = " SELECT COUNT(*) AS totalorders, SUM(ordTotal-ordDiscount) AS totalvalue FROM orders WHERE ".$ordersstatus."";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['totalorders'])){print '&' . $rs['totalorders'] . '&' . jsurlencode(jsenc(FormatEuroCurrency($rs['totalvalue'])));}else print '&0&0';
				}
				
				ect_query("UPDATE devicenotifications SET dnLastUpdated='" . date('Y-m-d H:i:s', time()+($dateadjust*60*60)) . "' WHERE dnID='".escape_string($newdeviceid)."'") or ect_error();
			}elseif(getpost("subact")=="alltimetotals"){
				$neworders=0;
				$sSQL="SELECT COUNT(*) AS thecnt FROM orders WHERE ordStatus>=2 AND ordDate>='".date('Y-m-d', time()+($dateadjust*60*60))."'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['thecnt'])) $neworders=$rs['thecnt'];
				}
				$newratings=0;
				$sSQL='SELECT COUNT(*) AS thecnt FROM ratings WHERE rtApproved=0';
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['thecnt'])) $newratings=$rs['thecnt'];
				}
				$newaccounts=0;
				$sSQL="SELECT COUNT(*) AS thecnt FROM customerlogin WHERE clDateCreated>'".date('Y-m-d', time()-(60*60*24))."'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['thecnt'])) $newaccounts=$rs['thecnt'];
				}
				$newmaillist=0;
				$sSQL="SELECT COUNT(*) AS thecnt FROM mailinglist WHERE mlConfirmDate>'".date('Y-m-d', time()-(60*60*24))."'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['thecnt'])) $newmaillist=$rs['thecnt'];
				}
				$newaffiliate=0;
				$sSQL="SELECT COUNT(*) AS thecnt FROM affiliates WHERE affilDate>'".date('Y-m-d', time()-(60*60*24))."'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['thecnt'])) $newaffiliate=$rs['thecnt'];
				}

				$newgiftcert=0;
				$sSQL="SELECT COUNT(*) AS thecnt FROM giftcertificate INNER JOIN orders ON giftcertificate.gcOrderID=orders.ordID WHERE gcOrderID<>0 AND ordStatus>=2 AND gcDateCreated>'".date('Y-m-d', time()-(60*60*24))."'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(!is_null($rs['thecnt'])) $newgiftcert=$rs['thecnt'];
				}
				ect_free_result($result);
				$newstocknotify=0;
				if(@$notifybackinstock){
					$sSQL="SELECT COUNT(*) AS thecnt FROM notifyinstock";
					$result=ect_query($sSQL) or ect_error();
					if($rs=ect_fetch_assoc($result)){
						if(!is_null($rs['thecnt'])) $newstocknotify=$rs['thecnt'];
					}
					ect_free_result($result);
				}
				$newlogevents=0;
				if(@$_SESSION['loginid']==0){
					$sSQL='SELECT COUNT(*) AS thecnt FROM auditlog WHERE eventSuccess=0';
					$result=ect_query($sSQL) or ect_error();
					if($rs=ect_fetch_assoc($result)){
						if(! is_null($rs['thecnt'])) $newlogevents=$rs['thecnt'];
					}
					ect_free_result($result);
				}
				print $neworders . '&' . $newratings . '&' . $newaccounts . '&' . $newmaillist . '&' . $newaffiliate . '&' . $newgiftcert . '&' . $newstocknotify . '&' . $newlogevents;

				$sSQL='SELECT statID,statPrivate FROM orderstatus';
				$result=ect_query($sSQL) or ect_error();
				while($rs=ect_fetch_assoc($result)){
					$allstatus[$rs['statID']]=$rs['statPrivate'];
				}
				ect_free_result($result);
				$sSQL='SELECT ordID,ordName,ordLastName,ordShipName,ordShipLastName,ordReferer,ordDate,ordAddress,ordCity,ordState,ordTotal,ordAddInfo,ordStatus FROM orders WHERE ordStatus>1 ORDER BY ordID DESC LIMIT 0,20';
				$result=ect_query($sSQL) or ect_error();
				if(ect_num_rows($result)>0){
					while($rs=ect_fetch_assoc($result)){
						print '&'.$rs['ordID'].'|';
						print jsurlencode(jsenc(trim_($rs['ordName']." ".$rs['ordLastName']))).'|';
						if(trim_($rs['ordShipName'])!='' && strtolower($rs['ordShipName'])!=strtolower($rs['ordName']))
							print jsurlencode(jsenc(trim_($rs['ordShipName']." ".$rs['ordShipLastName'])));
						print '|'.jsurlencode(jsenc(date('D j M H:i', strtotime($rs['ordDate'])))).'|'.jsurlencode(jsenc($allstatus[$rs['ordStatus']])).'|'.jsurlencode(jsenc(FormatEuroCurrency($rs['ordTotal'])));
					}
				}
				ect_free_result($result);
				
				ect_query("UPDATE devicenotifications SET dnLastUpdated='" . date('Y-m-d H:i:s', time()+($dateadjust*60*60)) . "' WHERE dnID='".escape_string($newdeviceid)."'") or ect_error();
			}
		}
	}
}elseif(getget('action')=='screlated'){
	$isupsell=getpost("isupsell")=="true" && @$GLOBALS['softcartupsell']!='';
	if($isupsell && @$GLOBALS['softcartupsellheader']!='') $GLOBALS['softcartrelatedheader']=$GLOBALS['softcartupsellheader'];
	if($isupsell)
		$screlatedlayout='productimage,productname,price,description,upsellbuttons';
	elseif(@$screlatedlayout=='')
		$screlatedlayout='productimage,productid,productname,price,description';
	$customlayoutarray=explode(',',strtolower(strreplace(' ','',$screlatedlayout)));
	$WSP='';
	get_wholesaleprice_sql();
	$sSQL='SELECT pId,pSKU,pSection,'.getlangid('pName',1).','.$WSP.'pPrice,pStaticPage,'.getaltlang('pStaticURL',8388608).',pDateAdded,pExemptions,pOrder,pTax,pStockByOpts,pNumRatings,pTotRating,'.getlangid('pDescription',2)." FROM products INNER JOIN relatedprods ON products.pId=relatedprods.rpRelProdID WHERE " . (@$GLOBALS['ectsiteid']!='' ? 'pSiteID='.$GLOBALS['ectsiteid'].' AND ' : '') . "pDisplay<>0 AND rpProdID='".escape_string(getpost('prodid'))."'";
	if(@$GLOBALS['relatedproductsbothways']) $sSQL.=' UNION SELECT pId,pSKU,pSection,'.getlangid('pName',1).','.$WSP.'pPrice,pStaticPage,'.getaltlang('pStaticURL',8388608).',pDateAdded,pExemptions,pOrder,pTax,pStockByOpts,pNumRatings,pTotRating,'.getlangid('pDescription',2)." FROM products INNER JOIN relatedprods ON products.pId=relatedprods.rpProdID WHERE " . (@$GLOBALS['ectsiteid']!='' ? 'pSiteID='.$GLOBALS['ectsiteid'].' AND ' : '') . "pDisplay<>0 AND rpRelProdID='".escape_string(getpost('prodid'))."'";
	if($isupsell)
		$sSQL='SELECT pId,pSKU,pSection,'.getlangid('pName',1).','.$WSP.'pPrice,pStaticPage,'.getaltlang('pStaticURL',8388608).',pDateAdded,pExemptions,pOrder,pTax,pStockByOpts,pNumRatings,pTotRating,'.getlangid('pDescription',2)." FROM products WHERE pID='" . escape_string($GLOBALS['softcartupsell']) . "'";
	elseif(@$GGLOBALS['screlateduserecommended'])
		$sSQL='SELECT pId,pSKU,pSection,'.getlangid('pName',1).','.$WSP.'pPrice,pStaticPage,'.getaltlang('pStaticURL',8388608).',pDateAdded,pExemptions,pOrder,pTax,pStockByOpts,pNumRatings,pTotRating,'.getlangid('pDescription',2)." FROM products WHERE " . (@$GLOBALS['ectsiteid']!='' ? 'pSiteID='.$GLOBALS['ectsiteid'].' AND ' : '') . "pDisplay<>0 AND pRecommend<>0";
	if(@$sSortBy!='') $sSQL.=' ORDER BY ' . $sSortBy . (@$isdesc?' DESC':'');
	$result=ect_query($sSQL) or ect_error();
	if(ect_num_rows($result)>0){
		if(@$GLOBALS['softcartrelatedheader']!='') print '<h1 class="sc' . ($isupsell?"u":"r") . 'header">' . @$GLOBALS['softcartrelatedheader'] . '</h1>';
		while($rs=ect_fetch_assoc($result)){
			$rpsmallimage='';
			$sSQL="SELECT imageSrc,imageType FROM productimages WHERE imageProduct='" . escape_string($rs['pId']) . "' AND (imageType=0 OR imageType=1) AND imageNumber=0 ORDER BY imageType";
			$result2=ect_query($sSQL) or ect_error();
			if($rs2=ect_fetch_assoc($result2)) $rpsmallimage=$rs2['imageSrc'];
			ect_free_result($result2);
			$thedetailslink=getdetailsurl($rs['pId'],$rs['pStaticPage'],$rs[getlangid('pName',1)],trim_($rs['pStaticURL']),'','');
			$startlink='<a class="ectlink" href="'.htmlspecials($thedetailslink).'">';
			$endlink='</a>';
			if(@$GLOBALS['perproducttaxrate'] && ! is_null($rs['pTax'])) $thetax=$rs['pTax']; else $thetax=$countryTaxRate;
			if(strpos($screlatedlayout,'price')!==FALSE){
				$sSQL="SELECT poOptionGroup,optType,optFlags,optTxtMaxLen,optAcceptChars,0 AS isDepOpt FROM prodoptions INNER JOIN optiongroup ON optiongroup.optGrpID=prodoptions.poOptionGroup WHERE poProdID='".$rs['pId']."' AND NOT (poProdID='".$giftcertificateid."' OR poProdID='".$donationid."') ORDER BY poID";
				$result2=ect_query($sSQL) or ect_error();
				if(ect_num_rows($result2)>0){
					$prodoptions=[];
					for($rowcounter=0;$rowcounter<ect_num_rows($result2);$rowcounter++){
						$prodoptions[$rowcounter]=ect_fetch_assoc($result2);
					}
				}else
					$prodoptions='';
				ect_free_result($result2);
			}
			print '<div class="sc' . ($isupsell?"u":"r") . 'product">';
			foreach($customlayoutarray as $layoutoption){
				if($layoutoption=='productimage'){
					print '<div class="scrimage">' . ($rpsmallimage!=''?$startlink . '<img class="scrimage" src="' . $rpsmallimage . '" style="border:0" alt="'.strreplace('"','&quot;',strip_tags($rs[getlangid('pName',1)])).'" />' . $endlink:'') . "</div>\n";
				}elseif($layoutoption=='productname'){
					print '<div class="scrprodname">' . $startlink . $rs[getlangid('pName',1)] . $endlink . "</div>\n";
				}elseif($layoutoption=='productid'){
					print '<div class="scrprodid">' . $rs['pId'] . "</div>\n";
				}elseif($layoutoption=='upsellbuttons'){
					print '<div class="scrupsellbuttons"><button type="button" class="ectbutton" onclick="document.location=\'' . $thedetailslink . '\'">View Product Details!</button> &nbsp; <button type="button" class="ectbutton" onclick="document.location=\'cart' . $extension . '\'">Decline &amp Checkout</button> </div>' . "\n";
				}elseif($layoutoption=='price'){
					$totprice=$rs['pPrice'];
					if(is_array($prodoptions)){
						$totprice+=getoptionspricediff($thetax);
					}
					print '<div class="scrprodprice">';
						print ($totprice==0 && @$pricezeromessage!='' ? $pricezeromessage : FormatEuroCurrency(@$GLOBALS['showtaxinclusive']===2 && ($rs['pExemptions'] & 2)!=2 ? $totprice+($totprice*$thetax/100.0) : $totprice));
						if(@$GLOBALS['showtaxinclusive']==1 && ($rs['pExemptions'] & 2)!=2 && $totprice>0) printf(' <span class="inctax scrinctax">' . $ssIncTax . '</span>',FormatEuroCurrency($totprice+($totprice*$thetax/100.0)));
					print "</div>\n";
				}elseif($layoutoption=='description'){
					print '<div class="scrproddescription">' . $rs[getlangid('pDescription',2)] . "</div>\n";
				}elseif($layoutoption=='reviewstars'){
					if($rs['pNumRatings']>0) print showproductreviews(2,'scrating'); else print @$GLOBALS['softcartnoratings'];
				}else
					print 'UNKNOWN LAYOUT OPTION:'.$layoutoption.'<br />';
			}
			print '</div>';
		}
	}
	ect_free_result($result);
}elseif(getget('action')=='execppsale'){
	if(is_numeric(getget('ordid'))&&getpost('paymentID')!=''){
		if(getpayprovdetx(27,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
			$ordID=getget('ordid');
			$transactionsuccess=FALSE;
			$errormsg="Sorry, there has been an error. Please try the checkout process again.";
			$sSQL="SELECT ordID,ordStatus,ordAuthStatus,ordShipType,ordTransID FROM orders WHERE ordID='" . escape_string($ordID) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if($rs['ordAuthStatus']=="MODWARNOPEN" || $rs['ordShipType']=="MODWARNOPEN")
					$errormsg=strip_tags($GLOBALS['xxMoWnRC']);
				elseif($rs['ordStatus']>=3)
					$errormsg="This transaction has already been processed.";
				elseif($rs['ordTransID']!=getpost("paymentID"))
					$errormsg="The attempt to process this payment was interrupted, possibly by having a second payment window open. Please start the checkout process again. You have not been charged for this transaction.";
				else
					$transactionsuccess=TRUE;
			}
			ect_free_result($result);
			if(!$transactionsuccess)
				print '{"ecterror":' . json_encode($errormsg) . '}';
			else{
				if($access_token=paypalaccesstoken($data1,$data2,$demomode,$data6,$errormsg)){
					$requestxx='{}';
					$seller_nonce=uniqid(date('Ymd'),TRUE).uniqid('',TRUE).uniqid('',TRUE);
					$seller_nonce=strreplace('.','_',$seller_nonce);
					$xmlfnheaders=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token,"PayPal-Request-Id: " . $seller_nonce);
					if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/checkout/orders/' . getpost('paymentID') . ($ppmethod==1?'/authorize':'/capture'),$requestxx,$jres,'',$errormsg,FALSE)){
						$jsarray=json_decode($jres);
						$tid=@$jsarray->{'id'};
						$authsuccess=FALSE;
						$authstatus='FAILED';
						if($ppmethod==1){
							$tid=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'authorizations'}[0]->{'id'};
							$authstatus=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'authorizations'}[0]->{'status'};
							$authsuccess=($authstatus=='CREATED'||$authstatus=='PENDING')&&$tid!='';
							$ordavs=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'authorizations'}[0]->{'processor_response'}->{'avs_code'};
							$ordcvv=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'authorizations'}[0]->{'processor_response'}->{'cvv_code'};
							if($ordavs==''){
								$ordavs=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'authorizations'}[0]->{'seller_protection'}->{'status'};
								$ordavs=substr_($ordavs,0,1);
							}
						}else{
							$tid=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'captures'}[0]->{'id'};
							$authstatus=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'captures'}[0]->{'status'};
							$authsuccess=($authstatus=='COMPLETED'||$authstatus=='PENDING')&&$tid!='';
							$ordavs=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'captures'}[0]->{'processor_response'}->{'avs_code'};
							$ordcvv=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'captures'}[0]->{'processor_response'}->{'cvv_code'};
							if($ordavs==''){
								$ordavs=trim_(@$jsarray->{'purchase_units'}[0]->{'payments'}->{'captures'}[0]->{'seller_protection'}->{'status'});
								$ordavs=substr_($ordavs,0,1);
							}
						}
						if($authsuccess){
							$sSQL="SELECT ordID FROM orders WHERE ordID='" . escape_string($ordID) . "' AND ordStatus<3 AND ordTransID='" . escape_string(getpost('paymentID')) . "'";
							$result=ect_query($sSQL) or ect_error();
							if($rs=ect_fetch_assoc($result)){
								if($authstatus=='PENDING')
									$pendingreason='Pending: Check Manually';
								else
									$pendingreason=($ppmethod==1?'Pending: Capture':'');
								$sSQL="UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string($ordID) . "'";
								ect_query($sSQL) or ect_error();
								$sSQL="UPDATE orders SET ordStatus=3,ordAuthNumber='" . escape_string(substr_($tid,0,48)) . "',ordAuthStatus='" . escape_string($pendingreason) . "',ordTransSession='',ordPrivateStatus='',ordAVS='" . escape_string($ordavs) . "',ordCVV='" . escape_string($ordcvv) . "' WHERE ordPayProvider=27 AND ordID='" . escape_string($ordID) . "'";
								ect_query($sSQL) or ect_error();
								do_order_success($ordID,$emailAddr,$sendEmail,FALSE,TRUE,TRUE,TRUE);
								print '{"ectsuccess":"true"}';
							}else
								print '{"ecterror":' . json_encode($jres) . '}';
							ect_free_result($result);
						}else{
							$pvterrtxt=$jres;
							$pvterrdsc=@$jsarray->{'details'}[0]->{'description'};
							if($pvterrdsc==''){
								$pvterrdsc=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'authorizations'}[0]->{'processor_response'}->{'response_code'};
								if($pvterrdsc!='') $pvterrdsc="Processor Response: " . $pvterrdsc;
							}
							if($pvterrdsc==''){
								$pvterrdsc=@$jsarray->{'purchase_units'}[0]->{'payments'}->{'captures'}[0]->{'processor_response'}->{'response_code'};
								if($pvterrdsc!='') $pvterrdsc="Processor Response: " . $pvterrdsc;
							}
							if($pvterrdsc!='') $pvterrtxt=$pvterrdsc;
							$sSQL="UPDATE orders SET ordPrivateStatus='" . escape_string(substr_($pvterrtxt,0,2048)) . "' WHERE ordPayProvider=27 AND ordID='" . escape_string($ordID) . "' AND ordStatus<3";
							ect_query($sSQL) or ect_error();
							print '{"ectsuccess":"false"}';
						}
					}else{
						print '{"ecterror":' . json_encode($jres) . '}';
					}
				}
			}
		}
	}elseif(getget('ordid')=='express'){
		print '{"ectsuccess":"true"}';
	}
}elseif(getget('action')=='createppsale'){
	$success=TRUE;
	$newcheck=hash('sha256',getpost('clid').getpost('sess').$GLOBALS['adminSecret'].getget('ordid').'PPCO');
	if(! (getget('ordid')=='express' || is_numeric(getget('ordid')))){
		$errormsg='Order id not numeric';
		$success=FALSE;
	}elseif(getpayprovdetx(27,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)&&$newcheck==getpost('check')){
		$cart_summary='';
		$methodname='CAPTURE';
		$alldigital=TRUE;
		if($ppmethod==1) $methodname='AUTHORIZE';
		$items='"items":[';
		$itemstotal=0;
		$sSQL="SELECT cartID,cartProdID,cartOrigProdID,cartProdName,cartProdPrice,cartQuantity,pWeight,pShipping,pShipping2,pExemptions,pTax,pDownload FROM cart LEFT JOIN products ON cart.cartProdID=products.pID WHERE cartCompleted=0 AND " . (getget('ordid')=='express' ? (getpost('clid')!='' ? "cartClientID='" . escape_string(getpost('clid')) . "'" : "cartSessionID='" . escape_string(getpost('sess')) . "'") : "cartOrderID='" . escape_string(getget('ordid')) . "'");
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			$item_category='PHYSICAL_GOODS';
			//if(trim_($rs['pDownload'])!='')$item_category='DIGITAL_GOODS';
			if($item_category=='PHYSICAL_GOODS') $alldigital=FALSE;
			$item_name=$rs['cartProdName'];
			$cartprodprice=$rs['cartProdPrice'];
			$sSQL="SELECT coOptGroup,coCartOption,coPriceDiff FROM cartoptions WHERE coCartID='" . escape_string($rs['cartID']) . "'";
			$result2=ect_query($sSQL) or ect_error();
			while($rs2=ect_fetch_assoc($result2)){
				$cartprodprice+=$rs2['coPriceDiff'];
				if($rs2['coCartOption']!='') $item_name.=' : ' . $rs2['coCartOption'];
			}
			if(is_null($rs['pExemptions'])){
				if($rs['cartProdID']==$giftcertificateid || $rs['cartProdID']==$donationid) $rs['pExemptions']=15;
				if($rs['cartProdID']==$giftwrappingid) $rs['pExemptions']=12;
			}
			if(@$GLOBALS['showtaxinclusive']===3 && $GLOBALS['countryTaxRate']>0 && ($rs['pExemptions'] & 2)!=2){
				$taxamount=round($cartprodprice / ((100+$GLOBALS['countryTaxRate'])/$GLOBALS['countryTaxRate']),2);
				$cartprodprice-=$taxamount;
			}
			$cart_summary.=$item_name.' ';
			$items.='{"name":' . json_encode(substr_($item_name,0,127)) . ',"unit_amount":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($cartprodprice,2,'.','') . '"},"quantity":"' . $rs['cartQuantity'] . '","category":"' . $item_category . '"},';
			$itemstotal+=$cartprodprice*$rs['cartQuantity'];
		}
		ect_free_result($result);
		$items=rtrim($items,',').']';
		if(getget('ordid')=='express'){
			$taxtotal=getpost('esttaxes');
			$handlingtotal=getpost('esthandling');
			$discounttotal=getpost('estdiscounts');
			$shippingtotal=getpost('estshipping');
			if($itemstotal>0 && is_numeric($taxtotal) && is_numeric($handlingtotal) && is_numeric($discounttotal) && is_numeric($shippingtotal)){
				$grandtotal=($itemstotal+$taxtotal+$handlingtotal+$shippingtotal)-$discounttotal;
				$requestxx='{
					"intent":"' . $methodname . '",
					"payment_source":{},
					"purchase_units":[
						{
						  "reference_id":"' . getget('ordid') . '",
						  "amount":{
							"currency_code":"' . $GLOBALS['countryCurrency'] . '",
							"value":"' . number_format($grandtotal,2,'.','') . '",
							"breakdown":{
								"item_total":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($itemstotal,2,'.','') . '"},
								"tax_total":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($taxtotal,2,'.','') . '"},
								"handling":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($handlingtotal,2,'.','') . '"},
								"discount":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($discounttotal,2,'.','') . '"},
								"shipping":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($shippingtotal,2,'.','') . '"}
							}
						  },
						  ' . $items . '
						}
					],
					"payment_source":{
						"paypal":{
							"experience_context":{' . ($alldigital?'"shipping_preference":"NO_SHIPPING",':'') . '
							"user_action":"CONTINUE",
							"return_url":"' . $storeurlssl . 'thanks' . $GLOBALS['extension'] . '?action=termpp&ordid=express",
							"cancel_url":"' . $storeurlssl . 'cart' . $GLOBALS['extension'] . '"}
						}
					}
				}';
			}else{
				$errormsg="Invalid Express Order";
				$success=FALSE;
			}
		}elseif(is_numeric(getget('ordid'))){
			$grandtotal=0;
			$sSQL="SELECT ordEmail,ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordZip,ordCountry,ordPhone,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordTotal,ordHandling,ordDiscount,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipZip,ordShipPhone,ordShipCountry FROM orders WHERE ordPayProvider=27 AND ordStatus<3 AND ordID='".escape_string(getget('ordid'))."'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$hasshipaddress=(trim_($rs['ordShipAddress'])!='');
				$grandtotal=($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'];
				$ordname=$rs['ordName'];
				$ordlastname=$rs['ordLastName'];
				$ordaddress=$rs['ordAddress'];
				$ordaddress2=$rs['ordAddress2'];
				$ordstate=$rs['ordState'];
				$ordcity=$rs['ordCity'];
				$ordzip=$rs['ordZip'];
				$ordcountry=$rs['ordCountry'];
				$ordphone=$rs['ordPhone'];
				$ordername=trim_($ordname.' '.$ordlastname);
				splitname($ordername,$first_name,$last_name);
				$taxtotal=$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax'];
				$shippingtotal=$rs['ordShipping'];
				$handlingtotal=$rs['ordHandling'];
				$discounttotal=$rs['ordDiscount'];
				if($itemstotal!=$rs['ordTotal']&&@$GLOBALS['showtaxinclusive']===3){
					$items='"items":[{"name":' . json_encode(substr_(trim_($cart_summary),0,127)) . ',"unit_amount":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($rs['ordTotal'],2,'.','') . '"},"quantity":"1","category":"PHYSICAL_GOODS"},';
					$items=rtrim($items,',').']';
				}
				$itemstotal=$rs['ordTotal'];
				$sSQL="SELECT countryCode FROM countries WHERE countryName='" . escape_string($ordcountry) . "' OR countryName2='" . escape_string($ordcountry) . "' OR countryName3='" . escape_string($ordcountry) . "'";
				$result2=ect_query($sSQL) or ect_error();
				if($rs2=ect_fetch_assoc($result2))
					$countrycode=$rs2['countryCode'];
				ect_free_result($result2);
				if($countrycode=='US' || $countrycode=='CA'){
					$sSQL="SELECT stateAbbrev FROM states WHERE (stateCountryID=1 OR stateCountryID=2) AND stateName='" . escape_string($ordstate) . "' OR stateName2='" . escape_string($ordstate) . "' OR stateName3='" . escape_string($ordstate) . "' OR stateAbbrev='" . escape_string($ordstate) . "'";
					$result2=ect_query($sSQL) or ect_error();
					if($rs2=ect_fetch_assoc($result2)) $ordstate=$rs2['stateAbbrev'];
					ect_free_result($result2);
				}
				$ordshipname=$hasshipaddress ? $rs['ordShipName'] : $rs['ordName'];
				$ordshiplastname=$hasshipaddress ? $rs['ordShipLastName'] : $rs['ordLastName'];
				$ordshipaddress=$hasshipaddress ? $rs['ordShipAddress'] : $rs['ordAddress'];
				$ordshipaddress2=$hasshipaddress ? $rs['ordShipAddress2'] : $rs['ordAddress2'];
				$ordshipstate=$hasshipaddress ? $rs['ordShipState'] : $rs['ordState'];
				$ordshipcity=$hasshipaddress ? $rs['ordShipCity'] : $rs['ordCity'];
				$ordshipzip=$hasshipaddress ? $rs['ordShipZip'] : $rs['ordZip'];
				$ordshipcountry=$hasshipaddress ? $rs['ordShipCountry'] : $rs['ordCountry'];
				$ordshipphone=$hasshipaddress ? $rs['ordShipPhone'] : $rs['ordPhone'];
				$shipcountrycode=$countrycode;
				if($hasshipaddress){
					$sSQL="SELECT countryCode FROM countries WHERE countryName='" . escape_string($ordshipcountry) . "' OR countryName2='" . escape_string($ordshipcountry) . "' OR countryName3='" . escape_string($ordshipcountry) . "'";
					$result2=ect_query($sSQL) or ect_error();
					if($rs2=ect_fetch_assoc($result2))
						$shipcountrycode=$rs2['countryCode'];
					ect_free_result($result2);
					if($shipcountrycode=='US' || $shipcountrycode=='CA'){
						$sSQL="SELECT stateAbbrev FROM states WHERE (stateCountryID=1 OR stateCountryID=2) AND stateName='" . escape_string($ordshipstate) . "' OR stateName2='" . escape_string($ordshipstate) . "' OR stateName3='" . escape_string($ordshipstate) . "' OR stateAbbrev='" . escape_string($ordshipstate) . "'";
						$result2=ect_query($sSQL) or ect_error();
						if($rs2=ect_fetch_assoc($result2)) $ordshipstate=$rs2['stateAbbrev'];
						ect_free_result($result2);
					}
				}
				$phone_number=preg_replace("/[^0-9]/",'',$ordphone);
				$requestxx='{
					"intent":"' . $methodname . '",
					"payment_source":{
						"paypal":{
							"email_address":' . json_encode($rs['ordEmail']) . ',
							"name":{"given_name":' . json_encode($first_name) . ',"surname":' . json_encode($last_name) . '},' .
							(strlen($phone_number)>5 && strlen($phone_number)<12 ? '"phone":{"phone_type":"MOBILE","phone_number":{"national_number":' . json_encode($phone_number) . '}},' : '') . '
							"experience_context":{"shipping_preference":"SET_PROVIDED_ADDRESS"},
							"address":{
								"address_line_1":' . json_encode($rs['ordAddress']) . ',
								"address_line_2":' . json_encode($rs['ordAddress2']) . ',
								"admin_area_1":' . json_encode($ordstate) . ',
								"admin_area_2":' . json_encode($rs['ordCity']) . ',
								"postal_code":' . json_encode($rs['ordZip']) . ',
								"country_code":' . json_encode($countrycode) . '
							}
						}
					},
					"redirect_urls":{
						"return_url":"' . $storeurlssl . 'cart' . $GLOBALS['extension'] . '",
						"cancel_url":"' . $storeurlssl . 'cart' . $GLOBALS['extension'] . '"
					},
					"purchase_units":[
						{
						  "reference_id":"' . getget('ordid') . '",
						  "custom_id":"' . getget('ordid') . '",
						  "amount":{
							"currency_code":"' . $GLOBALS['countryCurrency'] . '",
							"value":"' . number_format($grandtotal,2,'.','') . '",
							"breakdown":{
								"item_total":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($itemstotal,2,'.','') . '"},
								"tax_total":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($taxtotal,2,'.','') . '"},
								"handling":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($handlingtotal,2,'.','') . '"},
								"discount":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($discounttotal,2,'.','') . '"},
								"shipping":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format($shippingtotal,2,'.','') . '"}
							}
						  },
						  "shipping":{
							"type":"SHIPPING",
							"name":{"full_name":' . json_encode(trim_($ordshipname . ' ' . $ordshiplastname)) . '},
							"address":{
								"address_line_1":' . json_encode($ordshipaddress) . ',
								"address_line_2":' . json_encode($ordshipaddress2) . ',
								"admin_area_1":' . json_encode($ordshipstate) . ',
								"admin_area_2":' . json_encode($ordshipcity) . ',
								"postal_code":' . json_encode($ordshipzip) . ',
								"country_code":' . json_encode($shipcountrycode) . '
							}
						  },' . $items . '}]}';
			}else{
				$errormsg='Order not found';
				$success=FALSE;
			}
			ect_free_result($result);
		}else{
			$errormsg='Invalid order id';
			$success=FALSE;
		}
		if($success){
			if($access_token=paypalaccesstoken($data1,$data2,$demomode,$data6,$errormsg)){
				$seller_nonce=uniqid(date('Ymd'),TRUE).uniqid('',TRUE).uniqid('',TRUE);
				$seller_nonce=strreplace('.','_',$seller_nonce);
				$xmlfnheaders=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token,"PayPal-Request-Id: " . $seller_nonce);
				callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/checkout/orders',$requestxx,$jres,'',$errormsg,FALSE);
				$jsarray=json_decode($jres);
				$id=@$jsarray->{'id'};
				if($id!=''){
					if(getget('ordid')!='express'){
						$sSQL="UPDATE orders SET ordTransID='" . escape_string($id) . "',ordTransSession='' WHERE ordID='" . escape_string(getget('ordid')) . "'";
						ect_query($sSQL) or ect_error();
					}
					print $jres;
				}else{
					$errormsg=$jres;
					$success=FALSE;
				}
			}else{
				$errormsg='No access token returned: ' . $errormsg;
				$success=FALSE;
			}
		}
		if(!$success){
			print '{"ecterror":' . json_encode($errormsg) . '}';
		}
	}else{
		$success=FALSE;
		$errormsg="Invalid hash check";
		print '{"ecterror":' . json_encode("Invalid hash check. Please refresh page and try again.") . '}';
	}
	if($success==FALSE && is_numeric(getget("ordid"))){
		$sSQL="UPDATE orders SET ordPrivateStatus='" . escape_string(substr_($errormsg,0,2048)) . "' WHERE ordPayProvider=27 AND ordID='" . escape_string(getget("ordid")) . "' AND ordStatus<3";
		ect_query($sSQL) or ect_error();
	}
}elseif(getget('action')=='termsandconditions'){
	print '<div class="termsandconds">';
		print '<div class="tncclose no-print scclose" role="img" onclick="return closetandc()" title="' . htmlspecials($GLOBALS['xxClsWin']) . '"></div>';
		print '<div id="ecttermsandconds" class="termsandcondsinner" style="background-color:#FFF">';
		$sSQL="SELECT contentData FROM contentregions WHERE contentName='termsandconditions'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $hascontentid=TRUE; else $hascontentid=FALSE;
		ect_free_result($result);
		if($hascontentid)
			print $rs['contentData'];
		else
			print '<div style="margin:100px;text-align:center">You can create a terms and conditions page by going to the Admin Content Regions page and clicking &quot;New Content Region&quot; and creating a new content region with &quot;termsandconditions&quot; as the Region Name.</div>';
		print '</div>';
		print '<div class="termsandcondsbutton" style="text-align:center;padding:20px">';
			print '<input type="button" class="ectbutton no-print" value="' . htmlspecials($GLOBALS['xxTncYes']) . '" style="margin:20px" onclick="document.getElementById(\'ecttnccheckbox\').checked=true;closetandc();" />';
			print '<input type="button" class="ectbutton no-print" value="' . htmlspecials($GLOBALS['xxTncPrn']) . '" style="margin:20px" onclick="doprintterms()" />';
			print '<input type="button" class="ectbutton no-print" value="' . htmlspecials($GLOBALS['xxTncNo']) . '" style="margin:20px" onclick="document.getElementById(\'ecttnccheckbox\').checked=false;closetandc()" />';
		print '</div>';
	print '</div>';
}elseif(getget('action')=='shipcarrierupdate'&&is_numeric(getget('updfield'))){
	$sSQL="UPDATE orders SET ordShipCarrier='" . escape_string(getget('updfield')) . "' WHERE ordID='" . escape_string(getget('ordid')) . "'";
	ect_query($sSQL) or ect_error();
	print 'SUCCESS:shipcarrier';
}elseif(getget('action')=='tracknumupdate'){
	$sSQL="UPDATE orders SET ordTrackNum='" . escape_string(getget('updfield')) . "' WHERE ordID='" . escape_string(getget('ordid')) . "'";
	ect_query($sSQL) or ect_error();
	print 'SUCCESS:ordTrackNum';
}elseif(getget('action')=='invoiceupdate'){
	$sSQL="UPDATE orders SET ordInvoice='" . escape_string(getget('updfield')) . "' WHERE ordID='" . escape_string(getget('ordid')) . "'";
	ect_query($sSQL) or ect_error();
	print 'SUCCESS:ordInvoice';
}elseif(getget('action')=='logoutaccount'){
	$thesessionid=getsessionid();
	$_SESSION['clientID']=NULL; unset($_SESSION['clientID']);
	$_SESSION['clientUser']=NULL; unset($_SESSION['clientUser']);
	$_SESSION['clientActions']=NULL; unset($_SESSION['clientActions']);
	$_SESSION['clientLoginLevel']=NULL; unset($_SESSION['clientLoginLevel']);
	$_SESSION['clientPercentDiscount']=NULL; unset($_SESSION['clientPercentDiscount']);
	$sSQL="DELETE FROM tmplogin WHERE tmploginid='" . escape_string($thesessionid) . "'";
	ect_query($sSQL) or ect_error();
	setacookie('WRITECLL','',-7);
	setacookie('WRITECLP','',-7);
	print 'DONELOGOUT';
}elseif(getget('action')=='contactus'){
	if(@$multiemfblockmessage=='') $multiemfblockmessage="I'm sorry. We are experiencing temporary difficulties at the moment. Please try again later.";
	$loginsuccess=TRUE;
	$service=getpost('service');
	$afcaction=7;
	if($service=='emailfriend')$afcaction=8;
	if($service=='askquestion')$afcaction=9;
	if(recaptchaenabled(2)) $loginsuccess=checkrecaptcha($loginerror);
	if($loginsuccess){
		$loginerror=$GLOBALS['xxEmExi'];
		ect_query("DELETE FROM ajaxfloodcontrol WHERE afcAction=".$afcaction." AND afcDate<'" . date('Y-m-d H:i:s',time()-(30)) . "'") or ect_error();
		$sSQL="SELECT afcID FROM ajaxfloodcontrol WHERE afcAction=".$afcaction." AND (afcIP='" . escape_string($REMOTE_ADDR) . "' OR afcSession='" . escape_string(session_id()) . "')";
		$result=ect_query($sSQL) or ect_error();
		$dofloodcontrol=ect_num_rows($result)>0;
		ect_free_result($result);
	}
	if(!$loginsuccess)
		print "ERROR=" . strip_tags($loginerror);
	elseif($dofloodcontrol){
		$loginsuccess=FALSE;
		print 'ERROR=' . $GLOBALS['xxCoUsFC'];
	}elseif(checkemfuserblock()){
		$loginsuccess=FALSE;
		print 'ERROR=' . $multiemfblockmessage;
	}else{
		$toemail=$emailAddr;
		$yourname=strip_tags(getpost('nm'));
		$youremail=strip_tags(getpost('ye'));
		$yourcomments=strip_tags(getpost('yc'));
		if($GLOBALS['htmlemails']) $yourcomments=strreplace(array("\r","\n"),array('',"\r\n<br>"),$yourcomments);
		$theprodid=strip_tags(getpost('pid'));
		$replyto=$youremail;
		$subject=@$contactussubject==''?'Contact Us':strreplace(array('%name%','%pid%'),array($yourname,$theprodid),$contactussubject);
		$emlmessage='Name: ' . $yourname . $emlNl;
		$produrl='';
		if($service=='emailfriend'){
			if(@$GLOBALS['useemailfriend']){
				if(@$emailfriendsubject!='')
					$subject=strreplace(array('%name%','%pid%'),array($yourname,$theprodid),$emailfriendsubject);
				else
					$subject=$yourname . $xxEFRec;
				$toemail=strip_tags(getpost('fe'));
				$emlmessage=$xxEFYF1 . $yourname . ' (' . $youremail . ')' . $xxEFYF2;
				if($yourcomments!=''){
					$emlmessage.=$xxEFYF3 . $emlNl;
					$emlmessage.=$yourcomments . $emlNl;
				}else
					$emlmessage.='.' . $emlNl;
				if($theprodid!=''){
					$sSQL='SELECT pID,'.getaltlang('pName',1).',pStaticPage,'.getaltlang('pStaticURL',8388608)." FROM products WHERE pID='" . escape_string($theprodid) . "'";
					$result=ect_query($sSQL) or ect_error();
					if($rs=ect_fetch_assoc($result)) $produrl=getdetailsurl($rs['pID'],$rs['pStaticPage'],$rs['pName'],$rs['pStaticURL'],'','');
					ect_free_result($result);
				}
				if(@$htmlemails){
					$storeLink=$storeurl;
					if($theprodid!='') $storeLink.=$produrl;
					$emlmessage.=$emlNl . '<a href="' . $storeLink . '">' . $storeLink . '</a>';
				}else{
					$emlmessage.=$emlNl . $storeurl;
					if($theprodid!='') $emlmessage.=$produrl;
				}
			}else{
				$loginsuccess=FALSE;
				print 'ERROR=The Email Friend service is disabled.';
			}
		}elseif($service=='askquestion'){
			if(@$GLOBALS['useaskaquestion']){
				if(@$askaquestionsubject!='')
					$subject=strreplace(array('%name%','%pid%'),array($yourname,$theprodid),$askaquestionsubject);
				else
					$subject=$xxAskQue . ': ' . $yourname . ' about ' . $theprodid;
				$emlmessage.='PID: ' . $theprodid . $emlNl;
				if($theprodid!=''){
					$sSQL='SELECT pID,'.getaltlang('pName',1).',pStaticPage,'.getaltlang('pStaticURL',8388608)." FROM products WHERE pID='" . escape_string($theprodid) . "'";
					$result=ect_query($sSQL) or ect_error();
					if($rs=ect_fetch_assoc($result)){
						$produrl=getdetailsurl($rs['pID'],$rs['pStaticPage'],$rs['pName'],$rs['pStaticURL'],'','');
						$emlmessage.='Product: ' . $rs['pName'] . $emlNl;
					}
					ect_free_result($result);
				}
				if(@$htmlemails){
					$storeLink=$storeurl . $produrl;
					$emlmessage.='<a href="' . $storeLink . '">' . $storeLink . '</a>' . $emlNl;
				}else
					$emlmessage.=$storeurl . $produrl . $emlNl;
				for($index=1;$index<=9;$index++){
					eval('$askquestionparam=@$askquestionparam'.$index.';');
					if($askquestionparam!=''){
						$emlmessage.=$askquestionparam . ' : ' . strip_tags(getpost('aqex'.$index)) . $emlNl;
					}
				}
				$emlmessage.=$emlNl . $yourcomments;
			}else{
				$loginsuccess=FALSE;
				print 'ERROR=The Ask a Question service is disabled.';
			}
		}else{
			$service='contactus';
			if(@$GLOBALS['contactusemail']!='') $toemail=$GLOBALS['contactusemail'];
			if(@$GLOBALS['usecontactus']){
				for($index=1;$index<=9;$index++){
					eval('$contactusparam=@$contactusparam'.$index.';');
					if($contactusparam!=''){
						$emlmessage.=$contactusparam . ' : ' . strip_tags(getpost('aqex'.$index)) . $emlNl;
					}
				}
				$emlmessage.=$emlNl . $yourcomments;
			}else{
				$loginsuccess=FALSE;
				print 'ERROR=The Contact Us service is disabled.';
			}
		}
		if($loginsuccess){
			dosendemail($toemail,$emailAddr,$replyto,$subject,$emlmessage);
			print 'SUCCESS:'.$service;
		}
		$sSQL="INSERT INTO ajaxfloodcontrol (afcAction,afcIP,afcSession,afcDate) VALUES (".$afcaction.",'" . escape_string($REMOTE_ADDR) . "','" . escape_string(session_id()) . "','" . date('Y-m-d H:i:s') . "')";
		ect_query($sSQL) or ect_error();
	}
}elseif(getget('action')=='loginaccount'||getget('action')=='createaccount'){
	$loginsuccess=FALSE;
	$thesessionid=getsessionid();
	$theordersessionsql=getordersessionsql();
	if(getget('action')=='loginaccount'){
		$afcaction=@$_SERVER['HTTPS']=='on' || @$_SERVER['SERVER_PORT']=='443'?2:1;
		ect_query("DELETE FROM ajaxfloodcontrol WHERE afcAction=".$afcaction." AND afcDate<'" . date('Y-m-d H:i:s',time()-5) . "'") or ect_error();
		$sSQL="SELECT afcID FROM ajaxfloodcontrol WHERE afcAction=".$afcaction." AND (afcIP='" . escape_string($REMOTE_ADDR) . "' OR afcSession='" . escape_string(session_id()) . "')";
		$result=ect_query($sSQL) or ect_error();
		$dofloodcontrol=ect_num_rows($result)>0;
		ect_free_result($result);
		if($dofloodcontrol)
			print 'ERROR=1<div>'.$GLOBALS['xxFloCon'].'. '.$GLOBALS['xxMuWaLo'].'</div><div>'.$GLOBALS['xxPlTrAg'].' <span id="fclitspan">'.$GLOBALS['xxInSecs'].'</span>.</div>';
		elseif(getget('lc')=='' || getget('lc')!=hash('sha256',$GLOBALS['adminSecret'] . 'ect admin login' . session_id()))
			print 'ERROR=3Hash check failed.';
		else{
			$clientEmail=cleanupemail(getpost('email'));
			$clientPW=dohashpw(getpost('pw'));
			$sSQL="SELECT clID,clUserName,clActions,clLoginLevel,clPercentDiscount,avalaraentityuse FROM customerlogin WHERE (clEmail<>'' AND clEmail='".escape_string($clientEmail)."' AND clPW='".escape_string($clientPW)."') OR (clEmail='' AND clUserName='".escape_string($clientEmail)."' AND clPW='".escape_string($clientPW)."')";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$_SESSION['clientID']=$rs['clID'];
				$_SESSION['clientPW']=$clientPW;
				$_SESSION['clientUser']=$rs['clUserName'];
				$_SESSION['clientActions']=$rs['clActions'];
				$_SESSION['clientLoginLevel']=$rs['clLoginLevel'];
				$_SESSION['clientPercentDiscount']=(100.0-(float)$rs['clPercentDiscount'])/100.0;
				$_SESSION['avalaraentityuse']=$rs['avalaraentityuse'];
				setacookie('WRITECLL',$clientEmail,getpost('licook')=='ON'?365:0);
				setacookie('WRITECLP',$clientPW,getpost('licook')=='ON'?365:0);
				print 'SUCCESS:'.$rs['clLoginLevel'];
				$loginsuccess=TRUE;
			}else
				print 'ERROR=2' . $GLOBALS['xxNoLogD'];
			$sSQL="INSERT INTO ajaxfloodcontrol (afcAction,afcIP,afcSession,afcDate) VALUES (".$afcaction.",'" . escape_string($REMOTE_ADDR) . "','" . escape_string(session_id()) . "','" . date('Y-m-d H:i:s') . "')";
			ect_query($sSQL) or ect_error();
		}
	}elseif(getget('action')=='createaccount'){
		$loginsuccess=TRUE;
		if(recaptchaenabled(8)) $loginsuccess=checkrecaptcha($loginerror);
		if($loginsuccess){
			$loginerror=$GLOBALS['xxEmExi'];
			ect_query("DELETE FROM ajaxfloodcontrol WHERE afcAction=0 AND afcDate<'" . date('Y-m-d H:i:s',time()-(60*30)) . "'") or ect_error();
			$sSQL="SELECT afcID FROM ajaxfloodcontrol WHERE afcAction=0 AND (afcIP='" . escape_string($REMOTE_ADDR) . "' OR afcSession='" . escape_string(session_id()) . "')";
			$result=ect_query($sSQL) or ect_error();
			$dofloodcontrol=ect_num_rows($result)>0;
			ect_free_result($result);
		}
		if(!$loginsuccess)
			print "ERROR=" . $loginerror;
		elseif($dofloodcontrol){
			$loginsuccess=FALSE;
			print 'ERROR=Flood Control. You have already created an account in the last 30 minutes';
		}else{
			$clientemail=getpost('email');
			$clientpw=dohashpw(getpost('pw'));
			if(!@$GLOBALS['allowclientregistration']){
				$loginsuccess=FALSE;
				$loginerror='Client Registration is Disabled';
			}else{
				if(getpost('fullname')!='' && $clientpw!='' && strpos($clientemail,'@')!==FALSE && strpos($clientemail,'.')!==FALSE){
					$sSQL="SELECT clID FROM customerlogin WHERE clEmail='".escape_string($clientemail)."'";
					$result=ect_query($sSQL) or ect_error();
					$loginsuccess=ect_num_rows($result)==0;
					ect_free_result($result);
					if(!$loginsuccess) $loginerror=$GLOBALS['xxEmExi'];
				}else{
					$loginsuccess=FALSE;
					$loginerror='Invalid login details';
				}
			}
			if($loginsuccess && (strpos(getpost('fullname'),'<')!==FALSE || strpos(getpost('fullname'),'>')!==FALSE)){
				$loginsuccess=FALSE;
				$loginerror='Invalid Characters in Login Name';
			}
			if($loginsuccess){
				if(@$GLOBALS['defaultcustomerloginlevel']=='') $GLOBALS['defaultcustomerloginlevel']=0;
				if(@$GLOBALS['defaultcustomerloginactions']=='') $GLOBALS['defaultcustomerloginactions']=0;
				if(@$GLOBALS['defaultcustomerlogindiscount']=='') $GLOBALS['defaultcustomerlogindiscount']=0; else $GLOBALS['defaultcustomerloginactions']=(((int)$GLOBALS['defaultcustomerloginactions'])|16);
				$sSQL="INSERT INTO customerlogin (clUserName,clEmail,clPw,clDateCreated,clLoginLevel,clActions,clPercentDiscount,clientCustom1,clientCustom2) VALUES ('" . escape_string(getpost('fullname')) . "','" . escape_string($clientemail) . "','" . escape_string($clientpw) . "','" . date('Y-m-d', time()+($dateadjust*60*60)) . "','".$GLOBALS['defaultcustomerloginlevel']."','".$GLOBALS['defaultcustomerloginactions']."','".$GLOBALS['defaultcustomerlogindiscount']."','" . escape_string(strip_tags(getpost('extraclientfield1'))) . "','" . escape_string(strip_tags(getpost('extraclientfield2'))) . "')";
				ect_query($sSQL) or ect_error();
				$_SESSION['clientID']=ect_insert_id();
				$_SESSION['clientPW']=$clientpw;
				$_SESSION['clientUser']=getpost('fullname');
				$_SESSION['clientActions']=$defaultcustomerloginactions;
				$_SESSION['clientLoginLevel']=$defaultcustomerloginlevel;
				$_SESSION['clientPercentDiscount']=(100.0-(float)$defaultcustomerlogindiscount)/100.0;
				if(getpost('allowemail')=='1') addtomailinglist($clientemail,getpost('fullname'));
				if(($GLOBALS['adminEmailConfirm'] & 4)==4){
					$emailmessage='There has been a new customer signup at your store: ' . $emlNl .
						'Email: ' . $clientemail . $emlNl .
						'Name: ' . getpost('fullname') . $emlNl;
					dosendemail($emailAddr,$emailAddr,$clientemail,'New Customer Signup',$emailmessage);
				}
				$sSQL="INSERT INTO ajaxfloodcontrol (afcAction,afcIP,afcSession,afcDate) VALUES (0,'" . escape_string($REMOTE_ADDR) . "','" . escape_string(session_id()) . "','" . date('Y-m-d H:i:s') . "')";
				ect_query($sSQL) or ect_error();
				print 'SUCCESS';
			}else
				print 'ERROR=' . $loginerror;
		}
	}
	if($loginsuccess){
		get_wholesaleprice_sql();
		$sSQL="SELECT ordID FROM orders WHERE ordStatus>1 AND ordAuthNumber='' AND " . $theordersessionsql;
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			release_stock($rs['ordID']);
			ect_query("UPDATE cart SET cartSessionID='".escape_string(getsessionid())."',cartClientID='" . (@$_SESSION['clientID']!='' ? escape_string($_SESSION['clientID']) : 0) . "' WHERE cartCompleted=0 AND cartOrderID=" . $rs['ordID']) or ect_error();
			ect_query("UPDATE orders SET ordAuthStatus='MODWARNOPEN',ordShipType='MODWARNOPEN'" . (@$_SESSION['clientID']!='' ? ",ordClientID='" . escape_string($_SESSION['clientID']) . "'" : '') . " WHERE ordID=" . $rs['ordID']) or ect_error();
		}
		ect_free_result($result);
		$sSQL="SELECT cartID,cartProdID FROM cart WHERE cartCompleted=0 AND cartClientID='" . escape_string($_SESSION['clientID']) . "'";
		$result=ect_query($sSQL) or ect_error();
		while($cartarr=ect_fetch_assoc($result)){
			$hasoptions=TRUE;
			$sSQL="SELECT cartID,cartQuantity FROM cart WHERE cartClientID=0 AND cartCompleted=0 AND cartSessionID='" . escape_string($thesessionid) . "' AND cartProdID='" . escape_string($cartarr['cartProdID']) . "'";
			$result2=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result2)){ $thecartid=$rs['cartID']; $thequant=$rs['cartQuantity']; } else $thecartid='';
			if($thecartid!=''){ // check options
				$optarr1cnt=0; $optarr2cnt=0;
				$sSQL="SELECT coOptID,coCartOption FROM cartoptions WHERE coCartID=" . $cartarr['cartID'];
				$result3=ect_query($sSQL) or ect_error();
				while($rs2=ect_fetch_assoc($result3))
					$optarr1[$optarr1cnt++]=$rs2;
				$sSQL="SELECT coOptID,coCartOption FROM cartoptions WHERE coCartID=" . $thecartid;
				$result3=ect_query($sSQL) or ect_error();
				while($rs2=ect_fetch_assoc($result3))
					$optarr2[$optarr2cnt++]=$rs2;
				if($optarr1cnt!=$optarr2cnt) $hasoptions=FALSE;
				if($optarr1cnt>0 && $optarr2cnt>0){
					if($hasoptions){
						for($index2=0; $index2 < $optarr1cnt; $index2++){
							$hasthisoption=FALSE;
							for($index3=0; $index3 < $optarr2cnt; $index3++){
								if($optarr1[$index2]['coOptID']==$optarr2[$index3]['coOptID'] && $optarr1[$index2]['coCartOption']==$optarr2[$index3]['coCartOption']) $hasthisoption=TRUE;
							}
							if(! $hasthisoption) $hasoptions=FALSE;
						}
					}
				}
			}
			if($thecartid!='' && $hasoptions){
				ect_query("DELETE FROM cart WHERE cartID='".escape_string($cartarr['cartID'])."'") or ect_error();
				ect_query("DELETE FROM cartoptions WHERE coCartID='".escape_string($cartarr['cartID'])."'") or ect_error();
			}
		}
		ect_free_result($result);
		$sSQL="UPDATE cart SET cartClientID='" . escape_string($_SESSION['clientID']) . "' WHERE cartClientID=0 AND cartCompleted=0 AND cartSessionID='" . escape_string($thesessionid) . "'";
		ect_query($sSQL) or ect_error();
		$sSQL="UPDATE cart SET cartSessionID='" . escape_string($thesessionid) . "' WHERE cartCompleted=0 AND cartClientID='" . escape_string($_SESSION['clientID']) . "'";
		ect_query($sSQL) or ect_error();
		$sSQL="SELECT cartID,cartProdID,cartProdPrice,pID,".$WSP."pPrice FROM cart LEFT JOIN products ON cart.cartProdId=products.pID WHERE cartClientID='" . escape_string($_SESSION['clientID']) . "' AND cartCompleted=0 AND cartProdID<>'".$giftcertificateid."' AND cartProdID<>'".$donationid."' AND cartProdID<>'".$giftwrappingid."'";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			if(is_null($rs['pID'])){
				$cartchanged=TRUE;
				ect_query("DELETE FROM cart WHERE cartID='".escape_string($rs['cartID'])."'") or ect_error();
				ect_query("DELETE FROM cartoptions WHERE coCartID='".escape_string($rs['cartID'])."'") or ect_error();
			}else{
				$newprice=checkpricebreaks($rs['cartProdID'],$rs['pPrice']);
				if($rs['cartProdPrice']!=$newprice) $cartchanged=TRUE; // recalculate wholesale price plus quant discounts
				$sSQL='SELECT coID,coPriceDiff,'.$OWSP."optPriceDiff,optFlags FROM cart INNER JOIN cartoptions ON cart.cartID=cartoptions.coCartID INNER JOIN options ON cartoptions.coOptID=options.optID INNER JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE optType IN (-4,-2,-1,1,2,4) AND cartID='".$rs['cartID']."'";
				$result2=ect_query($sSQL) or ect_error();
				while($rs2=ect_fetch_assoc($result2)){
					$sSQL='UPDATE cartoptions SET coPriceDiff='.(($rs2['optFlags']&1)==0 ? $rs2['optPriceDiff'] : round(($rs2['optPriceDiff'] * $newprice)/100.0, 2))." WHERE coID='".$rs2['coID']."'";
					ect_query($sSQL) or ect_error();
				}
				ect_free_result($result2);
			}
		}
		ect_free_result($result);
		unset($_SESSION['xsshipping']);unset($_SESSION['discounts']);unset($_SESSION['xscountrytax']);unset($_SESSION['tofreeshipquant']);unset($_SESSION['tofreeshipamount']);
	}
}elseif(getget('action')=='dashboard'){
	$dropshipper='';
	if(@$_SESSION['loginid']!=0 && @$_SESSION['dropshipper']!='' && @$_SESSION['dropshipper']!=0) $dropshipper=@$_SESSION['dropshipper'];
	$neworders=0;
	$sSQL="SELECT COUNT(*) AS thecnt FROM orders" . ($dropshipper!=''?' INNER JOIN cart ON orders.ordID=cart.cartOrderID INNER JOIN products ON cart.cartProdID=products.pID':'') . " WHERE " . ($dropshipper!=''?'pDropShip=' . $dropshipper . " AND ":'') . "ordStatus>=2 AND ordDate>='".date('Y-m-d', time()+($dateadjust*60*60))."'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		if(!is_null($rs['thecnt'])) $neworders=$rs['thecnt'];
	}
	$newratings=0;
	$sSQL='SELECT COUNT(*) AS thecnt FROM ratings WHERE rtApproved=0';
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		if(!is_null($rs['thecnt'])) $newratings=$rs['thecnt'];
	}
	$newaccounts=0;
	$sSQL="SELECT COUNT(*) AS thecnt FROM customerlogin WHERE clDateCreated>'".date('Y-m-d', time()-(60*60*24))."'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		if(!is_null($rs['thecnt'])) $newaccounts=$rs['thecnt'];
	}
	$newmaillist=0;
	$sSQL="SELECT COUNT(*) AS thecnt FROM mailinglist WHERE mlConfirmDate>'".date('Y-m-d', time()-(60*60*24))."'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		if(!is_null($rs['thecnt'])) $newmaillist=$rs['thecnt'];
	}
	$newaffiliate=0;
	$sSQL="SELECT COUNT(*) AS thecnt FROM affiliates WHERE affilDate>'".date('Y-m-d', time()-(60*60*24))."'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		if(!is_null($rs['thecnt'])) $newaffiliate=$rs['thecnt'];
	}

	$newgiftcert=0;
	$sSQL="SELECT COUNT(*) AS thecnt FROM giftcertificate INNER JOIN orders ON giftcertificate.gcOrderID=orders.ordID WHERE gcOrderID<>0 AND ordStatus>=2 AND gcDateCreated>'".date('Y-m-d', time()-(60*60*24))."'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		if(!is_null($rs['thecnt'])) $newgiftcert=$rs['thecnt'];
	}
	ect_free_result($result);
	$newstocknotify=0;
	if(@$notifybackinstock){
		$sSQL="SELECT COUNT(*) AS thecnt FROM notifyinstock";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			if(!is_null($rs['thecnt'])) $newstocknotify=$rs['thecnt'];
		}
		ect_free_result($result);
	}
	$newlogevents=0;
	if(@$_SESSION['loginid']==0){
		$sSQL='SELECT COUNT(*) AS thecnt FROM auditlog WHERE eventSuccess=0';
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			if(! is_null($rs['thecnt'])) $newlogevents=$rs['thecnt'];
		}
		ect_free_result($result);
	}
	print $neworders . '&' . $newratings . '&' . $newaccounts . '&' . $newmaillist . '&' . $newaffiliate . '&' . $newgiftcert . '&' . $newstocknotify . '&' . $newlogevents;
	$sSQL='SELECT statID,statPrivate FROM orderstatus';
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$allstatus[$rs['statID']]=$rs['statPrivate'];
	}
	ect_free_result($result);
	$sSQL='SELECT ' . ($dropshipper!=''?"DISTINCT ":'') . 'ordID,ordName,ordLastName,ordShipName,ordShipLastName,ordReferer,ordDate,ordAddress,ordCity,ordState,ordTotal,ordAddInfo,ordStatus FROM orders ' . ($dropshipper!=''?" INNER JOIN cart ON orders.ordID=cart.cartOrderID INNER JOIN products ON cart.cartProdID=products.pID":'') . ' WHERE ' . ($dropshipper!=''?'pDropShip=' . $dropshipper . ' AND ':'') . 'ordStatus>1 ORDER BY ordID DESC LIMIT 0,5';
	$result=ect_query($sSQL) or ect_error();
	if(ect_num_rows($result)>0){
		while($rs=ect_fetch_assoc($result)){
			print '&'.$rs['ordID'].'|';
			print jsurlencode(jsenc(trim_($rs['ordName']." ".$rs['ordLastName']))).'|';
			if(trim_($rs['ordShipName'])!='' && strtolower($rs['ordShipName'])!=strtolower($rs['ordName']))
				print jsurlencode(jsenc(trim_($rs['ordShipName']." ".$rs['ordShipLastName'])));
			print '|'.jsurlencode(jsenc(date('D j M h:ia', strtotime($rs['ordDate'])))).'|'.jsurlencode(jsenc($allstatus[$rs['ordStatus']])).'|'.jsurlencode(jsenc(FormatEuroCurrency($rs['ordTotal'])));
		}
	}
}elseif(@$_GET['action']=='ipnarrived' && getget('oid')!=''){
	$oid=getget('oid');
	if(getget('sid')!='')
		$sSQL="SELECT ordID FROM orders WHERE ordTransID<>'' AND ordTransSession='".escape_string(getget('sid'))."' AND ordID='".escape_string($oid)."'";
	elseif(is_numeric($oid))
		$sSQL="SELECT ordID FROM orders WHERE ordAuthNumber<>'no ipn' AND ordID='".escape_string($oid)."'";
	else
		$sSQL="SELECT ordID FROM orders WHERE ordDate>='" . date('Y-m-d',time()-(36*60*60)) . "' AND ordAuthNumber='" . escape_string($oid) . "'";
	$result=ect_query($sSQL) or ect_error();
	if(ect_num_rows($result)>0) print '1'; else print '0';
	ect_free_result($result);
}elseif(@$_GET['action']=='notifystock'){
	$oid=@$_GET['oid'];
	$nsemail=getget('email');
	$legalrequest=TRUE;
	if(! is_numeric($oid)) $legalrequest=FALSE;
	if(!filter_var($nsemail, FILTER_VALIDATE_EMAIL)) $legalrequest=FALSE;
	if($legalrequest){
		$sSQL="SELECT pId FROM products WHERE pId='".escape_string(@$_GET['pid'])."'";
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)==0) $legalrequest=FALSE;
		ect_free_result($result);
	}
	if($legalrequest){
		$sSQL="SELECT pId FROM products WHERE pId='".escape_string(@$_GET['tpid'])."'";
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)==0) $legalrequest=FALSE;
		ect_free_result($result);
	}
	if($legalrequest){
		ect_query("DELETE FROM notifyinstock WHERE nsDate<'".date('Y-m-d', time() - (60*60*24*365))."'") or ect_error();
		ect_query("DELETE FROM notifyinstock WHERE nsTriggerProdID='".escape_string(@$_GET['tpid'])."' AND nsEmail='".escape_string($nsemail)."'") or ect_error();
		ect_query("INSERT INTO notifyinstock (nsProdID,nsTriggerProdID,nsOptID,nsEmail,nsDate) VALUES ('".escape_string(@$_GET['pid'])."','".escape_string(@$_GET['tpid'])."',".$oid.",'".escape_string($nsemail)."','".date('Y-m-d')."')") or ect_error();
	}
	print 'SUCCESS';
}elseif(@$_GET['action']=='clord'){
	if(@$closeorderimmediately){
		$thesessionid=@$_SESSION['sessionid'];		
		$sSQL="SELECT ordID FROM orders WHERE ordStatus>1 AND ordAuthNumber='' AND " . getordersessionsql();
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $orderid=$rs['ordID']; else $orderid='';
		ect_free_result($result);
		if($orderid!=''){
			ect_query("UPDATE cart SET cartCompleted=2 WHERE cartCompleted=0 AND cartOrderID=".$orderid) or ect_error();
			ect_query("UPDATE orders SET ordAuthNumber='CHECK MANUALLY' WHERE ordID=".$orderid) or ect_error();
		}
	}
}elseif(@$_GET['action']=='centinel2'&&is_numeric(@$_POST['MD'])){
	$sSQL="SELECT ordPrivateStatus FROM orders WHERE ordID='" . escape_string($_POST['MD']) . "' AND ordStatus=2";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)) $cardinalstring=$rs['ordPrivateStatus']; else $cardinalstring='';
	ect_free_result($result);
	$cardinalMDvars=explode('&',$cardinalstring);
	$cardinal_transaction=@$cardinalMDvars[0];
	$cardinal_orderid=@$cardinalMDvars[1];
	$cardinal_method=@$cardinalMDvars[2];
	$cardinal_ordernum=@$cardinalMDvars[3];
	$cardinal_sessionid=@$cardinalMDvars[4];
	$signatureverify=$ErrorDesc=$PAResStatus=$Cavv=$EciFlag=$Xid='';
	$sXML='<CardinalMPI>' .
		addtag('Version','1.7') .
		addtag('MsgType','cmpi_authenticate') .
		addtag('ProcessorId',$cardinalprocessor) .
		addtag('MerchantId',$cardinalmerchant) .
		addtag('TransactionPwd',$cardinalpwd) .
		addtag('TransactionType','C') .
		addtag('TransactionId',$cardinal_transaction) .
		addtag('OrderId',$cardinal_orderid) .
		addtag('PAResPayload',@$_POST['PaRes']) . '</CardinalMPI>';
	$theurl='https://'.($cardinal_method=='7'||$cardinal_method=='18'?'paypal':'centinel400').'.cardinalcommerce.com/maps/txns.asp';
	if(@$cardinaltestmode) $theurl='https://centineltest.cardinalcommerce.com/maps/txns.asp';
	if(@$cardinalurl!='') $theurl=$cardinalurl;
	if(callcurlfunction($theurl, 'cmpi_msg=' . urlencode($sXML), $res, '', $errormsg, 12)){
		$xmlDoc=new vrXMLDoc($res);
		$nodeList=$xmlDoc->nodeList->childNodes[0];
		for($i=0; $i < $nodeList->length; $i++){
			if($nodeList->nodeName[$i]=='PAResStatus') $PAResStatus=$nodeList->nodeValue[$i];
			if($nodeList->nodeName[$i]=='SignatureVerification') $signatureverify=$nodeList->nodeValue[$i];
			if($nodeList->nodeName[$i]=='Cavv') $Cavv=$nodeList->nodeValue[$i];
			if($nodeList->nodeName[$i]=='EciFlag') $EciFlag=$nodeList->nodeValue[$i];
			if($nodeList->nodeName[$i]=='Xid') $Xid=$nodeList->nodeValue[$i];
			if($nodeList->nodeName[$i]=='ErrorDesc') $ErrorDesc=$nodeList->nodeValue[$i];
		}
	}
	if(@$signatureverify!='Y' || $PAResStatus=='N') $centinelok='N'; else $centinelok='Y';
	$sSQL="UPDATE orders SET ordPrivateStatus='centinelresult&" . escape_string(urlencode($centinelok).'&'.urlencode($PAResStatus).'&'.urlencode($ErrorDesc).'&'.urlencode($Cavv).'&'.urlencode($EciFlag).'&'.urlencode($Xid)) . "' WHERE ordID='" . escape_string($_POST['MD']) . "'";
	ect_query($sSQL) or ect_error();
?>
<html><head>
<script>
function onLoadHandler(){document.frmLaunchACS.submit();}
</script>
</head>
<body onload="onLoadHandler();">
<center>
<form name="frmLaunchACS" method="post" action="<?php print $storeurlssl?>cart<?php print $GLOBALS['extension']?>" target="_top">
<noscript>
<p>&nbsp;</p>
<h1>Processing your transaction</h1>
<?php print '<p>'.$GLOBALS['xxNoJS'].'</p><p>'.$GLOBALS['xxMstClk'].'</p>'?><p>&nbsp;</p>
<input type="submit" value="<?php print $GLOBALS['xxSubmt']?>"></center>
</noscript>
<input type="hidden" name="mode" value="authorize" />
<input type="hidden" name="method" value="<?php print $cardinal_method?>" />
<input type="hidden" name="ordernumber" value="<?php print $cardinal_ordernum?>" />
<input type="hidden" name="sessionid" value="<?php print $cardinal_sessionid?>" />
</form></center></body></html>
<?php
}elseif(@$_GET['action']=="centinel"){
?>
<html><head>
<script>
function onLoadHandler(){document.frmLaunchACS.submit();}
</script>
</head>
<body onload="onLoadHandler();">
<center>
<form name="frmLaunchACS" method="post" action="<?php print strreplace('"', '', @$_GET['url'])?>">
<noscript>
<p>&nbsp;</p>
<h1>Processing your transaction</h1>
<?php print '<p>'.$GLOBALS['xxNoJS'].'</p><p>'.$GLOBALS['xxMstClk'].'</p>'?><p>&nbsp;</p>
<input type="submit" value="<?php print $GLOBALS['xxSubmt']?>"></center>
</noscript>
<input type="hidden" name="PaReq" value="<?php print strreplace('"', '&quot;', @$_SESSION['cardinal_pareq'])?>" />
<input type="hidden" name="TermUrl" value="<?php print $storeurlssl.'vsadmin/ajaxservice.php?action=centinel2'?>" />
<input type="hidden" name="MD" value="<?php print @$_SESSION['cardinal_ordernum']?>" />
</form></center></body></html>
<?php
}elseif(@$_GET['action']=='applycert'){
	if(@$_SESSION['lastcertapplied']!='') $lastapplied=time() - $_SESSION['lastcertapplied']; else $lastapplied=1000;
	$_SESSION['lastcertapplied']=time();
	$rgcpncode=@$_GET['cpncode'];
	if($lastapplied < 3 && @$_GET['act']!='delete'){
		print (getget('stg1')=='1'?'fail&':'').$GLOBALS['xxFldCnt'];
	}elseif($rgcpncode!=''){
		$gotcpncode=FALSE;
		if(getget('stg1')!='1') print '<div style="display:table"><div style="display:table-row">';
		if(@$_GET['act']=='delete'){
			$gotcpncode=TRUE;
			$_SESSION['giftcerts']=strreplace(trim_(strreplace("'","",$rgcpncode)) . " ", "", @$_SESSION['giftcerts']);
			$_SESSION['cpncode']=strreplace(trim_(strreplace("'","",$rgcpncode)) . " ", "", @$_SESSION['cpncode']);
			print (getget('stg1')=='1'?'success&':'').$GLOBALS['xxCpGcDl'];
		}else{
			$sSQL="SELECT gcID FROM giftcertificate WHERE gcRemaining>0 AND gcAuthorized<>0 AND gcID='" . escape_string($rgcpncode) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if(strpos(@$_SESSION['giftcerts'], $rs['gcID'] . ' ')===FALSE){
					@$_SESSION['giftcerts'].=$rs['gcID'] . ' ';
					print (getget('stg1')=='1'?'success&':'').$GLOBALS['xxGcApld'];
				}else
					print (getget('stg1')=='1'?'fail&':'').$GLOBALS['xxGcAlAp'];
				$gotcpncode=TRUE;
			}
			ect_free_result($result);
		}
		if(! $gotcpncode){
			$sSQL="SELECT cpnID,cpnNumber FROM coupons WHERE cpnIsCoupon=1 AND cpnNumAvail>0 AND cpnEndDate>='" . date('Y-m-d',time()) ."' AND cpnNumber='" . escape_string($rgcpncode) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if(is_null(@$_SESSION['cpncode']) || strpos(@$_SESSION['cpncode'], $rs['cpnNumber'] . ' ')===FALSE){
					if(trim_(@$_SESSION['cpncode'])==''){
						@$_SESSION['cpncode'].=$rs['cpnNumber'] . ' ';
						print (getget('stg1')=='1'?'success&':'').$GLOBALS['xxCpnApd'];
					}else
						print (getget('stg1')=='1'?'fail&':'').$GLOBALS['xxOnOnCp'];
				}else
					print (getget('stg1')=='1'?'fail&':'').$GLOBALS['xxCpAlAp'];
			}else
				print (getget('stg1')=='1'?'fail&':'').'<div class="ectwarning" style="display:table-cell">' . $GLOBALS['xxGCCNoF'] . '</div>';
			ect_free_result($result);
		}
		if(getget('stg1')!='1') print '</div>';
		if((@$_SESSION['giftcerts']!='' || @$_SESSION['cpncode']!='') && getget('stg1')!='1'){
			$gcarr=explode(' ', trim_(@$_SESSION['giftcerts']));
			foreach($gcarr as $key => $value){
				if($value!='') print '<div style="display:table-row"><div style="display:table-cell">' . $GLOBALS['xxAppGC'] . '</div><div style="display:table-cell">' . $value . '</div><div style="display:table-cell">(<a href="#" onclick="return removecert(\''.$value.'\')">'.$GLOBALS['xxRemove'].'</a>)</div></div>';
			}
			$cpnarr=explode(' ', trim_(@$_SESSION['cpncode']));
			foreach($cpnarr as $key => $value){
				if($value!='') print '<div style="display:table-row"><div style="display:table-cell">' . $GLOBALS['xxApdCpn'] . '</div><div style="display:table-cell">' . $value . '</div><div style="display:table-cell">(<a href="#" onclick="return removecert(\''.$value.'\')">'.$GLOBALS['xxRemove'].'</a>)</div></div>';
			}
		}
		if(getget('stg1')!='1') print '</div>';
	}
}elseif(@$_GET['action']=='checkupdates'){
	$str="?versions=true&format=PHP&plusver=".urlencode(@$_GET['storever']);
	if(! callcurlfunction('https://www.ecommercetemplates.com/updaterversions.asp'.$str,'',$sXML,'',$errormsg,FALSE)){
		$recommendedversion=$errormsg . " : " . $yyCdNoCo;
		$securityrelease='false';
		$shouldupdate='true';
		$xxhaserror='true';
	}else{
		$xmlDoc=new vrXMLDoc($sXML);
		$nodeList=$xmlDoc->nodeList->childNodes[0];
		$recommendedversion=$nodeList->getValueByTagName('recommendedversion');
		$securityrelease=($nodeList->getValueByTagName('securityrelease')=='true');
		$shouldupdate=($nodeList->getValueByTagName('shouldupdate')=='true');
		$xxhaserror='false';
		$sSQL="UPDATE admin SET updLastCheck='".date('Y-m-d')."',updRecommended='".escape_string($recommendedversion)."',updSecurity=".($securityrelease?"1":"0").",updShouldUpd=".($shouldupdate?"1":"0")." WHERE adminID=1";
		ect_query($sSQL) or ect_error();
	}
	header('Content-Type: text/xml');
	print '<?xml version="1.0"?><updaterresults><recommendedversion>'.$recommendedversion.'</recommendedversion><securityupdate>'.($securityrelease?'true':'false').'</securityupdate><shouldupdate>'.($shouldupdate?'true':'false').'</shouldupdate><haserror>'.$xxhaserror.'</haserror></updaterresults>';
}elseif(@$_GET['action']=='dazzleupd'){
	$newtrackingnum=trim_(@$_GET['trackno']);
	$iordid=@$_GET['ordid'];
	$emailstat=@$_GET['emstatus'];
	$ordstatus=@$_GET['ordstatus'];
	if(is_numeric($iordid) && $newtrackingnum!=''){
		$result=ect_query("SELECT ordStatus,ordAuthNumber,ordEmail,ordDate,".getlangid("statPublic",64).",ordStatusInfo,ordName,ordLastName,ordTrackNum,ordPayProvider,ordLang,ordClientID,loyaltyPoints,ordTotal,ordDiscount,pointsRedeemed FROM orders INNER JOIN orderstatus ON orders.ordStatus=orderstatus.statID WHERE ordID=" . $iordid) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$oldordstatus=$rs['ordStatus'];
			$ordauthno=$rs['ordAuthNumber'];
			$ordemail=$rs['ordEmail'];
			$orddate=strtotime($rs['ordDate']);
			$oldstattext=$rs[getlangid('statPublic',64)];
			$ordstatinfo=$rs['ordStatusInfo'];
			if(@$htmlemails==TRUE) $ordstatinfo=strreplace("\r\n", '<br />', $ordstatinfo);
			$ordername=trim_($rs['ordName'] . ' ' . $rs['ordLastName']);
			$trackingnum=trim_($rs['ordTrackNum']);
			$payprovider=$rs['ordPayProvider'];
			$languageid=$rs['ordLang']+1;
			$ordClientID=$rs['ordClientID'];
			$loyaltypointtotal=$rs['loyaltyPoints'];
			$ordTotal=$rs['ordTotal'];
			$ordDiscount=$rs['ordDiscount'];
			$pointsredeemed=$rs['pointsRedeemed'];
		}
		ect_free_result($result);
		
		if(strpos($trackingnum,$newtrackingnum)!==FALSE)
			$iordid=''; // Already set
		elseif($trackingnum!=''){
			ect_query("UPDATE orders SET ordTrackNum='" . escape_string($trackingnum . "," . $newtrackingnum) . "',ordStatusDate='" . date("Y-m-d H:i:s", time() + ($dateadjust*60*60)) . "' WHERE ordID=" . $iordid) or ect_error();
			$trackingnum.="," . $newtrackingnum;
		}else{
			ect_query("UPDATE orders SET ordTrackNum='" . escape_string($newtrackingnum) . "',ordStatusDate='" . date("Y-m-d H:i:s", time() + ($dateadjust*60*60)) . "' WHERE ordID=" . $iordid) or ect_error();
			$trackingnum=$newtrackingnum;
		}
		
		if($iordid!='' && $ordstatus!==''){
			if($oldordstatus != (int)$ordstatus && @$_POST['emailstat']=='1' && $ordstatus!=1){
				$result=ect_query("SELECT ".getlangid('statPublic',64).",emailstatus FROM orderstatus WHERE statID=" . $ordstatus);
				if($rs=ect_fetch_assoc($result)){
					$newstattext=$rs[getlangid('statPublic',64)];
					$emailstatus=($rs['emailstatus']!=0);
				}else
					$emailstatus=FALSE;
				ect_free_result($result);
				if(getget('noemail')=='true') $emailstatus=FALSE;

				if(($adminlangsettings & 4096)==0) $languageid=1;
				if(@$ordstatussubject[$languageid]!='') $emailsubject=$ordstatussubject[$languageid]; else $emailsubject='Order status updated';
				$ose=$ordstatusemail[$languageid];
				$timestest=0;
				for($index=0; $index<=18; $index++){
					$replaceone=TRUE;
					while($replaceone && $timestest++ < 30){
						$ose=replaceemailtxt($ose, '%statusid' . $index . '%', $index==$ordstatus ? '%ectpreserve%' : '', $replaceone);
					}
				}
				$ose=strreplace('%orderid%', $iordid, $ose);
				$ose=strreplace('%orderdate%', date($dateformatstr, $orddate) . ' ' . date('H:i', $orddate), $ose);
				$ose=strreplace('%oldstatus%', $oldstattext, $ose);
				$ose=strreplace('%newstatus%', $newstattext, $ose);
				$thetime=time() + ($dateadjust*60*60);
				$ose=strreplace('%date%', date($dateformatstr, $thetime) . ' ' . date('H:i', $thetime), $ose);
				$ose=strreplace('%ordername%', $ordername, $ose);
				$ose=replaceemailtxt($ose, '%statusinfo%', $ordstatinfo, $replaceone);
				$tracknumarr=explode(',', $trackingnum);
				foreach($tracknumarr as $key => $value){
					$ose=replaceemailtxt($ose, '%trackingnum%', $value, $replaceone);
				}
				while(strpos($ose, '%trackingnum%')!==FALSE){
					$ose=replaceemailtxt($ose, '%trackingnum%', '', $replaceone);
				}
				$reviewlinks=$norepeatlinks='';
				if(strpos($ose, '%reviewlinks%')!==FALSE){
					$sSQL="SELECT cartProdID,cartOrigProdID FROM cart WHERE cartOrderID=".$iordid;
					$result2=ect_query($sSQL) or ect_error();
					while($rs2=ect_fetch_assoc($result2)){
						if(trim_($rs2['cartOrigProdID'])!='') $cartprodid=$rs2['cartOrigProdID']; else $cartprodid=$rs2['cartProdID'];
						if(strpos($norepeatlinks,",'".$cartprodid."'")===FALSE){
							$norepeatlinks.=",'".$cartprodid."'";
							$sSQL="SELECT pID,".getlangid('pName',1).",pStaticPage,".getaltlang('pStaticURL',8388608).",pDisplay FROM products WHERE pDisplay<>0 AND pID='".escape_string($cartprodid)."'";
							$result=ect_query($sSQL) or ect_error();
							if($rs=ect_fetch_assoc($result)){
								$thelink=$storeurl . getdetailsurl($rs['pID'],$rs['pStaticPage'],$rs[getlangid('pName',1)],$rs['pStaticURL'],'review=true','');
								if(@$htmlemails==TRUE) $thelink='<a href="' . $thelink . '">' . $thelink . '</a>';
								$reviewlinks.=$thelink . $emlNl;
							}
							ect_free_result($result);
						}
					}
					ect_free_result($result2);
				}
				$ose=replaceemailtxt($ose, '%reviewlinks%', $reviewlinks, $replaceone);
				$ose=strreplace(array('%nl%','<br />'), $emlNl, $ose);
				if($emailstatus!=0) dosendemail($ordemail, $emailAddr, '', $emailsubject, $ose);
			}
			if($oldordstatus != (int)$ordstatus) ect_query("UPDATE orders SET ordStatus=" . $ordstatus . ",ordStatusDate='" . date("Y-m-d H:i:s", time() + ($dateadjust*60*60)) . "' WHERE ordID=" . $iordid) or ect_error();
		}
		print 'SUCCESS|'.@$_GET['rowid'];
	}else
		print 'ERROR';
}elseif(@$_GET['action']=='dazzle'){
	$isdazzlefile=FALSE;
	$isworldshipfile=FALSE;
	$csvcurrpos=1;
	$addressindex=-1;
	$trackingindex=-1;
	$csvfile=trim_(@$_POST['dazzletext']);
	$csvarray=preg_split('/$\R?^/m', $csvfile);
	$csvline=strtolower($csvarray[0]);
	$columnarr=explode("\t",$csvline);
	$fileseparator="\t";
	if(count($csvarray)>0){
		for($index=0; $index<count($columnarr); $index++){
			if($columnarr[$index]=='address') $addressindex=$index;
			if($columnarr[$index]=='tracking_id') $trackingindex=$index;
		}
		if($addressindex!=-1 && $trackingindex!=-1) $isdazzlefile=TRUE;
	}
	if(! $isdazzlefile){
		$columnarr=explode(',',$csvline);
		if(count($csvarray)>0){
			for($index=0; $index<count($columnarr); $index++){
				if($columnarr[$index]=='shiptocompanyorname') $addressindex=$index;
				if($columnarr[$index]=='packagetrackingnumber') $trackingindex=$index;
				if($columnarr[$index]=='shiptoemailaddress') $emailindex=$index;
			}
			if($addressindex!=-1 && $trackingindex!=-1 && $emailindex!=-1) $isworldshipfile=TRUE;
			$fileseparator=",";
		}
	}
	if($isdazzlefile || $isworldshipfile){
		for($index=1; $index<count($csvarray); $index++){
			$csvline=trim_($csvarray[$index]);
			$orderid=0;
			if($csvline!=''){
				if($columnarr=explode($fileseparator,$csvline)){
					$theaddress=trim_($columnarr[$addressindex]);
					$thetracknum=trim_(strreplace('"','',$columnarr[$trackingindex]));
					if($isworldshipfile) $theemail=trim_(strreplace('"','',$columnarr[$emailindex]));
					if(($isdazzlefile && $theaddress!='') || ($isworldshipfile && $theemail!='')){
						$addressarr=explode(',',$theaddress);
						print '==DAZZLELINE==' . $thetracknum . '==ORIGADD==' . $theaddress;
						if(is_array($addressarr) || $isworldshipfile){
							$sSQL='SELECT ordID,ordStatus,ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordZip,ordCountry FROM orders WHERE ordStatus>=3 AND';
							if($isworldshipfile){
								$sSQL.=" ordEmail='".escape_string($theemail)."' AND ordEmail<>''";
							}else{
								if(@$usefirstlastname){
									splitname($addressarr[0],$tfirstn,$tlastn);
									$sSQL.=" (((ordName='".escape_string(trim_($tfirstn))."' AND ordLastName='".escape_string(trim_($tlastn))."') OR (ordShipName='".escape_string(trim_($tfirstn))."' AND ordShipLastName='".escape_string(trim_($tlastn))."' AND (ordShipName<>'' OR ordShipLastName<>'')))";
									splitname($addressarr[1],$tfirstn,$tlastn);
									$sSQL.=" OR ((ordName='".escape_string(trim_($tfirstn))."' AND ordLastName='".escape_string(trim_($tlastn))."') OR (ordShipName='".escape_string(trim_($tfirstn))."' AND ordShipLastName='".escape_string(trim_($tlastn))."' AND (ordShipName<>'' OR ordShipLastName<>''))))";
								}else
									$sSQL.=" (ordName='".escape_string(trim_($addressarr[0]))."' OR ordName='".escape_string(trim_($addressarr[1]))."' OR ((ordShipName='".escape_string(trim_($addressarr[0]))."' OR ordShipName='".escape_string(trim_($addressarr[1]))."') AND ordShipName<>''))";
							}
							$sSQL.=' ORDER BY ordID DESC LIMIT 0,5';
							$result=ect_query($sSQL) or ect_error();
							while($rs=ect_fetch_assoc($result)){
								print '==MATCHLINE==' . $rs['ordID'] . '|' . $rs['ordStatus'] . '==FULLADD==' . trim_($rs['ordName'].' '.$rs['ordLastName']) . ', ' . $rs['ordAddress'] . ', ';
								if(trim_($rs['ordAddress2'])!='') print $rs['ordAddress2'] . ', ';
								print $rs['ordCity'] . ', ' . $rs['ordState'] . ', ' . $rs['ordZip'];
							}
							ect_free_result($result);
						}
					}
				}
			}
		}
	}else
		print 'ERRORFILEFORMAT';
}elseif(@$_GET['action']=='getlist'){
	$rc=0;
	if(@$maxadminlookup=='') $maxadminlookup=50;
	if(@$_GET['listtype']!='adddets') print @$_GET['objid'].'==LISTOBJ==';
	$listtext=@$_POST['listtext'];
	if(@$_GET['listtype']=='adddets'){
		$actarr=explode('|',$listtext);
		if($actarr[0]=='0'){
			print $actarr[1] . '==LISTELM==';
			$sSQL="SELECT clID,clUserName FROM customerlogin WHERE clID=".$actarr[1];
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if(@$usefirstlastname){
					$ordName=trim_($rs['clUserName']);
					$ordLastName='';
					if(strstr($ordName,' ')){
						$namearr=explode(' ',$ordName,2);
						$ordName=$namearr[0];
						$ordLastName=$namearr[1];
					}
					print jsenc($ordName) . '==LISTELM==' . jsenc($ordLastName);
				}else
					print jsenc($rs['clUserName']) . '==LISTELM==';
			}
			ect_free_result($result);
		}elseif($actarr[0]=='1' || $actarr[0]=='2'){
			if($actarr[0]=='1')
				$sSQL="SELECT addCustID,addName,addLastName,addAddress,addAddress2,addCity,addState,addZip,addCountry,addPhone,addExtra1,addExtra2 FROM address WHERE addID=".$actarr[1];
			else
				$sSQL="SELECT 0 AS addCustID,ordName AS addName,ordLastName AS addLastName,ordAddress AS addAddress,ordAddress2 AS addAddress2,ordCity AS addCity,ordState AS addState,ordZip AS addZip,ordCountry AS addCountry,ordPhone AS addPhone,ordExtra1 AS addExtra1,ordExtra2 AS addExtra2 FROM orders WHERE ordID=".$actarr[1];
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				print $rs['addCustID'] . '==LISTELM==' . jsenc($rs['addName']) . '==LISTELM==' . jsenc($rs['addLastName']) . '==LISTELM==';
				print jsenc($rs['addAddress']) . '==LISTELM==' . jsenc($rs['addAddress2']) . '==LISTELM==';
				print jsenc($rs['addCity']) . '==LISTELM==' . jsenc($rs['addState']) . '==LISTELM==';
				print jsenc($rs['addZip']) . '==LISTELM==' . jsenc($rs['addCountry']) . '==LISTELM==';
				print jsenc($rs['addPhone']) . '==LISTELM==';
				print jsenc($rs['addExtra1']) . '==LISTELM==' . jsenc($rs['addExtra2']);
			}
			ect_free_result($result);
		}
	}elseif(@$_GET['listtype']=='email'){
		// noaddress=0 addresstable=1 orderstable=2 | clid or addid or ordid
		$gotresults=FALSE;
		if($rc<10){
			$sSQL="SELECT clID,clEmail,clUserName,clActions,clPercentDiscount,addName,addLastName,addAddress,addAddress2,addID,addCity,addState,addZip,addCountry FROM customerlogin INNER JOIN address ON customerlogin.clID=address.addCustID WHERE ";
			$sSQL.="clEmail LIKE '".escape_string($listtext)."%' ";
			$sSQL.='ORDER BY clEmail LIMIT 0,20';
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0 && $gotresults){ print jsenc('----------------').'==LISTELM=='.jsenc('----------------').'==LISTOBJ=='; $gotresults=FALSE;}
			while($rs=ect_fetch_assoc($result)){
				$theaddress=$rs['clEmail'].' / '.trim_($rs['addName'].' '.$rs['addLastName']).' - '.$rs['addAddress'];
				if(trim_($rs['addAddress2'])!='') $theaddress.= ', ' . $rs['addAddress2'];
				$theaddress.= ', ' . $rs['addState'] . ', ' . $rs['addZip'] . ', ' . $rs['addCountry'];
				$thecode='1|'.$rs['addID'];
				print jsenc($rs['clEmail']).'==LISTELM=='.jsenc($theaddress).'==LISTELM=='.$thecode."==LISTELM==".(($rs['clActions'] & 8)==8?1:0)."==LISTELM==".(($rs['clActions'] & 16)==16?1:0)."==LISTELM==".$rs['clPercentDiscount'].'==LISTOBJ==';
				$rc++;
				$gotresults=TRUE;
			}
			ect_free_result($result);
		}
		if($rc<20){
			$sSQL="SELECT DISTINCT MAX(ordID) AS ordID,ordEmail,ordName,ordLastName,ordAddress,ordAddress2,ordState,ordZip,ordCountry FROM orders WHERE ";
			$sSQL.="ordEmail LIKE '".escape_string($listtext)."%' ";
			$sSQL.='GROUP BY ordEmail,ordName,ordLastName,ordAddress,ordAddress2,ordState,ordZip,ordCountry ORDER BY ordEmail LIMIT 0,20';
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0 && $gotresults){ print jsenc('----------------').'==LISTELM=='.jsenc('----------------').'==LISTOBJ=='; $gotresults=FALSE;}
			while($rs=ect_fetch_assoc($result)){
				$theaddress=$rs['ordEmail'].' / '.trim_($rs['ordName'].' '.$rs['ordLastName']).' - '.$rs['ordAddress'];
				if(trim_($rs['ordAddress2'])!='') $theaddress.= ', ' . $rs['ordAddress2'];
				$theaddress.= ', ' . $rs['ordState'] . ', ' . $rs['ordZip'] . ', ' . $rs['ordCountry'];
				$thecode='2|'.$rs['ordID'];
				print jsenc($rs['ordEmail']).'==LISTELM=='.jsenc($theaddress).'==LISTELM=='.$thecode.'==LISTOBJ==';
				$rc++;
				$gotresults=TRUE;
			}
			ect_free_result($result);
		}
		if($rc<40){
			$sSQL='SELECT clID,clEmail,clUserName FROM customerlogin WHERE ';
			$sSQL.="clEmail LIKE '".escape_string($listtext)."%' ";
			$sSQL.='ORDER BY clEmail LIMIT 0,10';
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0 && $gotresults){ print jsenc('----------------').'==LISTELM=='.jsenc('----------------').'==LISTOBJ=='; $gotresults=FALSE;}
			while($rs=ect_fetch_assoc($result)){
				$theaddress=$rs['clEmail'].' / '.$rs['clUserName'];
				$thecode='0|'.$rs['clID'];
				print jsenc($rs['clEmail']).'==LISTELM=='.jsenc($theaddress).'==LISTELM=='.$thecode.'==LISTOBJ==';
				$rc++;
				$gotresults=TRUE;
			}
			ect_free_result($result);
		}
	}elseif(@$_GET['listtype']=='prodid' OR @$_GET['listtype']=='prodname'){
		$sSQL='SELECT pID,pName FROM products WHERE ';
		if(@$_GET['listtype']=='prodname')
			$sSQL.="pName LIKE '".escape_string($listtext)."%' ORDER BY pName";
		else
			$sSQL.="pID LIKE '".escape_string($listtext)."%' OR pSKU LIKE '".escape_string($listtext)."%' ORDER BY pID";
		$sSQL.=' LIMIT 0,'.$maxadminlookup;
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			print jsenc($rs['pID']).'==LISTELM=='.jsenc($rs['pName']).'==LISTOBJ==';
			$rc++;
		}
		ect_free_result($result);
		if($maxadminlookup-30 > $rc){
			$sSQL='SELECT pID,pName FROM products WHERE ';
			if(@$_GET['listtype']=='prodname')
				$sSQL.="pName LIKE '%".escape_string($listtext)."%' AND NOT (pName LIKE '".escape_string($listtext)."%') ORDER BY pName";
			else
				$sSQL.="pID LIKE '%".escape_string($listtext)."%' AND NOT (pID LIKE '".escape_string($listtext)."%') ORDER BY pID";
			$sSQL.=' LIMIT 0,'.$maxadminlookup;
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0 && $rc!=0) print jsenc('----------------').'==LISTELM=='.jsenc('----------------').'==LISTOBJ==';
			while($rs=ect_fetch_assoc($result)){
				print jsenc($rs['pID']).'==LISTELM=='.jsenc($rs['pName']).'==LISTOBJ==';
				$rc++;
			}
			ect_free_result($result);
		}
	}
}elseif(trim_(@$_GET['action'])=='updateoptions'){
	$WSP=''; $OWSP='';
	$byoptions=FALSE;
	$optstockjs='';
	$id=@$_GET['index'];
	$productid=@$_POST['productid'];
	if(strtolower($adminencoding)!='utf-8') $productid=utf8_decode($productid);
	$haswsp=@$_GET['wsp']=='1';
	$percdisc=@$_GET['perc'];
	if($haswsp){
		$WSP='pWholesalePrice AS ';
		$TWSP='pWholesalePrice';
		if(@$wholesaleoptionpricediff==TRUE) $OWSP='optWholesalePriceDiff AS ';
	}
	if(is_numeric($percdisc)){
		$percdisc=(100.0-(float)$percdisc)/100.0;
		$WSP=$percdisc.'*'.($haswsp?'pWholesalePrice':'pPrice').' AS ';
		$TWSP=$percdisc.'*'.($haswsp?'pWholesalePrice':'pPrice');
		$OWSP=$percdisc.'*'.($haswsp && @$wholesaleoptionpricediff?'optWholesalePriceDiff':'optPriceDiff').' AS ';
	}
	$sSQL='SELECT ' . getlangid('pName',1) . ',' . $WSP . "pPrice,pStockByOpts,pInStock,pExemptions FROM products WHERE pID='" . escape_string($productid) . "'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$prodname=$rs[getlangid('pName',1)];
		$prodprice=round($rs['pPrice'],2);
		if($rs['pStockByOpts']!=0){ $prodstock="'bo'"; $byoptions=TRUE; } else $prodstock=(is_null($rs['pInStock'])?'0':$rs['pInStock']);
		$prodexemptions=$rs['pExemptions'];
	}else{
		$prodname='Not Found: ' . $productid;
		$prodprice=0;
		$prodstock="''";
		$prodexemptions=0;
	}
	ect_free_result($result);
	$opttext='';
	$sSQL="SELECT poOptionGroup,optType,optFlags FROM prodoptions INNER JOIN optiongroup ON optiongroup.optGrpID=prodoptions.poOptionGroup WHERE poProdID='" . escape_string($productid) . "' ORDER BY poID";
	$prodoptions=ect_query($sSQL) or ect_error();
	$jstext='';
	if(ect_num_rows($prodoptions)==0){
		$opttext.='-';
	}else{
		$rowcounter=0;
		$opttext.='<div class="optionstable">';
		while($theopt=ect_fetch_assoc($prodoptions)){
			$index=0;
			$sSQL="SELECT optID," . getlangid('optName',32) . "," . getlangid('optGrpName',16) . ','.$OWSP.'optPriceDiff,optType,optFlags,optStock,optTxtCharge FROM options INNER JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE optGroup=' . $theopt['poOptionGroup'] . ' ORDER BY optID';
			$result=ect_query($sSQL) or ect_error();
			if($rs2=ect_fetch_assoc($result)){
				$opttext.='<div class="optionstablerow"><div class="optionstableleft">' . $rs2[getlangid('optGrpName',16)] . ':</div><div>';
				if(abs((int)$rs2['optType'])==3){
					$opttext.='<input type="hidden" name="optn' . $id . '_' . $rs2['optID'] . '" value="' . $rs2['optID'] . '" />';
					if($rs2['optTxtCharge']!=0) $jstext.='opttxtcharge[' . $rs2['optID'] . ']=' . $rs2['optTxtCharge'] . ';';
					$opttext.='<textarea wrap="virtual" name="voptn' . $id . '_' . $rs2['optID'] . '" id="voptn' . $id . '_' . $rs2['optID'] . '" cols="30" rows="3">';
					$opttext.=$rs2[getlangid('optName',32)] . '</textarea>';
				}else{
					$opttext.='<select class="prodoption" onchange="dorecalc(true)" name="optn' . $id . '_' . $rowcounter . '" id="optn' . $id . '_' . $rowcounter . '" size="1">';
					$opttext.='<option value="">'.$GLOBALS['xxPlsSel'].'</option>';
					do{
						$opttext.="<option value='" . $rs2['optID'] . '|' . (($rs2['optFlags'] & 1)==1 ? ($prodprice*$rs2['optPriceDiff'])/100.0 : $rs2['optPriceDiff']) . "'>" . $rs2[getlangid('optName',32)];
						if((float)($rs2['optPriceDiff']) != 0){
							$opttext.=' ';
							if((float)($rs2['optPriceDiff']) > 0) $opttext.='+';
							if(($rs2['optFlags']&1)==1)
								$opttext.=number_format(($prodprice*$rs2['optPriceDiff'])/100.0,2,'.','');
							else
								$opttext.=number_format($rs2['optPriceDiff'],2,'.','');
						}
						$opttext.="</option>\r\n";
						if($byoptions){
							$optstockjs.="if(typeof(stock['oid_".$rs2['optID']."'])==\"undefined\"){";
							$optstockjs.="stock['oid_".$rs2['optID']."']=".$rs2['optStock'].";";
							$optstockjs.='}';
						}
					} while($rs2=ect_fetch_assoc($result));
					$opttext.='</select>';
				}
				$opttext.='</div></div>';
			}
			ect_free_result($result);
			$rowcounter++;
		}
		$opttext.='</div>';
	}
	ect_free_result($prodoptions);
	$jstext.="document.getElementById('prodname".$id."').value='".strreplace("'","\\'",$prodname)."';";
	$jstext.="document.getElementById('price".$id."').value='".$prodprice."';";
	$jstext.="document.getElementById('stateexempt".$id."').value='".(($prodexemptions & 1)==1?'true':'false')."';";
	$jstext.="document.getElementById('countryexempt".$id."').value='".(($prodexemptions & 2)==2?'true':'false')."';";
	$jstext.="document.getElementById('optdiffspan".$id."').value=0;";
	$jstext.="if(typeof(stock['pid_".strreplace("'", '', $productid)."'])=='undefined'){";
	$jstext.="stock['pid_".strreplace("'", '', $productid)."']=".$prodstock.";";
	$jstext.=$optstockjs."}";
	print $id.'==LISTELM=='.jsenc($opttext).'==LISTELM=='.jsenc($jstext);
}elseif(@$_GET['processor']=='AuthNET'){
	$ordID=strreplace("'",'',@$_GET['gid']);
	$payprov=$transid='';
	$success=FALSE;
	if(is_numeric($ordID)){
		$sSQL="SELECT ordTransID,ordPayProvider FROM orders WHERE ordID='" . escape_string($ordID) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$transid=$rs['ordTransID'];
			$payprov=$rs['ordPayProvider'];
		}
		ect_free_result($result);
	}
	if(is_numeric($ordID)&&$payprov!=''&&getpayprovdetails($payprov,$data1,$data2,$data3,$demomode,$ppmethod)){
		if(@$secretword!=''){
			$data1=upsdecode($data1, $secretword);
			$data2=upsdecode($data2, $secretword);
		}
		if(@$_GET['act']=='charge')
			$anaction='priorAuthCaptureTransaction';
		elseif(@$_GET['act']=='refund')
			$anaction='refundTransaction';
		elseif(@$_GET['act']=='void')
			$anaction='voidTransaction';
		elseif(@$_GET['act']=='reauth')
			$anaction='authOnlyContinueTransaction';
		if($anaction!=''){
			$sjson='{"createTransactionRequest":{"merchantAuthentication":{"name":' . json_encode($data1) . ',"transactionKey":' . json_encode($data2) . '},
				"transactionRequest":{"transactionType":"' . $anaction . '",' . ($anaction!='voidTransaction'?'"amount":"' . $_POST['amount'] . '",':'') . '"refTransId":"' . $transid . '"}}}';
			if(!($success=callcurlfunction('https://api' . ($demomode?'test':'') . '.authorize.net/xml/v1/request.api',$sjson,$jres,'',$errormsg,FALSE)))
				print $errormsg;
		}
		if($success){
			$index=0;
			while($index<strlen($jres)&&ord($jres[$index])>127)
				$index++;
			if($index>0) $jres=substr_($jres,$index);
			$jsarray=json_decode((string)$jres);
			if($jsarray->{'messages'}->{'resultCode'}=='Ok'){
				ect_query("UPDATE orders SET ordStatus='" . escape_string(getpost('capstatus')) . "',ordStatusDate='" . date("Y-m-d H:i:s", time() + ($dateadjust*60*60)) . "' WHERE ordID='" . escape_string($ordID) . "' AND ordStatus<>'" . escape_string(getpost('capstatus')) . "'") or ect_error();
				print $jsarray->{'transactionResponse'}->{'messages'}[0]->{'description'};
			}else{
				if(($errtxt=@$jsarray->{'transactionResponse'}->{'errors'}[0]->{'errorText'})!='')
					print $errtxt.'<br />';
				print $jsarray->{'messages'}->{'message'}[0]->{'text'};
			}
		}
	}
}elseif(@$_GET['processor']=='PayPalCO'){
	if(getpayprovdetx(27,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
		$ordID=strreplace("'",'',@$_GET['gid']);
		$success=FALSE;
		$requestxx='{"intent":"CAPTURE"}';

		if(is_numeric($ordID)){
			$transid='';
			$sSQL="SELECT ordID,ordTransID,ordAuthNumber,ordTransSession,ordEmail,ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordZip,ordCountry,ordPhone,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordTotal,ordHandling,ordDiscount FROM orders WHERE ordID='" . escape_string($ordID) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$transid=$rs['ordTransID'];
				$transsession=$rs['ordTransSession'];
				$grandtotal=($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'];
				$authnumber=$rs['ordAuthNumber'];
			}
			ect_free_result($result);
			if($transid!=''&&$access_token=paypalaccesstoken($data1,$data2,$demomode,$data6,$errormsg)){
				$seller_nonce=uniqid(date('Ymd'),TRUE).uniqid('',TRUE).uniqid('',TRUE);
				$seller_nonce=strreplace('.','_',$seller_nonce);
				$xmlfnheaders=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token,"PayPal-Request-Id: " . $seller_nonce);
				if(@$_GET['act']=='charge'){
					$requestxx='{"final_capture":' . (@$_POST['additionalcapture']=='1' ? 'false' : 'true') . ',"payment_instruction":{"disbursement_mode":"INSTANT"}' . 
					(getpost('amount')!=''?',"amount":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format(getpost('amount'),2,'.','') . '"}':'') .
					'}';
					if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/payments/authorizations/' . $authnumber . '/capture',$requestxx,$res,'',$errormsg,FALSE)){
						$success=TRUE;
						$jsarray=json_decode($res);
						$tstate=@$jsarray->{'status'};
						$tmessage=@$jsarray->{'status_details'}->{'reason'};
						$transid=@$jsarray->{'id'};
						$error_name=@$jsarray->{'name'};
						if($error_name=='RESOURCE_NOT_FOUND'){
							$resultstatus='Order has already been captured';
							$xmlfnheaders=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token);
							if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/payments/captures/' . $authnumber,'',$capres,'',$errormsg,FALSE)){
								$captureresult=json_decode($capres);
								if(@$captureresult->{'status'}!='COMPLETED'&&@$captureresult->{'status'}!='PARTIALLY_REFUNDED') $resultstatus='Error capturing order';
							}
							print $resultstatus;
						}elseif($tstate=='PENDING'){
							if($tmessage=='RECEIVING_PREFERENCE_MANDATES_MANUAL_ACTION') $tmessage='Check Manually';
							ect_query("UPDATE orders SET ordAuthStatus='Pending: " . escape_string($tmessage) . "',ordStatusDate='" . date("Y-m-d H:i:s", time() + ($dateadjust*60*60)) . "' WHERE ordID='" . escape_string($ordID) . "'") or ect_error();
							print 'Check Manually';
						}elseif($tstate=='COMPLETED'){
							ect_query("UPDATE orders SET ordStatus='" . escape_string(getpost('capstatus')) . "',ordStatusDate='" . date("Y-m-d H:i:s", time() + ($dateadjust*60*60)) . "' WHERE ordID='" . escape_string($ordID) . "' AND ordStatus<>'" . escape_string(getpost('capstatus')) . "'") or ect_error();
							ect_query("UPDATE orders SET ordAuthNumber='" . escape_string($transid) . "',ordAuthStatus='' WHERE ordID='" . escape_string($ordID) . "'") or ect_error();
							print 'Capture Completed';
						}else{
							if($tmessage==''){
								$tmessage=@$jsarray->{'details'}[0]->{'description'};
							}
							print $tmessage;
						}
					}
				}elseif(@$_GET['act']=='void'){
					if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/payments/authorizations/' . $authnumber . '/void','{}',$res,'',$errormsg,FALSE)){
						$success=TRUE;
						if($http_status==204){
							ect_query("UPDATE orders SET ordStatus=0,ordStatusDate='" . date("Y-m-d H:i:s", time() + ($dateadjust*60*60)) . "' WHERE ordID='" . escape_string($ordID) . "' AND ordStatus<>0") or ect_error();
							print 'Void completed';
						}else{
							if($res!=''){
								$jsarray=json_decode($res);
								$error_name=@$jsarray->{'name'};
								$error_desc=@$jsarray->{'details'}[0]->{'description'};
								if($error_name!=''||$error_desc!='')
									print $error_name . ' : ' . $error_desc;
								else
									print 'Error trying to void transaction';
							}
						}
					}
				}elseif(@$_GET['act']=='reauth'){
					if(getpost('amount')!='')$requestxx='{"amount":{"value":' . number_format(getpost('amount'),2,'.','') . ',"currency_code":"' . $GLOBALS['countryCurrency'] . '"}}'; else $requestxx='{}';
					if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/payments/authorizations/' . $authnumber . '/reauthorize',$requestxx,$res,'',$errormsg,FALSE)){
						$success=TRUE;
						$jsarray=json_decode($res);
						$tstate=@$jsarray->{'status'};
						$error_name=@$jsarray->{'name'};
						if($error_name=='INVALID_RESOURCE_ID'){
							$resultstatus='Order has already been captured';
							$xmlfnheaders=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token);
							if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/payments/captures/' . $authnumber,'',$capres,'',$errormsg,FALSE)){
								$captureresult=json_decode($capres);
								if(@$captureresult->{'status'}!='COMPLETED'&&@$captureresult->{'status'}!='PARTIALLY_REFUNDED') $resultstatus='Error capturing order';
							}
							print $resultstatus;
						}elseif($tstate=='CREATED')
							print 'Reauthorization successful';
						else{
							$tmessage=@$jsarray->{'message'};
							print $tmessage;
						}
					}
				}elseif(@$_GET['act']=='refund'){
					if(getpost('amount')!='')$requestxx='{"amount":{"currency_code":"' . $GLOBALS['countryCurrency'] . '","value":"' . number_format(getpost('amount'),2,'.','') . '"}}'; else $requestxx='{}';
					if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/payments/captures/' . $authnumber . '/refund',$requestxx,$res,'',$errormsg,FALSE)){
						$success=TRUE;
						$refundsuccess=FALSE;
						$jsarray=json_decode($res);
						$tstate=@$jsarray->{'status'};
						$error_name=@$jsarray->{'name'};
						if($error_name=='RESOURCE_NOT_FOUND'){
							$resultstatus='Cannot refund as order has not been captured';
							$xmlfnheaders=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token,"PayPal-Request-Id: " . $seller_nonce);
							if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/payments/authorizations/' . $authnumber,'',$capres,'',$errormsg,FALSE)){
								$captureresult=json_decode($capres);
								if(@$captureresult->{'status'}!='CREATED') $resultstatus='Error refunding order';
							}
							print $resultstatus;
						}elseif($tstate=='CANCELLED')
							print 'Refund cancelled';
						elseif($tstate=='COMPLETED'){
							$refundsuccess=TRUE;
							print 'The order has been successfully refunded';
						}elseif($tstate=='FAILED')
							print 'The refund could not be processed';
						elseif($tstate=='PENDING'){
							$refundsuccess=TRUE;
							print 'The refund is pending. ';
							$tmessage=@$jsarray->{'status_details'}->{'reason'};
							print $tmessage;
						}
						if($refundsuccess){
							updateorderstatus($ordID,getpost('capstatus'),FALSE);
						}
					}
				}
				if(!$success)print $errormsg;
				//print "<br><br>res: " . $res;
			}
		}
	}
}elseif(@$_GET['processor']=='PayPal'){
	$ordID=strreplace("'",'',@$_GET['gid']);
	$sSQL="SELECT ordPayProvider,ordAuthNumber,ordTransID,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordTotal,ordHandling,ordDiscount FROM orders WHERE ordID='".escape_string($ordID)."'";
	$result=ect_query($sSQL) or ect_error();
	$rs=ect_fetch_assoc($result);
	$authcode=$rs['ordAuthNumber'];
	$transid=$rs['ordTransID'];
	$grandtotal=($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'];
	if($success=getpayprovdetails(19,$username,$password,$data3,$demomode,$ppmethod)){
		$data2arr=explode('&',$password);
		$password=urldecode(@$data2arr[0]);
		$isthreetoken=(trim_(urldecode(@$data2arr[2]))=='1');
		$signature=''; $sslcertpath='';
		if($isthreetoken){
			$signature=urldecode(@$data2arr[1]);
			if(strpos($username,'/')!==FALSE){
				$data1arr=explode('/',$username);
				if($grandtotal<12) $username=trim_($data1arr[1]); else $username=trim_($data1arr[0]);
				$data1arr=explode('/',$password);
				if($grandtotal<12 && strpos($password,'/')!==FALSE) $password=trim_($data1arr[1]); else $password=trim_($data1arr[0]);
				$data1arr=explode('/',$signature);
				if($grandtotal<12 && strpos($signature,'/')!==FALSE) $signature=trim_($data1arr[1]); else $signature=trim_($data1arr[0]);
			}
		}else
			$sslcertpath=urldecode(@$data2arr[1]);
	}
	if($demomode) $sandbox='.sandbox'; else $sandbox='';
	if(! $success){
		print 'username / pw not set for express checkout';
	}else{
		if(@$_GET['act']=='charge'){
			$sXML=ppsoapheader($username, $password, $signature) . '<soap:Body><DoCaptureReq xmlns="urn:ebay:api:PayPalAPI">' .
				'<DoCaptureRequest xmlns="urn:ebay:api:PayPalAPI">' .
					'<Version xmlns="urn:ebay:apis:eBLBaseComponents" xsi:type="xsd:string">1.0</Version>' .
					'<AuthorizationID>' . $authcode . '</AuthorizationID>' .
					'<Amount currencyID="' . $countryCurrency . '" xsi:type="cc:BasicAmountType">' . $_POST['amount'] . '</Amount>' .
					'<CompleteType>' . (@$_POST['additionalcapture']=='1' ? 'NotComplete' : 'Complete') . '</CompleteType>' .
					'<Note>' . @$_POST['comments'] . '</Note>' .
				'</DoCaptureRequest></DoCaptureReq></soap:Body></soap:Envelope>';
		}elseif(@$_GET['act']=='void'){
			$sXML=ppsoapheader($username, $password, $signature) . '<soap:Body><DoVoidReq xmlns="urn:ebay:api:PayPalAPI">' .
				'<DoVoidRequest xmlns="urn:ebay:api:PayPalAPI">' .
					'<Version xmlns="urn:ebay:apis:eBLBaseComponents" xsi:type="xsd:string">1.0</Version>' .
					'<AuthorizationID>' . $authcode . '</AuthorizationID>' .
					'<Note>' . @$_POST['comments'] . '</Note>' .
				'</DoVoidRequest></DoVoidReq></soap:Body></soap:Envelope>';
		}elseif(@$_GET['act']=='reauth'){
			$sXML=ppsoapheader($username, $password, $signature) . '<soap:Body><DoReauthorizationReq xmlns="urn:ebay:api:PayPalAPI">' .
				'<DoReauthorizationRequest xmlns="urn:ebay:api:PayPalAPI">' .
					'<Version xmlns="urn:ebay:apis:eBLBaseComponents" xsi:type="xsd:string">1.0</Version>' .
					'<AuthorizationID>' . $authcode . '</AuthorizationID>' .
					'<Amount currencyID="' . $countryCurrency . '" xsi:type="cc:BasicAmountType">' . @$_POST['amount'] . '</Amount>' .
					'<Note>' . @$_POST['comments'] . '</Note>' .
				'</DoReauthorizationRequest></DoReauthorizationReq></soap:Body></soap:Envelope>';
		}
		if(callcurlfunction('https://api' . ($isthreetoken ? '-3t' : '') . $sandbox . '.paypal.com/2.0/', $sXML, $res, $sslcertpath, $errormsg, FALSE)){
			$success=FALSE;$vsERRCODE='';$vsRESPMSG='';$vsTRANSID='';
			$xmlDoc=new vrXMLDoc($res);
			$nodeList=$xmlDoc->nodeList->childNodes[0];
			for($i=0; $i < $nodeList->length; $i++){
				if($nodeList->nodeName[$i]=="SOAP-ENV:Body"){
					$e=$nodeList->childNodes[$i];
					for($j=0; $j < $e->length; $j++){
						if($e->nodeName[$j]=="DoCaptureResponse" || $e->nodeName[$j]=="DoVoidResponse" || $e->nodeName[$j]=="DoReauthorizationResponse"){
							$ee=$e->childNodes[$j];
							for($jj=0; $jj < $ee->length; $jj++){
								if($ee->nodeName[$jj]=='Ack'){
									if($ee->nodeValue[$jj]=='Success' || $ee->nodeValue[$jj]=='SuccessWithWarning'){
										$success=TRUE;
										$vsRESPMSG='Success';
									}
								}elseif($ee->nodeName[$jj]=="Errors"){
									$ff=$ee->childNodes[$jj];
									for($kk=0; $kk < $ff->length; $kk++){
										if($ff->nodeName[$kk]=="LongMessage"){
											$themsg=$ff->nodeValue[$kk];
										}elseif($ff->nodeName[$kk]=="ErrorCode"){
											$vsERRCODE=$ff->nodeValue[$kk];
										}elseif($ff->nodeName[$kk]=="SeverityCode"){
											$iswarning=($ff->nodeValue[$kk]=='Warning');
										}
									}
									if(! $iswarning)
										$vsRESPMSG=$themsg . '<br />' . $vsRESPMSG;
								}elseif($ee->nodeName[$jj]=="DoCaptureResponseDetails"){
									$vsTRANSID=$ee->getValueByTagName('TransactionID');
								}
							}
						}
					}
				}
			}
			if($success){
				if(@$_GET['act']=='charge'){
					ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID=". $ordID) or ect_error();
					ect_query("UPDATE orders SET ordTransID='" . $vsTRANSID . "' WHERE ordID=". $ordID) or ect_error();
					ect_query("UPDATE orders SET ordStatus=3,ordStatusDate='" . date("Y-m-d H:i:s", time() + ($dateadjust*60*60)) . "' WHERE ordStatus<3 AND ordID=". $ordID) or ect_error();
				}elseif(@$_GET['act']=='void'){
					ect_query("UPDATE orders SET ordTransID='void' WHERE ordID=". $ordID) or ect_error();
					ect_query("UPDATE orders SET ordStatus=0,ordStatusDate='" . date("Y-m-d H:i:s", time() + ($dateadjust*60*60)) . "' WHERE ordID=". $ordID) or ect_error();
				}
				print $vsRESPMSG;
			}elseif($vsERRCODE != ''){
				print $vsRESPMSG . ' (' . $vsERRCODE . ')';
			}
		}else{
			print $errormsg;
		}
	}
}elseif(@$_GET['processor']=='Amazon' && is_numeric(getget('gid'))){
	$amazonstr='';
	$amazonprms=[];
	$isstripedotcom=TRUE;
	function calculateStringToSignV2(){
		global $scripturl,$endpointpath,$demomode;
		return 'POST' . "\n" . $scripturl . "\n" . $endpointpath . "\n" . getParametersAsString();
	}
	function getParametersAsString(){
		global $amazonprms;
		$queryParameters = array();
		foreach ($amazonprms as $key => $value) {
			$queryParameters[] = $key . '=' . strreplace('%7E', '~', rawurlencode($value));
		}
		return implode('&', $queryParameters);
	}
	function calculateSignatureAndParametersToString(){
		global $amazonprms,$amazonstr,$data3;
		uksort($amazonprms, 'strcmp');
		$amazonstr=getParametersAsString();
	}
	function amazonparam2($nam, $val){
		global $amazonstr,$amazonprms;
		$amazonprms[$nam]=replaceaccents($val);
	}
	$ordID=strreplace("'",'',@$_GET['gid']);
	$sSQL="SELECT ordPayProvider,ordAuthNumber,payProvData1,payProvData2,payProvData3,payProvDemo FROM orders INNER JOIN payprovider ON orders.ordPayProvider=payprovider.payProvID WHERE ordPayProvider=21 AND ordID='".escape_string($ordID)."'";
	$result=ect_query($sSQL) or ect_error();
	$rs=ect_fetch_assoc($result);
	$authcode=$rs['ordAuthNumber'];
	$data1=$rs['payProvData1'];
	$data2=$rs['payProvData2'];
	$data3=$rs['payProvData3'];
	$demomode=$rs['payProvDemo'];
	ect_free_result($result);
	$scripturl='mws-eu.amazonservices.com';
	if($GLOBALS['origCountryCode']=='US') $scripturl='mws.amazonservices.com';
	if($GLOBALS['origCountryCode']=='JP') $scripturl='mws.amazonservices.jp';
	$endpointpath='/OffAmazonPayments' . ($demomode?'_Sandbox':'') . '/2013-01-01';
	$endpoint='https://' . $scripturl . $endpointpath;
	if(@$_GET['act']=='settle'){
		$data2arr=explode('&',$data2);
		$data2=$data2arr[0];
		$sellerid=@$data2arr[1];
		$currdatetime=date('Y-m-d H:i:s');
		$timestamp=gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
		amazonparam2('AWSAccessKeyId',$data2);
		amazonparam2('Action','Capture');
		amazonparam2('AmazonAuthorizationId',$authcode);
		amazonparam2('CaptureAmount.Amount',number_format(getget('amount'),2,'.',''));
		amazonparam2('CaptureAmount.CurrencyCode',$countryCurrency);
		amazonparam2('CaptureReferenceId',$ordID.'_'.strreplace(array('-',':',' '),'',$currdatetime));
		amazonparam2('SellerCaptureNote','Capture: ' . $currdatetime);
		amazonparam2('SellerId',$sellerid);
		amazonparam2('SignatureMethod','HmacSHA256');
		amazonparam2('SignatureVersion',2);
		amazonparam2('Timestamp',$timestamp);
		amazonparam2('Version','2013-01-01');
		calculateSignatureAndParametersToString();
		$amazonprms['Signature']=base64_encode(hash_hmac('sha256', calculateStringToSignV2($amazonprms), $data3, true));
		$amazonstr=getParametersAsString();

		$captureamount=0;
		$currentstate='';
		if(!callcurlfunction($endpoint,$amazonstr,$res,'',$errormsg,FALSE)){
			print '<span style="color:#FF0000">' . "Error, couldn't update order " . $ordID . '<br />' . $errormsg . '</span><br/>';
		}else{
			//print strreplace('<','<br />&lt;',strreplace('</','&lt;/',$res)) . "<br />\n";
			$captureresponse=new SimpleXMLElement($res);
			if($captureresponse->Error){
				print '<span style="color:#FF0000">' . $captureresponse->Error->Message . '</span>';
			}else{
				if($captureresponse->CaptureResult){
					$captureamount=$captureresponse->CaptureResult->CaptureDetails->CaptureAmount->Amount;
					$currentstate=$captureresponse->CaptureResult->CaptureDetails->CaptureStatus->State;
				}
				if($currentstate=='Completed')
					ect_query("UPDATE orders SET ordAuthStatus='',ordStatusDate='" . date('Y-m-d H:i:s', time() + ($dateadjust*60*60)) . "' WHERE ordPayProvider=21 AND ordID=".$ordID) or ect_error();
				print 'Captured: ' . $captureamount . '. The status of this capture is: ' . $currentstate;
			}
		}
	}
}
?>