<?php
@include 'adminsession.php';
session_cache_limiter('none');
session_start();
ob_start();
//=========================================
//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
include "db_conn_open.php";
include "includes.php";
include "inc/incfunctions.php";
if(@$dateadjust=='') $dateadjust=0;
@ob_clean();
function twodp($theval){
	return(number_format($theval,2,'.',''));
}
function xmlstrip($name2){
	$name2=strreplace(
		array('&','’','–','-',"'",'€','£','é','è','™','ú','á','ñ','ü','ö','®','"','“','”','©','å'),
		array('chr(11)','chr(146)','chr(150)','chr(150)','chr(39)chr(39)','chr(128)','chr(163)','chr(130)','chr(138)','','u','a','n','chr(129)','chr(148)','','','','','','a'),
		$name2);
	$tmp_str="";
	for($i=0; $i < strlen($name2); $i++){
		$ch_code=ord(substr($name2,$i,1));
		if($ch_code>130) $tmp_str.='chr(' . $ch_code . ')'; else $tmp_str.=substr($name2,$i,1);
	}
	return($tmp_str);
}
function getsearchparams(){
	global $sd,$ed,$dateadjust,$hasdetails;
	$whereSQL='';
	$hasfromdate=FALSE;
	$hastodate=FALSE;
	$fromdate=trim(@$_REQUEST['fromdate']);
	$todate=trim(@$_REQUEST['todate']);
	if($fromdate != ''){
		$hasfromdate=TRUE;
		if(is_numeric($fromdate))
			$thefromdate=time()-($fromdate*60*60*24);
		else
			$thefromdate=parsedate($fromdate);
	}else
		$thefromdate=strtotime(date('Y-m-d', time()+($dateadjust*60*60)));
	if($todate != ''){
		$hastodate=TRUE;
		if(is_numeric($todate))
			$thetodate=time()-($todate*60*60*24);
		else
			$thetodate=parsedate($todate);
	}else
		$thetodate=strtotime(date('Y-m-d', time()+($dateadjust*60*60)));
	if($hasfromdate && $hastodate){
		if($thefromdate > $thetodate){
			$tmpdate=$thetodate;
			$thetodate=$thefromdate;
			$thefromdate=$tmpdate;
		}
	}
	$origsearchtext=unstripslashes(@$_POST['searchtext']);
	$searchtext=escape_string(unstripslashes(@$_POST['searchtext']));
	$ordersearchfield=trim(@$_POST['ordersearchfield']);
	$ordstatus=@$_POST['ordStatus'];
	$ordstate=@$_POST['ordstate'];
	$ordcountry=@$_POST['ordcountry'];
	$payprovider=@$_POST['payprovider'];
	$orddiscount=@$_POST['orddiscount'];
	if($ordersearchfield=='product' && $searchtext!='' && ! $hasdetails && getpost('act')!='ouresolutionsxmldump') $whereSQL.=' INNER JOIN cart ON orders.ordID=cart.cartOrderID ';
	if($ordersearchfield=='ordid' && $searchtext != '' && is_numeric($searchtext)){
		$whereSQL.=" WHERE ordID='" . $searchtext . "' ";
	}else{
		if(is_array($ordstatus)) $whereSQL.=' WHERE ' . (@$_POST['notstatus']=='ON' ? 'NOT ' : '') . '(ordStatus IN (' . implode(',', $ordstatus) . '))'; else $whereSQL.=' WHERE ordStatus<>1';
		if(is_array($ordstate)) $whereSQL.=' AND ' . (@$_POST['notsearchfield']=='ON' ? 'NOT ' : '') . "(ordState IN ('" . implode("','", $ordstate) . "'))";
		if(is_array($ordcountry)) $whereSQL.=' AND ' . (@$_POST['notsearchfield']=='ON' ? 'NOT ' : '') . "(ordCountry IN ('" . implode("','", $ordcountry) . "'))";
		if(is_array($payprovider)) $whereSQL.=' AND ' . (@$_POST['notsearchfield']=='ON' ? 'NOT ' : '') . '(ordPayprovider IN (' . implode(',', $payprovider) . '))';
		if(is_array($orddiscount)) $whereSQL.=' AND ' . (@$_POST['notsearchfield']=='ON' ? 'NOT ' : '') . '(cpaCpnID IN (' . implode(',', $orddiscount) . '))';
		if($hasfromdate)
			$whereSQL.=" AND ordDate BETWEEN '" . date('Y-m-d', $thefromdate) . "' AND '" . date('Y-m-d', ($hastodate ? $thetodate+96400 : $thefromdate+96400)) . "'";
		elseif($searchtext=='' && $ordstatus=='' && $ordstate=='' && $ordcountry=='' && $payprovider=='')
			$whereSQL.=" AND ordDate BETWEEN '" . date('Y-m-d', time()+($dateadjust*60*60)) . "' AND '" . date('Y-m-d', time()+($dateadjust*60*60)+96400) . "'";
		if($searchtext!=''){
			if($ordersearchfield=='ordid' || $ordersearchfield=='name'){
				if(@$usefirstlastname){
					splitfirstlastname($searchtext,$firstname,$lastname);
					if($lastname=='')
						$namesql="(ordName LIKE '%".$firstname."%' OR ordLastName LIKE '%".$firstname."%')";
					else
						$namesql="(ordName LIKE '%".$firstname."%' AND ordLastName LIKE '%".$lastname."%')";
				}else
					$namesql="ordName LIKE '%".$searchtext."%'";
			}
			if($ordersearchfield=='ordid')
				$whereSQL.=" AND (ordEmail LIKE '%" . $searchtext . "%' OR ".$namesql.')';
			elseif($ordersearchfield=='email')
				$whereSQL.=" AND ordEmail LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='authcode')
				$whereSQL.=" AND (ordAuthNumber LIKE '%" . $searchtext . "%' OR ordTransID LIKE '%" . $searchtext . "%')";
			elseif($ordersearchfield=='name')
				$whereSQL.=" AND " . $namesql;
			elseif($ordersearchfield=='product' && getpost('act')!='ouresolutionsxmldump')
				$whereSQL.=" AND (cartProdID LIKE '%" . $searchtext . "%' OR cartProdName LIKE '%" . $searchtext . "%')";
			elseif($ordersearchfield=='address')
				$whereSQL.=" AND (ordAddress LIKE '%" . $searchtext . "%' OR ordAddress2 LIKE '%" . $searchtext . "%' OR ordCity LIKE '%" . $searchtext . "%' OR ordState LIKE '%" . $searchtext . "%')";
			elseif($ordersearchfield=='phone')
				$whereSQL.=" AND ordPhone LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='zip')
				$whereSQL.=" AND ordZip LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='invoice')
				$whereSQL.=" AND ordInvoice LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='tracknum')
				$whereSQL.=" AND ordTrackNum LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='affiliate')
				$whereSQL.=" AND ordAffiliate='" . $searchtext . "'";
			elseif($ordersearchfield=='extra1')
				$whereSQL.=" AND ordExtra1 LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='extra2')
				$whereSQL.=" AND ordExtra2 LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='checkout1')
				$whereSQL.=" AND ordCheckoutExtra1 LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='checkout2')
				$whereSQL.=" AND ordCheckoutExtra2 LIKE '%" . $searchtext . "%'";
		}
	}
	return($whereSQL);
}
if(@$storesessionvalue=="") $storesessionvalue="virtualstore";
if(!@$GLOBALS['disallowlogin']) include 'inc/incloginfunctions.php';
if(@$_SESSION["loggedon"]!=$storesessionvalue || @$GLOBALS['disallowlogin']==TRUE){
	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;
}
$hasdetails=(@$_POST['act']=='dumpdetails');
header('Content-type: unknown/exe');
if(@$_POST['act']=='stockinventory'||@$_POST['act']=='filteredstock')
	header('Content-Disposition: attachment;filename=stockinventory.csv');
elseif(@$_POST['act']=='productimages'||@$_POST['act']=='filteredimages')
	header('Content-Disposition: attachment;filename=productimages.csv');
elseif(@$_POST['act']=='dump2COinventory')
	header('Content-Disposition: attachment;filename=inventory2co.csv');
elseif(@$_POST['act']=='fullinventory'||@$_POST['act']=='filteredinventory')
	header('Content-Disposition: attachment;filename=inventory.csv');
elseif(@$_POST['act']=='catinventory')
	header('Content-Disposition: attachment;filename=categoryinventory.csv');
elseif(@$_POST['act']=='dumpaffiliate')
	header('Content-Disposition: attachment;filename=affilreport.csv');
elseif(@$_POST['act']=='quickbooks'){
}elseif(@$_POST['act']=='ouresolutionsxmldump'){
	header('Content-Disposition: attachment;filename=oes_ordersdata.xml');
}elseif(@$_POST['act']=='dumpemails'){
	header('Content-Disposition: attachment;filename=mailinglist.csv');
}elseif(@$_POST['act']=='dumpevents'){
	header('Content-Disposition: attachment;filename=eventlog.csv');
}elseif($hasdetails)
	header('Content-Disposition: attachment;filename=orderdetails.csv');
else
	header('Content-Disposition: attachment;filename=dumporders.csv');
$alreadygotadmin=getadminsettings();
$admindatestr='Y-m-d';
if(@$admindateformat=='') $admindateformat=0;
if($admindateformat==1)
	$admindatestr='m/d/Y';
elseif($admindateformat==2)
	$admindatestr='d/m/Y';
if(@$_POST['sd'] != '')
	$sd=@$_POST['sd'];
elseif(@$_GET['sd'] != '')
	$sd=@$_GET['sd'];
else
	$sd=date($admindatestr);
if(@$_POST['ed'] != '')
	$ed=@$_POST['ed'];
elseif(@$_GET['ed'] != '')
	$ed=@$_GET['ed'];
else
	$ed=date($admindatestr);
$sd=parsedate($sd);
$ed=parsedate($ed);
$sslok=TRUE;
if(@$_SERVER["HTTPS"] != "on" && (@$_SERVER["SERVER_PORT"] != "443") && @$nochecksslserver != TRUE) $sslok=FALSE;
if(@$_POST["act"]=="dumpaffiliate"){
	print "Affiliate report for " . date($admindatestr, $sd) . " to " . date($admindatestr, $ed) . "\r\n";
	print '"ID","Name","Address","City","State","Zip","Country","Email","Total"' . "\r\n";
	$sSQL="SELECT affilID,affilName,affilAddress,affilCity,affilState,affilZip,affilCountry,affilEmail FROM affiliates ORDER BY affilID";
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		print '"' . strreplace('"','""',$rs["affilID"]) . '",';
		print '"' . strreplace('"','""',$rs["affilName"]) . '",';
		print '"' . strreplace('"','""',$rs["affilAddress"]) . '",';
		print '"' . strreplace('"','""',$rs["affilCity"]) . '",';
		print '"' . strreplace('"','""',$rs["affilState"]) . '",';
		print '"' . strreplace('"','""',$rs["affilZip"]) . '",';
		print '"' . strreplace('"','""',$rs["affilCountry"]) . '",';
		print '"' . strreplace('"','""',$rs["affilEmail"]) . '",';
		$sSQL2="SELECT SUM(ordTotal-ordDiscount) AS sumTot FROM affiliates LEFT JOIN orders ON affiliates.affilID=orders.ordAffiliate WHERE affilID='" . $rs["affilID"] . "' AND ordStatus>=3 AND ordDate BETWEEN '" . date("Y-m-d", $sd) . "' AND '" . date("Y-m-d", $ed) . " 23:59:59'";
		$alldata2=ect_query($sSQL2) or ect_error();
		$rs2=ect_fetch_assoc($alldata2);
		print $rs2['sumTot'] . "\r\n";
		ect_free_result($alldata2);
	}
	ect_free_result($result);
}elseif(@$_POST["act"]=="stockinventory"||@$_POST['act']=='filteredstock'){
	$stext=getrequest('stext');
	$stype=getrequest('stype');
	$sprice=getrequest('sprice');
	$thecat=getrequest('scat');
	if($thecat!='') $thecat=(int)$thecat;
	$sortorder=@$_COOKIE['psort'];
	$catorman=@$_COOKIE['pcatorman'];
	if(@$_POST['act']=='filteredstock'){
		$whereand=' WHERE ';
		if($thecat=='' || $sortorder=='nsf')
			$sSQL=' FROM products LEFT OUTER JOIN sections ON products.pSection=sections.sectionID';
		else
			$sSQL=" FROM multisections RIGHT JOIN products ON products.pId=multisections.pId LEFT OUTER JOIN sections ON products.pSection=sections.sectionID";
		if($thecat!=''){
			if($catorman=='dis'){
				$sSQL.=" INNER JOIN cpnassign ON products.pID=cpnassign.cpaAssignment" . $whereand . "cpnassign.cpaCpnID=" . $thecat;
				$whereand=' AND ';
			}elseif($catorman=='man'){
				$sSQL.=" INNER JOIN multisearchcriteria ON products.pID=multisearchcriteria.mSCpID" . $whereand . "multisearchcriteria.mSCscID=" . $thecat;
				$whereand=' AND ';
			}else{
				$sectionids=getsectionids($thecat, TRUE);
				if($sectionids!=''){
					if(@$sortorder=='nsf')
						$sSQL.=$whereand . " products.pSection IN (" . $sectionids . ") ";
					else
						$sSQL.=$whereand . " (products.pSection IN (" . $sectionids . ") OR multisections.pSection IN (" . $sectionids . ")) ";
					$whereand=' AND ';
				}
			}
		}
		if($sprice!=''){
			if(strpos($sprice, '-') !== FALSE){
				$pricearr=explode('-', $sprice);
				if(! is_numeric($pricearr[0])) $pricearr[0]=0;
				if(! is_numeric($pricearr[1])) $pricearr[1]=10000000;
				$sSQL.=$whereand . "pPrice BETWEEN " . $pricearr[0] . " AND " . $pricearr[1];
				$whereand=' AND ';
			}elseif(is_numeric($sprice)){
				$sSQL.=$whereand . "pPrice='" . escape_string($sprice) . "' ";
				$whereand=' AND ';
			}
		}
		if(trim($stext)!=''){
			$Xstext=escape_string($stext);
			$aText=explode(' ',$Xstext);
			if(@$nosearchadmindescription) $maxsearchindex=2; else $maxsearchindex=3;
			$aFields[0]='products.pId';
			$aFields[1]='pSKU';
			$aFields[2]=getlangid('pName',1);
			$aFields[3]=getlangid('pDescription',2);
			if($stype=='exact'){
				$sSQL.=$whereand . "(products.pId LIKE '%" . $Xstext . "%' OR ".getlangid("pName",1)." LIKE '%" . $Xstext . "%' OR ".getlangid("pDescription",2)." LIKE '%" . $Xstext . "%' OR ".getlangid("pLongDescription",4)." LIKE '%" . $Xstext . "%') ";
				$whereand=' AND ';
			}else{
				$sJoin='AND ';
				if($stype=='any') $sJoin='OR ';
				$sSQL.=$whereand . '(';
				$whereand=' AND ';
				for($index=0;$index<=$maxsearchindex;$index++){
					$sSQL.='(';
					$rowcounter=0;
					$arrelms=count($aText);
					foreach($aText as $theopt){
						if(is_array($theopt))$theopt=$theopt[0];
						$sSQL.=$aFields[$index] . " LIKE '%" . $theopt . "%' ";
						if(++$rowcounter < $arrelms) $sSQL.=$sJoin;
					}
					$sSQL.=') ';
					if($index < $maxsearchindex) $sSQL.='OR ';
				}
				$sSQL.=') ';
			}
		}
		if(@$_REQUEST['disp']=='6'){ $sSQL.=$whereand . 'pBackOrder<>0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='7'){ $sSQL.=$whereand . 'pBackOrder=0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='8'){ $sSQL.=$whereand . 'pGiftWrap<>0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='9'){ $sSQL.=$whereand . 'pGiftWrap=0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='10'){ $sSQL.=$whereand . 'pRecommend<>0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='11'){ $sSQL.=$whereand . 'pRecommend=0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='12'){ $sSQL.=$whereand . 'pStaticPage<>0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='13'){ $sSQL.=$whereand . 'pStaticPage=0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='4'){ $sSQL.=$whereand . '(rootSection IS NULL OR rootSection=0)'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='3'){ $sSQL.=$whereand . '(pInStock<=0 AND pStockByOpts=0)'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='' || @$_REQUEST['disp']=='5'){ $sSQL.=$whereand . 'pDisplay<>0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='2'){ $sSQL.=$whereand . 'pDisplay=0'; $whereand=' AND '; }
	}else
		$sSQL=' FROM products';
	$sSQL2="SELECT DISTINCT products.pID,pName,pPrice,pInStock,pStockByOpts";
	$result=ect_query($sSQL2.$sSQL) or ect_error();
	print "pID,pName,pPrice,pInStock,optID,OptionGroup,Option\r\n";
	while($rs=ect_fetch_assoc($result)){
		if((int)$rs['pStockByOpts'] != 0){
			$result2=ect_query("SELECT optID,optGrpName,optName,optStock FROM optiongroup INNER JOIN options ON optiongroup.optGrpID=options.optGroup INNER JOIN prodoptions ON options.optGroup=prodoptions.poOptionGroup WHERE prodoptions.poProdID='" . escape_string($rs["pID"]) . "'") or ect_error();
			while($rs2=ect_fetch_assoc($result2)){
				print '"' . strreplace('"','""',$rs['pID']) . '",';
				print '"' . strreplace('"','""',$rs['pName']) . '",';
				print '"' . $rs['pPrice'] . '",';
				print $rs2['optStock'] . ",";
				print $rs2['optID'] . ",";
				print '"' . strreplace('"','""',$rs2['optGrpName']) . '",';
				print '"' . strreplace('"','""',$rs2['optName']) . '"' . "\r\n";
			}
			ect_free_result($result2);
		}else{
			print '"' . strreplace('"','""',$rs['pID']) . '",';
			print '"' . strreplace('"','""',$rs['pName']) . '",';
			print '"' . $rs['pPrice'] . '",';
			print $rs['pInStock'] . ",,,\r\n";
		}
	}
	ect_free_result($result);
}elseif(@$_POST['act']=='productimages'||@$_POST['act']=='filteredimages'){
	$thecat=getrequest('scat');
	if($thecat!='') $thecat=(int)$thecat;
	$catorman=@$_COOKIE['pcatorman'];
	if(@$_POST['act']=='filteredimages'){
		$sSQL=' FROM productimages';
		if($thecat!=''){
			if($catorman=='dis'){
				$sSQL.=" INNER JOIN products ON productimages.imageProduct=products.pID INNER JOIN cpnassign ON products.pID=cpnassign.cpaAssignment WHERE cpnassign.cpaCpnID=" . $thecat;
			}elseif($catorman=='man'){
				$sSQL.=" INNER JOIN products ON productimages.imageProduct=products.pID INNER JOIN multisearchcriteria ON products.pID=multisearchcriteria.mSCpID WHERE multisearchcriteria.mSCscID=" . $thecat;
			}else{
				$sectionids=getsectionids($thecat, TRUE);
				if($sectionids!=''){
					$sSQL.=' INNER JOIN products ON productimages.imageProduct=products.pID WHERE products.pSection IN (' . $sectionids . ') ';
				}
			}
		}
	}else
		$sSQL=' FROM productimages';
	$sSQL2='SELECT imageProduct,imageSrc,imageType,imageNumber' . $sSQL . ' ORDER BY imageProduct,imageType,imageNumber';
	//print $sSQL2."\r\n";
	$result=ect_query($sSQL2) or ect_error();
	print "imageProduct,imageSrc,imageType,imageNumber\r\n";
	while($rs=ect_fetch_assoc($result)){
		print '"' . strreplace('"','""',$rs['imageProduct']) . '",';
		print '"' . strreplace('"','""',$rs['imageSrc']) . '",';
		print $rs['imageType'] . ',' . $rs['imageNumber'] . "\r\n";
	}
	ect_free_result($result);
}elseif(@$_POST['act']=='fullinventory'||@$_POST['act']=='filteredinventory'){
	$stext=getrequest('stext');
	$stype=getrequest('stype');
	$sprice=getrequest('sprice');
	$thecat=getrequest('scat');
	if($thecat!='') $thecat=(int)$thecat;
	$sortorder=@$_COOKIE['psort'];
	$catorman=@$_COOKIE['pcatorman'];
	$columnlist='products.pID,pName';
	for($index=2; $index <= $adminlanguages+1; $index++){
		if(($adminlangsettings & 1)==1) $columnlist.=',pName' . $index;
	}
	$columnlist.=',products.pSection,pPrice,pWholesalePrice,pListPrice,pShipping,pShipping2,pWeight,pDisplay,pSell,pBackOrder,pGiftWrap,pExemptions,pInStock,pDims,pTax,pDropship';
	if(@$digidownloads==TRUE) $columnlist.=',pDownload';
	if(@$numcustomcolumns!=''){
		for($index=1;$index<=$numcustomcolumns;$index++){
			$columnlist.=',pCustom' . $index;
		}
	}else{
		if(strpos(@$productpagelayout.@$detailpagelayout,'custom1')!==FALSE) $columnlist.=',pCustom1';
		if(strpos(@$productpagelayout.@$detailpagelayout,'custom2')!==FALSE) $columnlist.=',pCustom2';
		if(strpos(@$productpagelayout.@$detailpagelayout,'custom3')!==FALSE) $columnlist.=',pCustom3';
	}
	$columnlist.=',pStaticPage,pStockByOpts,pRecommend,pOrder,pSKU,pManufacturer,pSearchParams,pTitle,pMetaDesc,pStaticURL,pDescription,pMinQuant,pDateAdded';
	for($index=2; $index <= $adminlanguages+1; $index++){
		if(($adminlangsettings & 2)==2) $columnlist.=',pDescription' . $index;
	}
	$columnlist.=',pLongDescription';
	for($index=2; $index <= $adminlanguages+1; $index++){
		if(($adminlangsettings & 4)==4) $columnlist.=',pLongDescription' . $index;
	}
	if(@$_POST['act']=='filteredinventory'){
		$whereand=' WHERE ';
		if($thecat=='' || $sortorder=='nsf')
			$sSQL=' FROM products LEFT OUTER JOIN sections ON products.pSection=sections.sectionID';
		else
			$sSQL=" FROM multisections RIGHT JOIN products ON products.pId=multisections.pId LEFT OUTER JOIN sections ON products.pSection=sections.sectionID";
		if($thecat!=''){
			if($catorman=='dis'){
				$sSQL.=" INNER JOIN cpnassign ON products.pID=cpnassign.cpaAssignment" . $whereand . "cpnassign.cpaCpnID=" . $thecat;
				$whereand=' AND ';
			}elseif($catorman=='man'){
				$sSQL.=" INNER JOIN multisearchcriteria ON products.pID=multisearchcriteria.mSCpID" . $whereand . "multisearchcriteria.mSCscID=" . $thecat;
				$whereand=' AND ';
			}else{
				$sectionids=getsectionids($thecat, TRUE);
				if($sectionids!=''){
					if(@$sortorder=='nsf')
						$sSQL.=$whereand . " products.pSection IN (" . $sectionids . ") ";
					else
						$sSQL.=$whereand . " (products.pSection IN (" . $sectionids . ") OR multisections.pSection IN (" . $sectionids . ")) ";
					$whereand=' AND ';
				}
			}
		}
		if($sprice!=''){
			if(strpos($sprice, '-') !== FALSE){
				$pricearr=explode('-', $sprice);
				if(! is_numeric($pricearr[0])) $pricearr[0]=0;
				if(! is_numeric($pricearr[1])) $pricearr[1]=10000000;
				$sSQL.=$whereand . "pPrice BETWEEN " . $pricearr[0] . " AND " . $pricearr[1];
				$whereand=' AND ';
			}elseif(is_numeric($sprice)){
				$sSQL.=$whereand . "pPrice='" . escape_string($sprice) . "' ";
				$whereand=' AND ';
			}
		}
		if(trim($stext)!=''){
			$Xstext=escape_string($stext);
			$aText=explode(' ',$Xstext);
			if(@$nosearchadmindescription) $maxsearchindex=2; else $maxsearchindex=3;
			$aFields[0]='products.pId';
			$aFields[1]='pSKU';
			$aFields[2]=getlangid('pName',1);
			$aFields[3]=getlangid('pDescription',2);
			if($stype=='exact'){
				$sSQL.=$whereand . "(products.pId LIKE '%" . $Xstext . "%' OR ".getlangid("pName",1)." LIKE '%" . $Xstext . "%' OR ".getlangid("pDescription",2)." LIKE '%" . $Xstext . "%' OR ".getlangid("pLongDescription",4)." LIKE '%" . $Xstext . "%') ";
				$whereand=' AND ';
			}else{
				$sJoin='AND ';
				if($stype=='any') $sJoin='OR ';
				$sSQL.=$whereand . '(';
				$whereand=' AND ';
				for($index=0;$index<=$maxsearchindex;$index++){
					$sSQL.='(';
					$rowcounter=0;
					$arrelms=count($aText);
					foreach($aText as $theopt){
						if(is_array($theopt))$theopt=$theopt[0];
						$sSQL.=$aFields[$index] . " LIKE '%" . $theopt . "%' ";
						if(++$rowcounter < $arrelms) $sSQL.=$sJoin;
					}
					$sSQL.=') ';
					if($index < $maxsearchindex) $sSQL.='OR ';
				}
				$sSQL.=') ';
			}
		}
		if(@$_REQUEST['disp']=='6'){ $sSQL.=$whereand . 'pBackOrder<>0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='7'){ $sSQL.=$whereand . 'pBackOrder=0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='8'){ $sSQL.=$whereand . 'pGiftWrap<>0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='9'){ $sSQL.=$whereand . 'pGiftWrap=0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='10'){ $sSQL.=$whereand . 'pRecommend<>0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='11'){ $sSQL.=$whereand . 'pRecommend=0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='12'){ $sSQL.=$whereand . 'pStaticPage<>0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='13'){ $sSQL.=$whereand . 'pStaticPage=0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='4'){ $sSQL.=$whereand . '(rootSection IS NULL OR rootSection=0)'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='3'){ $sSQL.=$whereand . '(pInStock<=0 AND pStockByOpts=0)'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='' || @$_REQUEST['disp']=='5'){ $sSQL.=$whereand . 'pDisplay<>0'; $whereand=' AND '; }
		if(@$_REQUEST['disp']=='2'){ $sSQL.=$whereand . 'pDisplay=0'; $whereand=' AND '; }
	}else
		$sSQL=' FROM products';
	if($sortorder=='ida')
		$sSQL.=' ORDER BY products.pid';
	elseif($sortorder=='idd')
		$sSQL.=' ORDER BY products.pid DESC';
	elseif($sortorder=='')
		$sSQL.=' ORDER BY pName';
	elseif($sortorder=='na2')
		$sSQL.=' ORDER BY pName2';
	elseif($sortorder=='na3')
		$sSQL.=' ORDER BY pName3';
	elseif($sortorder=='nad')
		$sSQL.=' ORDER BY pName DESC';
	elseif($sortorder=='pra')
		$sSQL.=' ORDER BY pPrice';
	elseif($sortorder=='prd')
		$sSQL.=' ORDER BY pPrice DESC';
	elseif($sortorder=='daa')
		$sSQL.=' ORDER BY pDateAdded';
	elseif($sortorder=='dad')
		$sSQL.=' ORDER BY pDateAdded DESC';
	elseif($sortorder=='poa')
		$sSQL.=' ORDER BY pOrder';
	elseif($sortorder=='pod')
		$sSQL.=' ORDER BY pOrder DESC';
	elseif($sortorder=='sta')
		$sSQL.=' ORDER BY products.pInStock';
	elseif($sortorder=='std')
		$sSQL.=' ORDER BY products.pInStock DESC';
	$sSQL='SELECT DISTINCT ' . $columnlist . $sSQL;
	$result=ect_query($sSQL) or ect_error();
	$fieldlistarr=explode(',',strreplace('products.','',$columnlist));
	$addcomma='';
	foreach($fieldlistarr as $flarrval){
		print $addcomma;
		print '"' . $flarrval . '"';
		$addcomma=',';
	}
	print "\r\n";
	while($rs=ect_fetch_assoc($result)){
		$addcomma='';
		foreach($fieldlistarr as $flarrval){
			print $addcomma;
			print '"' . strreplace('"','""',$rs[$flarrval]). '"';
			$addcomma=',';
		}
		print "\r\n";
	}
	ect_free_result($result);
}elseif(@$_POST['act']=='catinventory'){
	$fieldlist='sectionID,sectionName';
	for($index=2; $index <= $adminlanguages+1; $index++){
		if(($adminlangsettings & 256)==256) $fieldlist.=',sectionName' . $index;
	}
	$fieldlist.=',sectionWorkingName,sectionImage,topSection,sectionOrder,rootSection,sectionDisabled,sectionURL';
	for($index=2; $index <= $adminlanguages+1; $index++){
		if(($adminlangsettings & 2048)==2048) $fieldlist.=',sectionURL' . $index;
	}
	$fieldlist.=',sectionDescription';
	for($index=2; $index <= $adminlanguages+1; $index++){
		if(($adminlangsettings & 512)==512) $fieldlist.=',sectionDescription' . $index;
	}
	$fieldlist.=',sectionHeader';
	for($index=2; $index <= $adminlanguages+1; $index++){
		if(($adminlangsettings & 524288)==524288) $fieldlist.=',sectionHeader' . $index;
	}
	$sSQL='SELECT ' . $fieldlist . ' FROM sections';
	$result=ect_query($sSQL) or ect_error();
	$fieldlistarr=explode(',', $fieldlist);
	$addcomma='';
	foreach($fieldlistarr as $flarrval){
		print $addcomma;
		print '"' . $flarrval . '"';
		$addcomma=',';
	}
	print "\r\n";
	while($rs=ect_fetch_assoc($result)){
		$addcomma='';
		foreach($fieldlistarr as $flarrval){
			print $addcomma;
			print '"' . strreplace('"','""',$rs[$flarrval]). '"';
			$addcomma=',';
		}
		print "\r\n";
	}
	ect_free_result($result);
}elseif(@$_POST["act"]=="dump2COinventory"){
	$sSQL2="SELECT payProvData1 FROM payprovider WHERE payProvID=2";
	$result=ect_query($sSQL2) or ect_error();
	$rs=ect_fetch_assoc($result);
	print $rs["payProvData1"] . "\r\n";
	ect_free_result($result);
	$sSQL2="SELECT pID,pName,pPrice," . (@$digidownloads==TRUE ? "pDownload," : "") . "pDescription FROM products";
	$result=ect_query($sSQL2) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		print strreplace(',', '&#44;', $rs["pID"]) . ",";
		print preg_replace("(\r\n|\n|\r)",' ',strreplace(',', '&#44;',strip_tags($rs["pName"]))) . ",";
		print ",";
		print $rs["pPrice"] . ",";
		print ",,";
		if(@$digidownloads==TRUE)
			print (trim($rs["pDownload"]) != "" ? "N" : "Y") . ",";
		else
			print 'Y,';
		print preg_replace("(\r\n|\n|\r)",'\\n',strreplace(',','&#44;',strip_tags($rs["pDescription"]))) . "\r\n";
	}
	ect_free_result($result);
}elseif(@$_POST["act"]=="quickbooks"){
}elseif(@$_POST["act"]=="ouresolutionsxmldump"){
	print '<?xml version="1.0"?>' . "\r\n";
	print '<DATABASE NAME="DataBaseCopy.mdb" >' . "\r\n";
	$sSQL="SELECT ordID,cartProdId,cartProdName,cartProdPrice,cartQuantity,cartID FROM cart INNER JOIN orders ON cart.cartOrderId=orders.ordID";
	$sSQL.=getsearchparams();
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$theoptionspricediff=0;
		$sSQL="SELECT coPriceDiff,coOptGroup,coCartOption FROM cartoptions WHERE coCartID=" . $rs['cartID'];
		$result2=ect_query($sSQL) or ect_error();
		while($rs2=ect_fetch_assoc($result2)){
			$theoptionspricediff+=$rs2['coPriceDiff'];
		}
		$theunitprice=$rs['cartProdPrice']+$theoptionspricediff;
		$sSQL="SELECT pName,pDescription,pDropShip FROM products WHERE pID='" . $rs['cartProdId'] . "'";
		$result2=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result2)){
			$prodname=strip_tags($rs2['pName']);
			$proddesc=strip_tags($rs2['pDescription']);
			$supplier=$rs2['pDropShip'];
		}else{
			$prodname='';
			$proddesc='';
			$supplier=0;
		}
		if($ouresolutionsxml==1)
			$itemname=strip_tags($rs['cartProdId']) . 'chr(60)brchr(62)' . $proddesc;
		elseif($ouresolutionsxml==3)
			$itemname=strip_tags($rs['cartProdId']);
		elseif($ouresolutionsxml==4)
			$itemname=$prodname;
		elseif($ouresolutionsxml==5)
			$itemname=strip_tags($rs['cartProdId']) . 'chr(60)brchr(62)' . $prodname;
		else // default to "2"
			$itemname=$prodname . 'chr(60)brchr(62)' . $proddesc;
		print "<DATA TABLE='oitems' ORDERITEMID='" . $rs['cartID'] . "' ORDERID='" . $rs['ordID'] . "' CATALOGID='" . $rs['cartID'] . "' NUMITEMS='" . $rs['cartQuantity'] . "' ITEMNAME='" . xmlstrip($itemname) . "' UNITPRICE='" . twodp($theunitprice) . "' DUALPRICE='0' SUPPLIERID='" . $supplier . "' ADDRESS='' />" . "\r\n";
	}
	ect_free_result($result);
	$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,statPrivate,ordAddInfo FROM orders INNER JOIN orderstatus ON orders.ordStatus=orderstatus.statID";
	$sSQL.=getsearchparams();
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$ordGrandTotal=($rs['ordTotal']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordShipping']+$rs['ordHandling'])-$rs['ordDiscount'];
		if(@$usefirstlastname){
			$firstname=xmlstrip(trim($rs['ordName']));
			$lastname=xmlstrip(trim($rs['ordLastName']));
		}else{
			$thename=xmlstrip(trim($rs['ordName']));
			if($thename != ''){
				if(strstr($thename,' ')){
					$namearr=explode(' ',$thename,2);
					$firstname=$namearr[0];
					$lastname=$namearr[1];
				}else{
					$firstname='';
					$lastname=$thename;
				}
			}
		}
		print "<DATA TABLE='orders' ORDERID='" . $rs['ordID'] . "' OCUSTOMERID='" . $rs['ordID'] . "' ODATE='" . date($admindatestr, strtotime($rs['ordDate'])) . "' ORDERAMOUNT='" . twodp($ordGrandTotal) . "' OFIRSTNAME='" . $firstname . "' OLASTNAME='" . $lastname . "' OEMAIL='" . xmlstrip($rs['ordEmail']) . "' OADDRESS='" . xmlstrip($rs['ordAddress'] . (trim($rs['ordAddress2']) != '' ? ', ' . $rs['ordAddress2'] : '')) . "' OCITY='" . xmlstrip($rs['ordCity']) . "' OPOSTCODE='" . xmlstrip($rs['ordZip']) . "' OSTATE='" . xmlstrip($rs['ordState']) . "' OCOUNTRY='" . xmlstrip($rs['ordCountry']) . "' OPHONE='" . substr(xmlstrip(strreplace(array(' ','.','-',')','('), '', $rs['ordPhone'])), -10) . "' OFAX='' OCOMPANY='" . (@$extra1iscompany==TRUE ? xmlstrip($rs['ordExtra1']) : '') . "' OCARDTYPE='' ";
		if(@$dumpccnumber){
			if($sslok==FALSE){
				print "OCARDNO='No SSL' OCARDNAME='No SSL' OCARDEXPIRES='No SSL' OCARDADDRESS='No SSL' ";
			}else{
				$result2=ect_query("SELECT ordCNum,ordPayProvider FROM orders WHERE ordID=" . $rs["ordID"]) or ect_error();
				$rs2=ect_fetch_assoc($result2);
				$ordCNum=$rs2['ordCNum'];
				$encryptmethod=strtolower(@$encryptmethod);
				if(trim($ordCNum)=='' || is_null($ordCNum) || $rs2['ordPayProvider']!=10){
					print "OCARDNO='' OCARDNAME='' OCARDEXPIRES='' OCARDADDRESS='' ";
				}elseif($encryptmethod=='mcrypt'){
					if(@$mcryptalg=='') $mcryptalg=MCRYPT_BLOWFISH;
					$td=mcrypt_module_open($mcryptalg, '', 'cbc', '');
					$thekey=@$ccencryptkey;
					$thekey=substr($thekey, 0, mcrypt_enc_get_key_size($td));
					$cnumarr=explode(' ', $ordCNum);
					$iv=@$cnumarr[0];
					$iv=@pack("H" . strlen($iv), $iv);
					$ordCNum=@pack("H" . strlen(@$cnumarr[1]), @$cnumarr[1]);
					mcrypt_generic_init($td, $thekey, $iv);
					$cnumarr=explode("&", mdecrypt_generic($td, $ordCNum));
					mcrypt_generic_deinit($td);
					mcrypt_module_close($td);
					if(is_array($cnumarr)){
						print "OCARDNO='" . $cnumarr[0] . "' OCARDNAME='" . $cnumarr[3] . "' OCARDEXPIRES='" . $cnumarr[1] . "' OCARDADDRESS='" . $rs["ordAddress"] . (trim($rs["ordAddress2"]) != '' ? ', ' . $rs["ordAddress2"] : '') . "' ";
					}else
						print "OCARDNO='' OCARDNAME='' OCARDEXPIRES='' OCARDADDRESS='' ";
				}elseif($encryptmethod=="none"){
					$cnumarr=explode("&",$ordCNum);
					if(is_array($cnumarr)){
						print "OCARDNO='" . $cnumarr[0] . "' OCARDNAME='" . $cnumarr[3] . "' OCARDEXPIRES='" . $cnumarr[1] . "' OCARDADDRESS='" . $rs["ordAddress"] . (trim($rs["ordAddress2"]) != '' ? ', ' . $rs["ordAddress2"] : '') . "' ";
					}else
						print "OCARDNO='' OCARDNAME='' OCARDEXPIRES='' OCARDADDRESS='' ";
				}
				ect_free_result($result2);
			}
		}
		print "OPROCESSED='' OCOMMENT='" . xmlstrip($rs['ordAddInfo']) . "' OTAX='" . twodp($rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']) . "' OPROMISEDSHIPDATE='' OSHIPPEDDATE='' OSHIPMETHOD='0' OSHIPCOST='" . twodp($rs['ordShipping']) . "' ";
		print "OSHIPNAME='" . xmlstrip(trim($rs['ordShipName'].' '.$rs['ordShipLastName'])) . "' OSHIPCOMPANY='' OSHIPEMAIL='' OSHIPMETHODTYPE='" . xmlstrip($rs['ordShipType']) . "' OSHIPADDRESS='" . xmlstrip($rs['ordShipAddress'] . (trim($rs['ordShipAddress2']) != '' ? ', ' . $rs['ordShipAddress2'] : '')) . "' OSHIPTOWN='" . xmlstrip($rs['ordShipCity']) . "' OSHIPZIP='" . xmlstrip($rs['ordShipZip']) . "' OSHIPCOUNTRY='" . xmlstrip($rs['ordShipCountry']) . "' OSHIPSTATE='" . xmlstrip($rs['ordShipState']) . "' ";
		print "OPAYMETHOD='" . $rs['ordPayProvider'] . "' OTHER1='" . (@$extra1iscompany==TRUE ? '' : xmlstrip($rs['ordExtra1'])) . "' OTHER2='" . xmlstrip($rs['ordExtra2']) . "' OTIME='' OAUTHORIZATION='' OERRORS='' ODISCOUNT='" . twodp($rs['ordDiscount']) . "' OSTATUS='" . xmlstrip($rs['statPrivate']) . "' OAFFID='' ODUALTOTAL='0' ODUALTAXES='0' ODUALSHIPPING='0' ODUALDISCOUNT='0' OHANDLING='" . twodp($rs['ordHandling']) . "' COUPON='" . xmlstrip(strip_tags($rs['ordDiscountText'])) . "' COUPONDISCOUNT='0' COUPONDISCOUNTDUAL='0' GIFTCERTIFICATE='' GIFTAMOUNTUSED='0' GIFTAMOUNTUSEDDUAL='0' CANCELED='" . ($rs['ordStatus']<2 ? "True" : "False") . "' />\r\n";
	}
	print "</DATABASE>\r\n";
	ect_free_result($result);
}elseif(@$_POST['act']=='dumpevents'){
	if(@$_SESSION['loginid']==0){
		$success=TRUE;
		$sSQL="SELECT userID,eventType,eventDate,eventSuccess,eventOrigin,areaAffected FROM auditlog ORDER BY logID DESC";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			print '"'.strreplace('"','""',$rs['userID']).'",';
			print '"'.strreplace('"','""',$rs['eventType']).'",';
			print strreplace('"','""',$rs['eventDate']).",";
			print '"'.strreplace('"','""',$rs['eventSuccess']).'",';
			print '"'.strreplace('"','""',$rs['eventOrigin']).'",';
			print '"'.strreplace('"','""',$rs['areaAffected']).'",'."\r\n";
		}
		ect_free_result($result);
	}else{
		$success=FALSE;
		print 'No Access Privileges.';
	}
	logevent(@$_SESSION['loginuser'],'EVENTLOG',$success,'dumporders.php','DUMP LOG');
}elseif(@$_POST['act']=='dumpemails'){
	$sSQL="SELECT email,mlName,mlIPAddress,mlConfirmDate FROM mailinglist WHERE isconfirmed<>0";
	if(@$_GET['entirelist']!='1') $sSQL.=" AND selected<>0";
	$result=ect_query($sSQL) or ect_error();
	print "Email,Full Name\r\n";
	while($rs=ect_fetch_assoc($result)){
		print '"'.strreplace('"','""',$rs['email']).'",';
		print '"'.strreplace('"','""',$rs['mlName']).'",';
		print '"'.strreplace('"','""',$rs['mlIPAddress']).'",';
		$thedate=$rs['mlConfirmDate'];
		if($thedate!=''){
			print '"'.strreplace('"','""',$rs['mlConfirmDate']).'",'."\r\n";
		}else{
			print '"",'."\r\n";
		}
	}
	ect_free_result($result);
}else{
	$sSQL2="SELECT statID,statPrivate FROM orderstatus";
	$result=ect_query($sSQL2) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$allstatus[$rs['statID']]=$rs['statPrivate'];
	}
	ect_free_result($result);
	$orddiscount=@$_POST['orddiscount'];
	if($hasdetails)
		$sSQL2="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,payProvName,ordAuthNumber,ordTotal,ordDate,ordStateTax,ordCountryTax,ordHSTTax,ordShipping,ordHandling,ordDiscount,ordDiscountText,ordAddInfo,ordShipType,ordStatus,ordAuthStatus,ordTrackNum,ordInvoice,cartProdId,cartProdName,cartProdPrice,cartQuantity,cartID FROM cart LEFT JOIN orders" . ($orddiscount!=''?" INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID":'') . " ON cart.cartOrderId=orders.ordID LEFT JOIN payprovider ON payprovider.payProvID=orders.ordPayProvider";
	else
		$sSQL2="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,payProvName,ordAuthNumber,ordTotal,ordDate,ordStateTax,ordCountryTax,ordHSTTax,ordShipping,ordHandling,ordDiscount,ordDiscountText,ordAddInfo,ordShipType,ordStatus,ordAuthStatus,ordTrackNum,ordInvoice FROM orders" . ($orddiscount!=''?" INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID":'') . " LEFT JOIN payprovider ON payprovider.payProvID=orders.ordPayProvider";
	$sSQL2.=getsearchparams();
	$result=ect_query($sSQL2 . ' ORDER BY ordID' . ($hasdetails?',cartID':'')) or ect_error();
	print '"OrderID",';
	if(@$extraorderfield1 != '') print '"' . strreplace(array('"',' '),array('""',''),ucwords($extraorderfield1)) . '",';
	if(@$usefirstlastname) print '"FirstName","LastName",'; else print '"CustomerName",';
	print '"Address",';
	if(@$useaddressline2==TRUE) print '"Address2",';
	print '"City","State","Zip","Country","Email","Phone",';
	if(@$extraorderfield2 != '') print '"' . strreplace(array('"',' '),array('""',''),ucwords($extraorderfield2)) . '",';
	if(@$extraorderfield1 != '') print '"' . strreplace(array('"',' '),array('""',''),'Ship'.ucwords($extraorderfield1)) . '",';
	print '"ShipName",';
	if(@$usefirstlastname) print '"ShipLastName",';
	print '"ShipAddress",';
	if(@$useaddressline2==TRUE) print '"ShipAddress2",';
	print '"ShipCity","ShipState","ShipZip","ShipCountry","ShipPhone",';
	if(@$extraorderfield2 != '') print '"' . strreplace(array('"',' '),array('""',''),'Ship'.ucwords($extraorderfield2)) . '",';
	print '"PaymentMethod","AuthNumber","Total","Date","StateTax","CountryTax",';
	if($origCountryID==2) print '"HST",';
	print '"Shipping","Handling","Discounts","AddInfo",';
	if(@$extracheckoutfield1 != '') print '"' . strreplace(array('"',' '),array('""',''),ucwords($extracheckoutfield1)) . '",';
	if(@$extracheckoutfield2 != '') print '"' . strreplace(array('"',' '),array('""',''),ucwords($extracheckoutfield2)) . '",';
	print '"ShippingMethod","Status","AuthStatus","Tracking","InvoiceNum","DiscountText"';
	if(@$dumpccnumber) print ',"Card Number","Expiry Date","CVV Code","Issue Number","Card Name"';
	if($hasdetails) print ',"ProductID","ProductName","ProductPrice","Quantity","Options"';
	print "\r\n";
	while($rs=ect_fetch_assoc($result)){
		$discounttext=trim(strreplace(array("<br>","<br />"),',',trim_($rs['ordDiscountText'])),',');
		print $rs["ordID"] . ",";
		if(@$extraorderfield1 != '') print '"' . strreplace('"','""',$rs["ordExtra1"]) . '",';
		print '"' . strreplace('"','""',$rs["ordName"]) . '",';
		if(@$usefirstlastname) print '"' . strreplace('"','""',$rs['ordLastName']) . '",';
		print '"' . strreplace('"','""',$rs["ordAddress"]) . '",';
		if(@$useaddressline2==TRUE) print '"' . strreplace('"','""',$rs["ordAddress2"]) . '",';
		print '"' . strreplace('"','""',$rs["ordCity"]) . '",';
		print '"' . strreplace('"','""',$rs["ordState"]) . '",';
		print '"' . strreplace('"','""',$rs["ordZip"]) . '",';
		print '"' . strreplace('"','""',$rs["ordCountry"]) . '",';
		print '"' . strreplace('"','""',$rs["ordEmail"]) . '",';
		print '"' . strreplace('"','""',$rs["ordPhone"]) . '",';
		if(@$extraorderfield2 != '') print '"' . strreplace('"','""',$rs["ordExtra2"]) . '",';
		if(@$extraorderfield1 != '') print '"' . strreplace('"','""',$rs["ordShipExtra1"]) . '",';
		print '"' . strreplace('"','""',$rs["ordShipName"]) . '",';
		if(@$usefirstlastname) print '"' . strreplace('"','""',$rs['ordShipLastName']) . '",';
		print '"' . strreplace('"','""',$rs["ordShipAddress"]) . '",';
		if(@$useaddressline2==TRUE) print '"' . strreplace('"','""',$rs["ordShipAddress2"]) . '",';
		print '"' . strreplace('"','""',$rs["ordShipCity"]) . '",';
		print '"' . strreplace('"','""',$rs["ordShipState"]) . '",';
		print '"' . strreplace('"','""',$rs["ordShipZip"]) . '",';
		print '"' . strreplace('"','""',$rs["ordShipCountry"]) . '",';
		print '"' . strreplace('"','""',$rs["ordShipPhone"]) . '",';
		if(@$extraorderfield2 != '') print '"' . strreplace('"','""',$rs["ordShipExtra2"]) . '",';
		print '"' . strreplace('"','""',$rs["payProvName"]) . '",';
		print '"' . strreplace('"','""',$rs["ordAuthNumber"]) . '",';
		print '"' . $rs["ordTotal"] . '",';
		print '"' . $rs["ordDate"] . '",';
		print '"' . $rs["ordStateTax"] . '",';
		print '"' . $rs["ordCountryTax"] . '",';
		if($origCountryID==2) print '"' . $rs["ordHSTTax"] . '",';
		print '"' . $rs["ordShipping"] . '",';
		print '"' . $rs["ordHandling"] . '",';
		print '"' . $rs["ordDiscount"] . '",';
		print '"' . strreplace('"','""',$rs["ordAddInfo"]) . '",';
		if(@$extracheckoutfield1 != '') print '"' . strreplace('"','""',$rs['ordCheckoutExtra1']) . '",';
		if(@$extracheckoutfield2 != '') print '"' . strreplace('"','""',$rs['ordCheckoutExtra2']) . '",';
		print '"' . strreplace('"','""',$rs["ordShipType"]) . '",';
		print '"' . strreplace('"','""',@$allstatus[$rs["ordStatus"]]) . '",';
		print '"' . strreplace('"','""',$rs["ordAuthStatus"]) . '",';
		print '"' . strreplace('"','""',$rs["ordTrackNum"]) . '",';
		print '"' . strreplace('"','""',$rs["ordInvoice"]) . '",';
		print '"' . strreplace('"','""',$discounttext) . '"';
		if(@$dumpccnumber){
			if($sslok==FALSE){
				print ",No SSL,No SSL,No SSL,No SSL,No SSL";
			}else{
				$result2=ect_query("SELECT ordCNum,ordPayProvider FROM orders WHERE ordID=" . $rs["ordID"]) or ect_error();
				$rs2=ect_fetch_assoc($result2);
				$ordCNum=$rs2["ordCNum"];
				$encryptmethod=strtolower(@$encryptmethod);
				if(trim($ordCNum)=="" || is_null($ordCNum) || $rs2['ordPayProvider']!=10){
					print ',"(no data)","","","",""';
				}elseif($encryptmethod=="mcrypt"){
					if(@$mcryptalg=="") $mcryptalg=MCRYPT_BLOWFISH;
					$td=mcrypt_module_open($mcryptalg, '', 'cbc', '');
					$thekey=@$ccencryptkey;
					$thekey=substr($thekey, 0, mcrypt_enc_get_key_size($td));
					$cnumarr=explode(" ", $ordCNum);
					$iv=@$cnumarr[0];
					$iv=@pack("H" . strlen($iv), $iv);
					$ordCNum=@pack("H" . strlen(@$cnumarr[1]), @$cnumarr[1]);
					mcrypt_generic_init($td, $thekey, $iv);
					$cnumarr=explode("&", mdecrypt_generic($td, $ordCNum));
					mcrypt_generic_deinit($td);
					mcrypt_module_close($td);
					if(is_array($cnumarr)){
						print ',"""' . $cnumarr[0] . '"""';
						print ',"""' . @$cnumarr[1] . '"""';
						print ',"' . @$cnumarr[2] . '"';
						print ',"' . @$cnumarr[3] . '"';
						print ',"' . urldecode(@$cnumarr[4]) . '"';
					}else
						print ',"(no data)","","","",""';
				}elseif($encryptmethod=="none"){
					$cnumarr=explode("&",$ordCNum);
					if(is_array($cnumarr)){
						print ',"""' . $cnumarr[0] . '"""';
						print ',"""' . @$cnumarr[1] . '"""';
						print ',"' . @$cnumarr[2] . '"';
						print ',"' . @$cnumarr[3] . '"';
						print ',"' . urldecode(@$cnumarr[4]) . '"';
					}else
						print ',"(no data)","","","",""';
				}
				ect_free_result($result2);
			}
		}
		if($hasdetails){
			$theOptions="";
			$thePriceDiff=0;
			$result2=ect_query("SELECT coPriceDiff,coOptGroup,coCartOption FROM cartoptions WHERE coCartID=" . $rs['cartID'] . ' ORDER BY coID') or ect_error();
			while($rs2=ect_fetch_assoc($result2)){
				$theOptions.=',' . '"' . strreplace('"','""',$rs2['coOptGroup']) . ' - ' . strreplace('"','""',$rs2['coCartOption']) . '"';
				$thePriceDiff+=$rs2['coPriceDiff'];
			}
			print ',"' . strreplace('"','""',$rs['cartProdId']) . '"';
			print ',"' . strreplace('"','""',$rs['cartProdName']) . '"';
			print ',' . ($rs['cartProdPrice'] + $thePriceDiff);
			print ',' . $rs['cartQuantity'];
			print $theOptions;
			ect_free_result($result2);
		}
		print "\r\n";
	}
	ect_free_result($result);
}
?>