<?php
//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
if(@$storesessionvalue=="") $storesessionvalue="virtualstore".time();
if(@$_SESSION['loggedon']!=$storesessionvalue||@$GLOBALS['disallowlogin']||!@$GLOBALS['incfunctionsdefined']) exit;
function dbencodeimage($imurl){
	$imurl=str_replace('\\','/',$imurl);
	$imurl=str_replace(array('|','<','>','?'),array('%7C','%3C','%3E','%3F'),$imurl);
	$imurl=str_replace(array('prodimages/','.gif','.jpg','.png'),array('|','<','>','?'),$imurl);
	return(str_replace("'","\'",$imurl));
}
if(getget("act")=="delimages"){
	ob_clean();
	$sSQL="DELETE FROM productimages WHERE imageSrc='".escape_string(getget("iu"))."'";
	ect_query($sSQL) or ect_error();
	print getget("iname");
	exit;
}elseif(getget("getprodfromimage")!=''){
	ob_clean();
	$sSQL="SELECT imageProduct FROM productimages WHERE imageSrc='".escape_string(getget("getprodfromimage"))."' LIMIT 0,1";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)) print $rs['imageProduct'];
	ect_free_result($result);
	exit;
}
function gobackhome(){
	print '<div style="margin:20px;text-align:center"><input type="button" value="Please click here to go back to the DB Utility Home Screen" onclick="document.location=\'admindbutility.php\'" /></div>';
}
?>
<script>
function editproduct(pid){
	document.getElementById('postform').action="adminprods.php";
	document.getElementById('postform').target="dbedit";
	document.getElementById('control1').name="id";
	document.getElementById('control1').value=pid;
	document.getElementById('control2').name="act";
	document.getElementById('control2').value="modify";
	document.getElementById('control3').name="posted";
	document.getElementById('control3').value="1";
	document.getElementById('postform').submit();
}
function fixsection(tact){
	document.getElementById('postform').action="admindbutility.php";
	document.getElementById('postform').target="";
	document.getElementById('control1').name="mainaction";
	document.getElementById('control1').value="checkdatabase";
	document.getElementById('control2').name="subaction";
	document.getElementById('control2').value=tact;
	document.getElementById('postform').submit();
}
</script>
<form id="postform" method="post" action="">
<input type="hidden" id="control1" value="" />
<input type="hidden" id="control2" value="" />
<input type="hidden" id="control3" value="" />
</form>
<?php
@set_time_limit(3600);
if(@$GLOBALS['ectdemostore']){ ?>
<div style="padding:30px 0px">This function has been disabled for the demo store.</div>
<?php
}elseif(getpost("mainaction")=="removestocknotify"){
	$sSQL="DELETE FROM notifyinstock";
	ect_query($sSQL) or ect_error();
	print '<div style="margin:40px;text-align:center">All done!!.</div>';
	gobackhome();
}elseif(getpost("mainaction")=="stateabbrev"){
	if(getpost("subaction")=="dostatetoabbrev"){
		ect_query("UPDATE address SET addState='AL' WHERE addState='Alabama' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='AK' WHERE addState='Alaska' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='AB' WHERE addState='Alberta' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='AZ' WHERE addState='Arizona' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='AR' WHERE addState='Arkansas' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='BC' WHERE addState='British Columbia' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='CA' WHERE addState='California' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='CO' WHERE addState='Colorado' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='CT' WHERE addState='Connecticut' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='DE' WHERE addState='Delaware' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='DC' WHERE addState='District Of Columbia' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='FL' WHERE addState='Florida' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='GA' WHERE addState='Georgia' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='HI' WHERE addState='Hawaii' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='ID' WHERE addState='Idaho' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='IL' WHERE addState='Illinois' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='IN' WHERE addState='Indiana' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='IA' WHERE addState='Iowa' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='KS' WHERE addState='Kansas' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='KY' WHERE addState='Kentucky' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='LA' WHERE addState='Louisiana' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='ME' WHERE addState='Maine' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='MB' WHERE addState='Manitoba' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='MD' WHERE addState='Maryland' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='MA' WHERE addState='Massachusetts' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='MI' WHERE addState='Michigan' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='MN' WHERE addState='Minnesota' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='MS' WHERE addState='Mississippi' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='MO' WHERE addState='Missouri' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='MT' WHERE addState='Montana' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='NE' WHERE addState='Nebraska' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='NV' WHERE addState='Nevada' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='NB' WHERE addState='New Brunswick' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='NH' WHERE addState='New Hampshire' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='NJ' WHERE addState='New Jersey' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='NM' WHERE addState='New Mexico' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='NY' WHERE addState='New York' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='NF' WHERE addState='Newfoundland' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='NC' WHERE addState='North Carolina' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='ND' WHERE addState='North Dakota' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='NT' WHERE addState='Northwest Territories' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='NS' WHERE addState='Nova Scotia' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='NU' WHERE addState='Nunavut' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='OH' WHERE addState='Ohio' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='OK' WHERE addState='Oklahoma' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='ON' WHERE addState='Ontario' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='OR' WHERE addState='Oregon' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='PA' WHERE addState='Pennsylvania' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='PE' WHERE addState='Prince Edward Island' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='QC' WHERE addState='Quebec' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='RI' WHERE addState='Rhode Island' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='SK' WHERE addState='Saskatchewan' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='SC' WHERE addState='South Carolina' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='SD' WHERE addState='South Dakota' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='TN' WHERE addState='Tennessee' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='TX' WHERE addState='Texas' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='UT' WHERE addState='Utah' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='VT' WHERE addState='Vermont' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='VA' WHERE addState='Virginia' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='WA' WHERE addState='Washington' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='WV' WHERE addState='West Virginia' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='WI' WHERE addState='Wisconsin' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='WY' WHERE addState='Wyoming' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='YT' WHERE addState='Yukon' AND addCountry IN ('United States of America','Canada','USA')");
		
		print '<div style="margin:40px;text-align:center">All done!!.</div>';
	}elseif(getpost("subaction")=="doabbrevtostate"){
	
		ect_query("UPDATE address SET addState='Alabama' WHERE addState='AL' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Alaska' WHERE addState='AK' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Alberta' WHERE addState='AB' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Arizona' WHERE addState='AZ' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Arkansas' WHERE addState='AR' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='British Columbia' WHERE addState='BC' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='California' WHERE addState='CA' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Colorado' WHERE addState='CO' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Connecticut' WHERE addState='CT' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Delaware' WHERE addState='DE' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='District Of Columbia' WHERE addState='DC' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Florida' WHERE addState='FL' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Georgia' WHERE addState='GA' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Hawaii' WHERE addState='HI' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Idaho' WHERE addState='ID' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Illinois' WHERE addState='IL' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Indiana' WHERE addState='IN' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Iowa' WHERE addState='IA' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Kansas' WHERE addState='KS' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Kentucky' WHERE addState='KY' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Louisiana' WHERE addState='LA' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Maine' WHERE addState='ME' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Manitoba' WHERE addState='MB' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Maryland' WHERE addState='MD' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Massachusetts' WHERE addState='MA' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Michigan' WHERE addState='MI' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Minnesota' WHERE addState='MN' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Mississippi' WHERE addState='MS' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Missouri' WHERE addState='MO' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Montana' WHERE addState='MT' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Nebraska' WHERE addState='NE' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Nevada' WHERE addState='NV' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='New Brunswick' WHERE addState='NB' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='New Hampshire' WHERE addState='NH' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='New Jersey' WHERE addState='NJ' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='New Mexico' WHERE addState='NM' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='New York' WHERE addState='NY' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Newfoundland' WHERE addState='NF' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='North Carolina' WHERE addState='NC' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='North Dakota' WHERE addState='ND' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Northwest Territories' WHERE addState='NT' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Nova Scotia' WHERE addState='NS' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Nunavut' WHERE addState='NU' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Ohio' WHERE addState='OH' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Oklahoma' WHERE addState='OK' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Ontario' WHERE addState='ON' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Oregon' WHERE addState='OR' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Pennsylvania' WHERE addState='PA' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Prince Edward Island' WHERE addState='PE' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Quebec' WHERE addState='QC' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Rhode Island' WHERE addState='RI' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Saskatchewan' WHERE addState='SK' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='South Carolina' WHERE addState='SC' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='South Dakota' WHERE addState='SD' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Tennessee' WHERE addState='TN' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Texas' WHERE addState='TX' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Utah' WHERE addState='UT' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Vermont' WHERE addState='VT' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Virginia' WHERE addState='VA' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Washington' WHERE addState='WA' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='West Virginia' WHERE addState='WV' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Wisconsin' WHERE addState='WI' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Wyoming' WHERE addState='WY' AND addCountry IN ('United States of America','Canada','USA')");
		ect_query("UPDATE address SET addState='Yukon' WHERE addState='YT' AND addCountry IN ('United States of America','Canada','USA')");
		
		print '<div style="margin:40px;text-align:center">All done!!.</div>';
	}else{
		print '<form method="post" action="admindbutility.php">';
		print whv("mainaction","stateabbrev") . whv("subaction","dostatetoabbrev");
		print '<div style="text-align:center;padding:20px"><input type="submit" value="Convert State Names to Abbreviations" /></div>';
		print '</form>';
		
		print '<form method="post" action="admindbutility.php">';
		print whv("mainaction","stateabbrev") . whv("subaction","doabbrevtostate");
		print '<div style="text-align:center;padding:20px"><input type="submit" value="Convert State Abbreviations to Names" /></div>';
		print '</form>';
	}
	gobackhome();
}elseif(getpost("mainaction")=='sizeofrow'){
	$sSQL="SELECT COLUMN_NAME, COLUMN_TYPE, CHARACTER_MAXIMUM_LENGTH FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='admin'";
	$result2=ect_query($sSQL) or ect_error();
	$row_tot=0;
	print '<table>';
	while($rs2=ect_fetch_assoc($result2)){
		$row_tot+=(is_null($rs2['CHARACTER_MAXIMUM_LENGTH']) || (float)$rs2['CHARACTER_MAXIMUM_LENGTH']>1000 ? 0 : $rs2['CHARACTER_MAXIMUM_LENGTH']);
		print '<tr><td>' . $rs2['COLUMN_NAME'] . '</td>
			<td>' . $rs2['COLUMN_TYPE'] . '</td>
			<td>' . (is_null($rs2['CHARACTER_MAXIMUM_LENGTH']) || (float)$rs2['CHARACTER_MAXIMUM_LENGTH']>1000 ? '-' : (float)$rs2['CHARACTER_MAXIMUM_LENGTH']) . '</td>
			<td>' . $row_tot . '</td>
			</tr>';
	}
	print '</table>';
	print '<p>ROW TOT: ' . $row_tot . '</p>';
}elseif(getpost("mainaction")=='dostorageengine'){
	$sSQL="SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='MyISAM'";
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$tbl=$rs['TABLE_NAME'];
		$sSQL="ALTER TABLE " . $tbl . " ENGINE=INNODB";
		ect_query($sSQL) or ect_error();
	}
	print '<div style="margin:20px;text-align:center">All done!!.</div>';
	gobackhome();
}elseif(getpost("mainaction")=='storageengine'){
	$sSQL='SELECT TABLE_NAME, ENGINE from information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE()';
	$result=ect_query($sSQL) or ect_error();
	$indexarr=[];
	print '<h2>These are the storage engines currently used</h2>';
	print '<div class="ecttable" style="width:80%"><div class="ecttablerow" style="font-weight:bold"><div>Table Name</div><div>Storage Engine</div></div>';
	while($rs=ect_fetch_assoc($result)){
		print '<div class="ecttablerow"><div>' . $rs['TABLE_NAME'] . '</div><div>' . $rs['ENGINE'] . '</div></div>';
	}
	print '</div>';
	print '<form method="post" action="admindbutility.php">';
	print whv('mainaction','dostorageengine');
	print '<div style="text-align:center;padding:20px"><input type="submit" value="Change to InnoDB" /></div>';
	print '</form>';
	gobackhome();
}elseif(getpost("mainaction")=="discountstats"){
	if(getpost("subaction")=='dodiscountstats'){
		$cpnarray=[];
		$maxcpnindex=0;
		$sSQL="SELECT cpnID,cpnName,cpnName2,cpnName3 FROM coupons";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			$cpnarray[$maxcpnindex]['cpnID']=$rs['cpnID'];
			$cpnarray[$maxcpnindex]['cpnName']=$rs['cpnName'];
			$cpnarray[$maxcpnindex]['cpnName2']=$rs['cpnName2'];
			$cpnarray[$maxcpnindex]['cpnName3']=$rs['cpnName3'];
			$maxcpnindex++;
		}
		$sSQL="SELECT ordID,cpaCpnID,ordDiscountText FROM orders LEFT JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID WHERE (ordDiscountText<>'' AND NOT ordDiscountText IS NULL) AND cpaCpnID IS NULL";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			$orddiscounttext=str_replace('<br />','<br>',$rs['ordDiscountText']);
			$orddiscountarray=explode('<br>',$orddiscounttext);
			foreach($orddiscountarray as $key=>$val){
				for($index=0;$index<$maxcpnindex;$index++){
					if($val!='' && ($val==$cpnarray[$index]['cpnName'] || $val==$cpnarray[$index]['cpnName2'] || $val==$cpnarray[$index]['cpnName3'])){
						$sSQL="INSERT INTO couponsapplied (cpaCpnID,cpaOrdID,cpaAmount,cpaTxt) VALUES (" . $cpnarray[$index]['cpnID'] . "," . $rs['ordID'] . ",0,'" . escape_string($cpnarray[$index]['cpnName']) . "')";
						ect_query($sSQL);
						break;
					}
				}
			}
		}
		print '<div style="text-align:center;padding:80px">Discounts have been updated.</div>';
	}else{
		$sSQL="SELECT COUNT(ordID) AS thecount,cpaCpnID FROM orders LEFT JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID WHERE (ordDiscountText<>'' AND NOT ordDiscountText IS NULL) AND cpaCpnID IS NULL";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			print '<div style="text-align:center;padding:80px">There are ' . $rs['thecount'] . ' orders where the discount stats may need updating.</div>';
			print '<form method="post" action="admindbutility.php">';
			print whv('mainaction','discountstats') . whv('subaction','dodiscountstats');
			print '<div style="text-align:center;padding:20px"><input type="submit" value="Update Discount Stats" /></div>';
			print '</form>';
		}else{
			print '<div style="text-align:center;padding:80px">There are no orders where the discount stats need updating.</div>';
		}
	}
	gobackhome();
}elseif(getpost("mainaction")=="dupindexes"){
	$sSQL="SELECT DISTINCT TABLE_NAME, COLUMN_NAME, INDEX_NAME, SEQ_IN_INDEX FROM INFORMATION_SCHEMA.STATISTICS WHERE SEQ_IN_INDEX=1 AND INDEX_NAME<>'PRIMARY' AND TABLE_SCHEMA=DATABASE()";
	$result=ect_query($sSQL) or ect_error();
	$indexarr=[];
	while($rs=ect_fetch_assoc($result)){
		$indexarr[] = $rs;
	}
	
	if(getpost("subaction")=='deldupindexes'){
		for($index=0; $index<count($indexarr); $index++){
			$trs = $indexarr[$index];
			for($index2=0; $index2<count($indexarr); $index2++){
				if($index!=$index2){
					$trs2 = $indexarr[$index2];
					if($trs['TABLE_NAME']==$trs2['TABLE_NAME'] && $trs['COLUMN_NAME']==$trs2['COLUMN_NAME']){
						if($trs['INDEX_NAME']=='PRIMARY' || $trs['INDEX_NAME'].'_2'==$trs2['INDEX_NAME']){
							$sSQL='ALTER TABLE ' .$trs['TABLE_NAME'] . ' DROP INDEX ' .$trs2['INDEX_NAME'];
							ect_query($sSQL) or ect_error();
						}
					}
				}
			}
		}
		print '<div style="text-align:center;padding:80px">Duplicate indexes have been deleted</div>';
	}else{
		$headermessage='<h2>The following indexes are duplicates and could be removed</h2><div class="ecttable" style="width:80%"><div class="ecttablerow" style="font-weight:bold"><div>Table Name</div><div>Column Name</div><div>Index Name</div><div>Duplicate Index Name</div></div>';
		$hasdupindex=FALSE;
		for($index=0; $index<count($indexarr); $index++){
			$trs = $indexarr[$index];
			for($index2=0; $index2<count($indexarr); $index2++){
				if($index!=$index2){
					$trs2 = $indexarr[$index2];
					if($trs['TABLE_NAME']==$trs2['TABLE_NAME'] && $trs['COLUMN_NAME']==$trs2['COLUMN_NAME']){
						if($trs['INDEX_NAME']=='PRIMARY' || $trs['INDEX_NAME'].'_2'==$trs2['INDEX_NAME']){
							print $headermessage;
							$headermessage='';
							$hasdupindex=TRUE;
							print '<div class="ecttablerow"><div>' . $trs['TABLE_NAME'] . '</div><div>' . $trs['COLUMN_NAME'] . '</div><div>' . $trs['INDEX_NAME'] . '</div><div>' . $trs2['INDEX_NAME'] . '</div></div>';
						}
					}
				}
			}
		}
		if($hasdupindex){
			print '</div>' . "\r\n";
			print '<form method="post" action="admindbutility.php">';
			print whv('mainaction','dupindexes') . whv('subaction','deldupindexes');
			print '<div style="text-align:center;padding:20px"><input type="submit" value="Delete Duplicate Indexes" /></div>';
			print '</form>';
		}else{
			print '<div style="text-align:center;padding:80px">There are no duplicate indexes</div>';
		}
	}
	gobackhome();
}elseif(getpost("mainaction")=="optimize"){
	$sSQL='SELECT table_name FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE()';
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		if(trim($rs['table_name'])!=''){
			print "<div>OPTIMIZING TABLE " . escape_string($rs['table_name']) . "</div>";
			flush();
			$sSQL="OPTIMIZE TABLE " . escape_string($rs['table_name']);
			ect_query($sSQL) or ect_error();
		}
	}
	gobackhome();
}elseif(getpost("mainaction")=="checkdatabase"){
	print '<div class="ectred ectdbsection">';
		print '<div style="padding:10px 0">Before fixing any database problems, please make sure you have made a backup of your database.</div>';
	print '</div>';
	// Fix Actions
	if(getpost("subaction")=='remmultisearch'){
		print '<div class="ectdbsection">';
		print '<div class="half_bottom">Fixing entries where the manufacturer attributes are not the same as that set for the product</div>';
		$sSQL="SELECT mSCpID,mSCscID FROM multisearchcriteria INNER JOIN products ON multisearchcriteria.mSCpID=products.pID AND products.pManufacturer<>multisearchcriteria.mSCscID INNER JOIN searchcriteria ON multisearchcriteria.mSCscID=searchcriteria.scID WHERE scGroup=0";
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0){
			while($rs=ect_fetch_assoc($result)){
				$sSQL="DELETE FROM multisearchcriteria WHERE mSCpID='" . escape_string($rs['mSCpID']) . "' AND mSCscID='" . escape_string($rs['mSCscID']) . "'";
				ect_query($sSQL) or ect_error();
			}
			print '<div class="half_bottom" style="color:#369105">Fixed - entries where the manufacturer attributes are not the same as that set for the product.</div>';
		}else
			print '<div class="half_bottom">No entries where the manufacturer attributes are not the same as that set for the product.</div>';
		print '</div>';
	}elseif(getpost("subaction")=='addmanuf'||getpost("subaction")=='remmanuf'){
		print '<div class="ectdbsection">';
		print '<div class="half_bottom">Inserting missing manufacturer entries in the Product Attributes table</div>';
		$manufacturers=array();
		if(getpost("subaction")!='remmanuf'){
			$sSQL="SELECT scID FROM searchcriteria WHERE scGroup=0";
			$result=ect_query($sSQL) or ect_error();
			while($rs=ect_fetch_assoc($result)){
				$manufacturers[]=$rs['scID'];
			}
		}
		$sSQL="SELECT pID,pManufacturer FROM products LEFT JOIN multisearchcriteria ON products.pID=multisearchcriteria.mSCpID AND products.pManufacturer=multisearchcriteria.mSCscID WHERE pManufacturer<>0 AND mSCscID IS NULL";
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0){
			while($rs=ect_fetch_assoc($result)){
				if(in_array($rs['pManufacturer'],$manufacturers))
					$sSQL="INSERT INTO multisearchcriteria (mSCpID,mSCscID) VALUES ('" . escape_string($rs['pID']) . "','" . escape_string($rs['pManufacturer']) . "')";
				else
					$sSQL="UPDATE products SET pManufacturer=0 WHERE pID='" . escape_string($rs['pID']) . "'";
				ect_query($sSQL) or ect_error();
			}
			print '<div class="half_bottom" style="color:#369105">Fixed - missing manufacturer entries in the Product Attributes table.</div>';
		}else
			print '<div class="half_bottom">No missing manufacturer entries in the Product Attributes table.</div>';
		print '</div>';
	}elseif(getpost("subaction")=='missmscp'){
		print '<div class="ectdbsection">';
		print '<div class="half_bottom">Fixing entries in the multisearchcriteria table where the product does not exist</div>';
		$sSQL="SELECT mSCpID,mSCscID FROM multisearchcriteria LEFT JOIN products ON multisearchcriteria.mSCpID=products.pID WHERE products.pID IS NULL";
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0){
			while($rs=ect_fetch_assoc($result)){
				$sSQL="DELETE FROM multisearchcriteria WHERE mSCpID='" . escape_string($rs['mSCpID']) . "' AND mSCscID='" . escape_string($rs['mSCscID']) . "'";
				ect_query($sSQL) or ect_error();
			}
			print '<div class="half_bottom" style="color:#369105">Fixed - entries with missing products in multisearchcriteria table.</div>';
		}else
			print '<div class="half_bottom">No entries with missing products in multisearchcriteria table.</div>';
		print '</div>';
	}elseif(getpost("subaction")=='missmscc'){
		print '<div class="ectdbsection">';
		print '<div class="half_bottom">Fixing entries in the multisearchcriteria table where the Attribute does not exist</div>';
		$sSQL="SELECT mSCpID,mSCscID FROM multisearchcriteria LEFT JOIN searchcriteria ON multisearchcriteria.mSCscID=searchcriteria.scID WHERE searchcriteria.scID IS NULL";
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0){
			while($rs=ect_fetch_assoc($result)){
				$sSQL="DELETE FROM multisearchcriteria WHERE mSCpID='" . escape_string($rs['mSCpID']) . "' AND mSCscID='" . escape_string($rs['mSCscID']) . "'";
				ect_query($sSQL) or ect_error();
			}
			print '<div class="half_bottom" style="color:#369105">Fixed - entries with missing Attributes in multisearchcriteria table.</div>';
		}else
			print '<div class="half_bottom">No entries with missing Attributes in multisearchcriteria table.</div>';
		print '</div>';
	}elseif(getpost("subaction")=='mscdisplay'){
		print '<div class="ectdbsection">';
		print '<div class="half_bottom">Fixing entries where Display Setting is incorrect in the Product Attributes cache</div>';
		
		$sSQL="SELECT DISTINCT pID,pDisplay FROM products INNER JOIN multisearchcriteria ON products.pID=multisearchcriteria.mSCpID WHERE products.pDisplay<>multisearchcriteria.mscDisplay";
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0){
			while($rs=ect_fetch_assoc($result)){
				$sSQL="UPDATE multisearchcriteria SET mscDisplay='" . escape_string($rs['pDisplay']) . "' WHERE mSCpID='" . escape_string($rs['pID']) . "'";
				ect_query($sSQL) or ect_error();
			}
			print '<div class="half_bottom" style="color:#369105">Fixed - entries with incorrect Display Setting in Product Attributes table.</div>';
		}else
			print '<div class="half_bottom">No entries with incorrect Display Setting in Product Attributes table.</div>';
		print '</div>';
	}elseif(getpost("subaction")=='mscgroup'){
		print '<div class="ectdbsection">';
		print '<div class="half_bottom">Fixing incorrect values in the Product Attributes Group cache</div>';
		
		$sSQL="SELECT DISTINCT scID,scgOrder,scgTitle,scgTitle2,scgTitle3 FROM searchcriteria INNER JOIN searchcriteriagroup ON searchcriteria.scGroup=searchcriteriagroup.scgID WHERE searchcriteria.scGroupOrder<>searchcriteriagroup.scgOrder OR searchcriteria.scGroupTitle<>searchcriteriagroup.scgTitle OR searchcriteria.scGroupTitle2<>searchcriteriagroup.scgTitle2 OR searchcriteria.scGroupTitle3<>searchcriteriagroup.scgTitle3";
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0){
			while($rs=ect_fetch_assoc($result)){
				$sSQL="UPDATE searchcriteria SET scGroupOrder='" . escape_string($rs['scgOrder']) . "',scGroupTitle='" . escape_string($rs['scgTitle']) . "',scGroupTitle2='" . escape_string($rs['scgTitle2']) . "',scGroupTitle3='" . escape_string($rs['scgTitle3']) . "' WHERE scID='" . escape_string($rs['scID']) . "'";
				ect_query($sSQL) or ect_error();
			}
			print '<div class="half_bottom" style="color:#369105">Fixed - incorrect values in the Product Attributes Group cache.</div>';
		}else
			print '<div class="half_bottom">No incorrect values in the Product Attributes Group cache.</div>';
		print '</div>';
	}elseif(getpost("subaction")=='misspimg'){
		print '<div class="ectdbsection">';
		print '<div class="half_bottom">Fixing entries in the productimages table where the Product does not exist</div>';
		$sSQL="SELECT imageProduct FROM productimages LEFT JOIN products ON productimages.imageProduct=products.pID WHERE products.pID IS NULL";
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0){
			while($rs=ect_fetch_assoc($result)){
				$sSQL="DELETE FROM productimages WHERE imageProduct='" . escape_string($rs['imageProduct']) . "'";
				ect_query($sSQL) or ect_error();
			}
			print '<div class="half_bottom" style="color:#369105">Fixed - entries with missing Product in productimages table.</div>';
		}else
			print '<div class="half_bottom">No entries with missing Product in productimages table.</div>';
		print '</div>';
	}

	// Missing category / section
	print '<div class="ectdbsection" style="max-height:500px;overflow:auto">';
	print '<div class="half_bottom">Checking for products whose category / section is missing</div>';
	$sSQL="SELECT pID,pSection,sectionID FROM products LEFT JOIN sections ON products.pSection=sections.sectionID WHERE sectionID IS NULL LIMIT 0,100";
	$result=ect_query($sSQL) or ect_error();
	if(ect_num_rows($result)>0){
		print '<div class="ectred half_bottom">The following products link to a category which is not defined.</div>';
		print '<div class="ectdbtable"><div class="ectdbhead"><div class="ectdbheadrow">Product ID</div><div class="ectdbheadrow">Section ID</div><div class="ectdbheadrow">&nbsp;</div></div>';
		while($rs=ect_fetch_assoc($result)){
			print '<div class="ectdbrow_cnt"><div class="ectdbrow">' . $rs['pID'] . '</div><div class="ectdbrow">' . $rs['pSection'] . '</div><div class="ectdbrow"><input type="button" value="Edit Product" onclick="editproduct(\'' . jscheck($rs['pID']) . '\')" /></div></div>';
		}
		print '</div>';
	}else
		print '<div class="half_bottom" style="color:#369105">All ok!</div>';
	ect_free_result($result);
	print '</div>';
	
	// Category / section not a products section
	print '<div class="ectdbsection" style="max-height:500px;overflow:auto">';
	print '<div class="half_bottom">Checking for products whose category / section is not for products</div>';
	$sSQL="SELECT pID,pSection,sectionID FROM products INNER JOIN sections ON products.pSection=sections.sectionID WHERE rootSection<>1 LIMIT 0,100";
	$result=ect_query($sSQL) or ect_error();
	if(ect_num_rows($result)>0){
		print '<div class="ectred half_bottom">The following products link to a category which is not for products.</div>';
		print '<div class="ectdbtable"><div class="ectdbhead"><div class="ectdbheadrow">Product ID</div><div class="ectdbheadrow">Section ID</div><div class="ectdbheadrow">&nbsp;</div></div>';
		while($rs=ect_fetch_assoc($result)){
			print '<div class="ectdbrow_cnt"><div class="ectdbrow">' . $rs['pID'] . '</div><div class="ectdbrow">' . $rs['pSection'] . '</div><div class="ectdbrow"><input type="button" value="Edit Product" onclick="editproduct(\'' . jscheck($rs['pID']) . '\')" /></div></div>';
		}
		print '</div>';
	}else
		print '<div class="half_bottom" style="color:#369105">All ok!</div>';
	ect_free_result($result);
	print '</div>';
	
	// Manufacturer Not In Multisearchcriteria Table.
	print '<div class="ectdbsection">';
	print '<div class="half_bottom">Checking for products where the manufacturer set has no entry in the Product Attributes table</div>';
	$sSQL="SELECT COUNT(pID) AS thecount FROM products LEFT JOIN multisearchcriteria ON products.pID=multisearchcriteria.mSCpID AND products.pManufacturer=multisearchcriteria.mSCscID WHERE pManufacturer<>0 AND mSCscID IS NULL";
	$result=ect_query($sSQL) or ect_error();
	$thecount=0;
	if($rs=ect_fetch_assoc($result))
		$thecount=$rs['thecount'];
	if($thecount>0){
		print '<div class="ectred half_bottom">There are ' . $thecount . ' entries where the manufacturer set has no entry in the Product Attributes table.</div>';
		print '<div class="half_bottom"><input type="button" value="Remove manufacturer setting from these products." onclick="fixsection(\'remmanuf\')" /></div>';
		print '<div class="half_bottom"><input type="button" value="Add entry to Product Attributes table for these products." onclick="fixsection(\'addmanuf\')" /></div>';
	}else
		print '<div class="half_bottom" style="color:#369105">All ok!</div>';
	ect_free_result($result);
	print '</div>';
	
	// Multisearchcriteria Table Entry to Manufacturer not the same as products.
	print '<div class="ectdbsection">';
	print '<div class="half_bottom">Checking for manufacturer attributes which are not the same as that set for the product</div>';
	$sSQL="SELECT COUNT(mSCpID) AS thecount FROM multisearchcriteria INNER JOIN products ON multisearchcriteria.mSCpID=products.pID AND products.pManufacturer<>multisearchcriteria.mSCscID INNER JOIN searchcriteria ON multisearchcriteria.mSCscID=searchcriteria.scID WHERE scGroup=0";
	$result=ect_query($sSQL) or ect_error();
	$thecount=0;
	if($rs=ect_fetch_assoc($result))
		$thecount=$rs['thecount'];
	if($thecount>0){
		print '<div class="ectred half_bottom">There are ' . $thecount . ' entries where the manufacturer attributes are not the same as that set for the product.</div>';
		print '<div class="half_bottom"><input type="button" value="Remove these attribute entries." onclick="fixsection(\'remmultisearch\')" /></div>';
	}else
		print '<div class="half_bottom" style="color:#369105">All ok!</div>';
	ect_free_result($result);
	print '</div>';

	// Multisearchcriteria Product Missing.
	print '<div class="ectdbsection">';
	print '<div class="half_bottom">Checking for entries in the Product Attributes table where the product does not exist</div>';
	$sSQL="SELECT COUNT(mSCpID) AS thecount FROM multisearchcriteria LEFT JOIN products ON multisearchcriteria.mSCpID=products.pID WHERE products.pID IS NULL";
	$result=ect_query($sSQL) or ect_error();
	$thecount=0;
	if($rs=ect_fetch_assoc($result))
		$thecount=$rs['thecount'];
	if($thecount>0){
		print '<div class="ectred half_bottom">There are ' . $thecount . ' entries in the Product Attributes table where the product does not exist.</div>';
		print '<div class="half_bottom"><input type="button" value="Delete entries with missing products in multisearchcriteria table." onclick="fixsection(\'missmscp\')" /></div>';
	}else
		print '<div class="half_bottom" style="color:#369105">All ok!</div>';
	ect_free_result($result);
	print '</div>';
	
	// Multisearchcriteria Attribute Missing.
	print '<div class="ectdbsection">';
	print '<div class="half_bottom">Checking for entries in the Product Attributes table where the attribute does not exist</div>';
	$sSQL="SELECT COUNT(mSCscID) AS thecount FROM multisearchcriteria LEFT JOIN searchcriteria ON multisearchcriteria.mSCscID=searchcriteria.scID WHERE searchcriteria.scID IS NULL";
	$result=ect_query($sSQL) or ect_error();
	$thecount=0;
	if($rs=ect_fetch_assoc($result))
		$thecount=$rs['thecount'];
	if($thecount>0){
		print '<div class="ectred half_bottom">There are ' . $thecount . ' entries in the Product Attributes table where the attribute does not exist.</div>';
		print '<div class="half_bottom"><input type="button" value="Delete entries with missing sections in Product Attributes table." onclick="fixsection(\'missmscc\')" /></div>';
	}else
		print '<div class="half_bottom" style="color:#369105">All ok!</div>';
	ect_free_result($result);
	print '</div>';
	
	// Product Images entry has missing product
	print '<div class="ectdbsection">';
	print '<div class="half_bottom">Checking for entries in the Product Images table where the product does not exist</div>';
	$sSQL="SELECT COUNT(imageProduct) AS thecount FROM productimages LEFT JOIN products ON productimages.imageProduct=products.pID WHERE products.pID IS NULL";
	$result=ect_query($sSQL) or ect_error();
	$thecount=0;
	if($rs=ect_fetch_assoc($result))
		$thecount=$rs['thecount'];
	if($thecount>0){
		print '<div class="ectred half_bottom">There are ' . $thecount . ' entries in the Product Images table where the product does not exist.</div>';
		print '<div class="half_bottom"><input type="button" value="Delete entries with missing products in Product Attributes table." onclick="fixsection(\'misspimg\')" /></div>';
	}else
		print '<div class="half_bottom" style="color:#369105">All ok!</div>';
	ect_free_result($result);
	print '</div>';

	gobackhome();
}elseif(getpost("mainaction")=="buildcache"){
	$sSQL='UPDATE searchcriteria SET scGroupOrder=(SELECT scgOrder FROM searchcriteriagroup WHERE searchcriteriagroup.scgID=searchcriteria.scGroup),scGroupTitle=(SELECT scgTitle FROM searchcriteriagroup WHERE searchcriteriagroup.scgID=searchcriteria.scGroup),scGroupTitle2=(SELECT scgTitle2 FROM searchcriteriagroup WHERE searchcriteriagroup.scgID=searchcriteria.scGroup),scGroupTitle3=(SELECT scgTitle3 FROM searchcriteriagroup WHERE searchcriteriagroup.scgID=searchcriteria.scGroup) WHERE EXISTS (SELECT * FROM searchcriteriagroup WHERE searchcriteriagroup.scgID=searchcriteria.scGroup)';
	ect_query($sSQL) or print_sql_error();
	
	$sSQL='UPDATE multisearchcriteria SET mscDisplay=(SELECT pDisplay FROM products WHERE products.pID=multisearchcriteria.mSCpID) WHERE EXISTS (SELECT * FROM products WHERE products.pID=multisearchcriteria.mSCpID)';
	ect_query($sSQL) or print_sql_error();

	print '<div style="margin:20px;text-align:center">All done!!.</div>';
	gobackhome();
}elseif(getpost("mainaction")=="setcollation"){
	if(getpost("subaction")=="go" && getpost('collation_name')!=''){
		$charsetarray=explode('_',getpost('collation_name'));
		$thecharset=$charsetarray[0];
		print '<div style="margin:20px;text-align:center">Converting database to charset: ' . $thecharset . ', collation: ' . getpost('collation_name') . '.</div>';
		$sSQL="SELECT TABLE_NAME, TABLE_COLLATION FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE()";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			$sSQL='ALTER TABLE ' . $rs['TABLE_NAME'] . ' CONVERT TO CHARACTER SET ' . $thecharset . ' COLLATE ' . getpost('collation_name');
			ect_query($sSQL) or ect_error();
			// ALTER TABLE <table-name> CHARACTER SET utf8 COLLATE utf8_bin;
		}
		print '<div style="margin:20px;text-align:center">All done!!.</div>';
		print '<div style="margin:20px;text-align:center">Please click here to view your database tables new settings.</div>';
		print '<form id="collateform" method="post" action="admindbutility.php">';
		print whv('mainaction','setcollation');
		print '<div style="margin:20px;text-align:center"><input type="submit" value="View Database" /></div>';
		print '</form>';
	}else{
		print '<div style="margin-bottom:10px">Please select below only if you wish to change the collation for ALL the database tables and columns.</div>';
		print '<div style="margin-bottom:10px">The most commonly used collations are latin1_swedish_ci and utf8_general_ci.</div>';
		print '<div style="margin-bottom:10px;color:red">This is an advanced setting and we only recommend expert users, or those following instructions from Ecommerce Templates support make changes here.</div>';
		$sSQL='SELECT COLLATION_NAME,information_schema.COLLATIONS.CHARACTER_SET_NAME,DESCRIPTION FROM information_schema.COLLATIONS INNER JOIN information_schema.CHARACTER_SETS ON information_schema.COLLATIONS.CHARACTER_SET_NAME=information_schema.CHARACTER_SETS.CHARACTER_SET_NAME ORDER BY CHARACTER_SET_NAME,COLLATION_NAME';
		$result=ect_query($sSQL) or ect_error();
		$currcharset='';
		print '<form id="collateform" method="post" action="admindbutility.php">';
		print whv('mainaction','setcollation') . whv('subaction','go');
		print '<select size="1" name="collation_name" onchange="if(confirm(\'Are you sure you want to change the database charset / collation?\'))document.getElementById(\'collateform\').submit()">';
		print '<option value="">Please select a collation...</option>' . "\r\n";
		while($rs=ect_fetch_assoc($result)){
			if($currcharset!=$rs['CHARACTER_SET_NAME']){
				print '<optgroup label="' . $rs['CHARACTER_SET_NAME'] . '" title="' . $rs['DESCRIPTION'] . '">';
				$currcharset=$rs['CHARACTER_SET_NAME'];
			}
			print '<option value="' . $rs['COLLATION_NAME'] . '">' . $rs['COLLATION_NAME'] . '</option>' . "\r\n";
		}
		print '</select>';
		print '</form>';
		$sSQL="SELECT TABLE_NAME, TABLE_COLLATION FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE()";
		$result=ect_query($sSQL) or ect_error();
		print '<table>';
		while($rs=ect_fetch_assoc($result)){
			print '<tr><td><strong>' . $rs['TABLE_NAME'] . '</strong></td><td><strong>' . $rs['TABLE_COLLATION'] . '</strong></td></tr>';
			$sSQL="SELECT COLUMN_NAME, COLLATION_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='" . escape_string($rs['TABLE_NAME']) . "' AND COLUMN_TYPE LIKE '%VARCHAR%'";
			$result2=ect_query($sSQL) or ect_error();
			while($rs2=ect_fetch_assoc($result2)){
				print '<tr><td>' . $rs2['COLUMN_NAME'] . '</td><td>' . $rs2['COLLATION_NAME'] . '</td></tr>';
			}
		}
		print '</table>';
	}
	gobackhome();
}elseif(getpost("mainaction")=="reorderimages"){
	if(getpost("subaction")=="go"){ ?>
<table style="margin:0 auto">
<tr><td width="100%">
<?php	$sSQL="SELECT imageProduct,imageNumber,imageType FROM productimages ORDER BY imageProduct,imageType,imageNumber";
		$currImageType=-1;
		$currImageNumber=-1;
		$currImageProduct="";
		$expectedimagenumber=0;
		$numberreordered=0;
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			if($currImageProduct!=$rs['imageProduct'] || $currImageType!=$rs['imageType']){
				$expectedimagenumber=0;
				$currImageProduct=$rs['imageProduct'];
				$currImageType=$rs['imageType'];
			}
			if($rs['imageNumber']!=$expectedimagenumber){
				$sSQL="UPDATE productimages SET imageNumber=" . $expectedimagenumber . " WHERE imageProduct='" . escape_string($currImageProduct) . "' AND imageType=" . $currImageType . " AND imageNumber=" . $rs['imageNumber'];
				ect_query($sSQL) or ect_error();
				$numberreordered++;
			}
			$expectedimagenumber++;
		}
		print '<p>&nbsp;</p>';
		print '<p>&nbsp;</p>';
		if($numberreordered==0)
			print "<p>No images needed reordering.</p>";
		else
			print "<p>A total of " . $numberreordered . " images were reordered.</p>";
		print "<p>&nbsp;</p>";
		print "<p>&nbsp;</p>";
		gobackhome();
		ect_free_result($result);
?>
</td></tr>
</table>
<?php
	}else{
		$numimages=0;
		$sSQL="SELECT COUNT(*) AS numimages FROM productimages";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			if(! is_null($rs['numimages'])) $numimages=$rs['numimages'];
		} ?>
		<table style="margin:0 auto">
<tr><td width="100%">
<form action="admindbutility.php" method="post">
<input type="hidden" name="mainaction" value="reorderimages">
<input type="hidden" name="subaction" value="go">
<input type="hidden" name="posted" value="1">
<p>This script will check the order of the images in your Ecommerce Templates database ensuring they are in sequential order.</p>
<p>Please make sure you have backed up your site and database before proceeding.</p>
<p>&nbsp;</p>
<p>Please click below to start checking<?php if($numimages>0) print " <strong>(" . $numimages . " images)</strong>"?>.</p>
<p>&nbsp;</p>
<p><input style="background:#399908; color:#fff;cursor:pointer;padding:5px 10px;-moz-border-radius:10px;-webkit-border-radius:10px" type="submit" value="Reorder Images" /></p>
<p>&nbsp;</p>
</form>
<?php gobackhome() ?>
</td></tr>
</table>
<?php
	}
}elseif(getrequest("mainaction")=="checkimagerefs"){ ?>
<script>
function dodeleteimages(){
	if(confirm('Are you sure you want to delete these images?\n\nYou should make sure you have a backup before you continue.\n')){
		document.getElementById('subaction').value='dodeleteimages';
		document.getElementById('dodeleteimages').submit();
	}
}
function domoveimages(){
	if(confirm('Are you sure you want to move these images to the "unreferenced" folder?\n\nYou should make sure you have a backup before you continue.\n')){
		document.getElementById('subaction').value='domoveimages';
		document.getElementById('dodeleteimages').submit();
	}
}
function doarchiveimages(){
	if(confirm('Are you sure you want to move these images to the "archived" folder?\n\nYou should make sure you have a backup before you continue.\n')){
		document.getElementById('subaction').value='doarchiveimages';
		document.getElementById('dodeleteimages').submit();
	}
}
function docheckimages(){
	if(confirm('This can take a long time if you have a lot of images. Continue?\n')){
		document.getElementById('subaction').value='docheckimages';
		document.getElementById('dodeleteimages').submit();
	}
}
function donextbatch(){
	document.getElementById('dodeleteimages').submit();
}
function doalldone(){
	document.location='admindbutility.php?mainaction=checkimagerefs';
}
</script>
<?php
	$maxbatch=500;
	$startindex=0;
	$alldone=FALSE;
	if(getpost('batchsize')!='') $maxbatch=(int)getpost('batchsize');
	print '<div style="max-width:800px;margin:auto">';
	$fileexts='gif,jpg,png,jpeg,tif,gif,bmp';
	function isimagefile($fname){
		$lfname=strtolower(pathinfo($fname,PATHINFO_EXTENSION));
		return($lfname=='gif' || $lfname=='jpg' || $lfname=='png' || $lfname=='jpeg' || $lfname=='tif' || $lfname=='gif' || $lfname=='bmp');
	}
	if(@$GLOBALS['defaultprodimages']=='') $defaultprodimages='prodimages/'; else $defaultprodimages=$GLOBALS['defaultprodimages'];
	if(substr($defaultprodimages,0,1)=='/')
		$filepath=$_SERVER['DOCUMENT_ROOT'] . $defaultprodimages;
	else
		$filepath='../' . $defaultprodimages;
	$mappedfilepath=realpath($filepath);
	$direxists=$mappedfilepath!==FALSE;
	print '<p><strong>Current Product Images Path:</strong> ' . $filepath . '</p>';
	print '<div style="font-size:0.8em">If this location is incorrect then please set the parameter $defaultprodimages in your vsadmin/includes.php file.</div>';
	
	if(! $direxists){
		print '<h1 style="text-align:center;margin:40px 0">That directory does not exist</h1>';
	}else{
		$files=glob($mappedfilepath.'/*.*');
		$numchecked=0;
		$numfiles=count($files);
		$startindex=$numfiles-(int)getpost('filesremaining');
		if(FALSE){
			print 'numfilesatstart: ' . getpost('numfilesatstart') . "<br>";
			print 'filesremaining: ' . getpost('filesremaining') . "<br>";
			print 'batchsize: ' . $maxbatch . "<br>";
			print 'startindex: ' . $startindex . "<br>";
		}
		$numreferenced=0;
		$notreferenced=0;
		$time_start=microtime_ect_float();
		if(getpost("subaction")!=""){
			print '<div style="max-height:300px;overflow-y:auto;display:flex;flex-direction:column;border:1px solid lightgray;padding:10px;border-radius:10px;margin:30px 0">';
			if(getpost("subaction")=="dodeleteimages"){
				print "<h2>Starting Deleting Files</h2>\n";
				for($index=0;$index<$maxbatch;$index++){
					if($index+$startindex>=$numfiles){
						$alldone=TRUE;
						break;
					}
					$filename=$files[$index+$startindex];
					if(isimagefile($filename)){
						$basefilename=basename($filename);
						$sSQL="SELECT imageSrc FROM productimages WHERE imageSrc LIKE '" . escape_string($basefilename) . "' OR imageSrc LIKE '%/" . escape_string($basefilename) . "'";
						$result=ect_query($sSQL) or ect_error();
						$isfound=ect_num_rows($result)>0;
						ect_free_result($result);
						if(! $isfound){
							print "Deleting: " . $basefilename . "<br>";
							unlink($filename);
						}
					}
					if(($numchecked++ % 1000)==0){
						ob_flush();
						flush();
					}
				}
				$files=glob($mappedfilepath.'/*.*');
			}elseif(getpost("subaction")=="domoveimages"){
				@mkdir($mappedfilepath . DIRECTORY_SEPARATOR . 'unreferenced');
				print "<h2>Starting Moving Files</h2>\n";
				for($index=0;$index<$maxbatch;$index++){
					if($index+$startindex>=$numfiles){
						$alldone=TRUE;
						break;
					}
					$filename=$files[$index+$startindex];
					if(isimagefile($filename)){
						$basefilename=basename($filename);
						$sSQL="SELECT imageSrc FROM productimages WHERE imageSrc LIKE '" . escape_string($basefilename) . "' OR imageSrc LIKE '%/" . escape_string($basefilename) . "'";
						$result=ect_query($sSQL) or ect_error();
						$isfound=ect_num_rows($result)>0;
						ect_free_result($result);
						if(! $isfound){
							print "Moving: " . $basefilename . "<br>";
							rename($filename,$mappedfilepath . DIRECTORY_SEPARATOR . 'unreferenced' . DIRECTORY_SEPARATOR . $basefilename);
						}
					}
					if(($numchecked++ % 1000)==0){
						ob_flush();
						flush();
					}
				}
				$files=glob($mappedfilepath.'/*.*');
			}elseif(getpost("subaction")=="doarchiveimages"){
				@mkdir($mappedfilepath . DIRECTORY_SEPARATOR . 'archived');
				print "<h2>Starting Archiving Files</h2>\n";
				$sSQL="SELECT imageSrc FROM productimages_archive";
				$result=ect_query($sSQL) or ect_error();
				while($rs=ect_fetch_assoc($result)){
					$filename=$rs['imageSrc'];
					$basefilename=basename($filename);
					if(substr($filename,0,1)=='/')
						$filepath=$_SERVER['DOCUMENT_ROOT'] . $filename;
					else
						$filepath='../' . $filename;
					$filepath=realpath($filepath);
					if($filepath!=FALSE){
						print "Archiving: " . $basefilename . "<br>";
						rename($filepath,$mappedfilepath . DIRECTORY_SEPARATOR . 'archived' . DIRECTORY_SEPARATOR . $basefilename);
					}
				}
				ect_free_result($result);
				$alldone=TRUE;
				$files=glob($mappedfilepath.'/*.*');
			}elseif(getpost("subaction")=="docheckimages"){
				print '<h2>Check Unreferenced Images</h2>';
				for($index=0;$index<$maxbatch;$index++){
					if($index+$startindex>=$numfiles){
						$alldone=TRUE;
						break;
					}
					$filename=$files[$index+$startindex];
					if(isimagefile($filename)){
						$basefilename=basename($filename);
						$sSQL="SELECT imageSrc FROM productimages WHERE imageSrc LIKE '" . escape_string($basefilename) . "' OR imageSrc LIKE '%/" . escape_string($basefilename) . "'";
						$result=ect_query($sSQL) or ect_error();
						$isfound=ect_num_rows($result)>0;
						ect_free_result($result);
						if(! $isfound){
							print $basefilename . "<br>";
							$notreferenced++;
						}else
							$numreferenced++;
						if(($numchecked++ % 1000)==0){
							ob_flush();
							flush();
						}
					}
				}
				if($notreferenced==0)
					print '<p>== No unreferenced images ==</p>';
			}
			print "<p>Batch finished!</p>\n";
			print '</div>';
		}
		print '<div style="margin:15px 0">';
		$nowfiles=glob($mappedfilepath.'/*.*');
		print "<h2>Number of files in folder: " . count($nowfiles) . "</h2>";
?>
<form method="post" id="dodeleteimages" action="admindbutility.php">
<input type="hidden" name="mainaction" value="checkimagerefs">
<input type="hidden" name="numfilesatstart" value="<?php print $numfiles?>">
<input type="hidden" name="nextstartindex" value="<?php print $startindex+$maxbatch?>">
<input type="hidden" name="filesremaining" value="<?php print getpost("subaction")!=""?(int)getpost('filesremaining')-$maxbatch:$numfiles?>">
<input type="hidden" name="subaction" id="subaction" value="<?php print getpost('subaction')?>">
<?php
	if(count($files)>500 && !$alldone){
?>
<p>Perform actions in batches of:
<select size="1" name="batchsize">
<option value="">500</option>
<option value="1000"<?php if(getpost('batchsize')=='1000') print ' selected'?>>1000</option>
<option value="1500"<?php if(getpost('batchsize')=='1500') print ' selected'?>>1500</option>
<option value="2000"<?php if(getpost('batchsize')=='2000') print ' selected'?>>2000</option>
<option value="4000"<?php if(getpost('batchsize')=='4000') print ' selected'?>>4000</option>
<option value="5000"<?php if(getpost('batchsize')=='5000') print ' selected'?>>5000</option>
<option value="7500"<?php if(getpost('batchsize')=='7500') print ' selected'?>>7500</option>
<option value="1000000"<?php if(getpost('batchsize')=='1000000') print ' selected'?>>Unlimited</option>
</select>
</p>
<?php
	}
?>
</form>
<?php
		if(@$GLOBALS['allowdeleteimages']){
			if(getpost("subaction")!=""){
				if(!$alldone) print '<input type="button" value="Batch (' . ((int)($startindex / $maxbatch))+1 . ' of ' . ceil((int)getpost('numfilesatstart') / $maxbatch). ') - Next Batch" onclick="donextbatch()" style="margin:15px auto;max-width:600px;width:100%;display:block">';
				print '<input type="button" value="Done!" onclick="doalldone()" style="margin:15px auto;max-width:600px;width:100%;display:block">';
			}else{
				print '<input type="button" value="Check Unreferenced Images" onclick="docheckimages()" style="margin:15px auto;max-width:600px;width:100%;display:block">';
				print '<input type="button" value="Delete Unreferenced Images" onclick="dodeleteimages()" style="margin:15px auto;max-width:600px;width:100%;display:block">';
				print '<input type="button" value="Move Unreferenced Images to &quot;' . htmlspecials($defaultprodimages) . 'unreferenced/&quot;" onclick="domoveimages()" style="margin:15px auto;max-width:600px;width:100%;display:block">';
				print '<input type="button" value="Move Archived Images to &quot;' . htmlspecials($defaultprodimages) . 'archived/&quot;" onclick="doarchiveimages()" style="margin:15px auto;max-width:600px;width:100%;display:block">';
			}
		}else{
			print '<input type="button" value="Delete Unreferenced Images: DISABLED" disabled="disabled">';
			print '<div style="font-size:0.8em;margin-top:10px">To allow the automatic deletion of unreferenced images, please add the parameter "$allowdeleteimages=TRUE;" to your vsadmin/includes.php file.</div>';
		}
		print '</div>';
		if(getpost("subaction")!=""){
			print '<div style="font-size:0.9em">';
			print '<p><span style="font-weight:bold">Images referenced:</span> ' . $numreferenced . "</p>";
			print '<p><span style="font-weight:bold">Images NOT referenced:</span> ' . $notreferenced . "</p>";
			print '<p><span style="font-weight:bold">Time taken:</span> ' . round(microtime_ect_float()-$time_start,2) . ' seconds.</p>';
			print '</div>';
		}
		if(@$GLOBALS['allowdeleteimages']) print '<div style="font-size:0.8em;margin-top:10px">It is recommended that you remove the parameter "$allowdeleteimages=TRUE;" from your vsadmin/includes.php file after using this script.</div>';
	}
	gobackhome();
	print '</div>';
}elseif(getpost("mainaction")=="checkimages"){
	if(getpost("subaction")=="gohttp"){ ?>
<form id="viewform" method="post" action="adminprods.php" target="viewprodwindow">
<input type="hidden" name="posted" value="1" />
<input type="hidden" name="act" value="modify" />
<input type="hidden" id="viewprodid" name="id" value="" />
</form>
<script>
/* <![CDATA[ */
var foundimages=0, missingimages=0, imageindex=0, imagearray=[];
function displayproductcallback(){
	if(ajaxobj.readyState==4){
		var retvals=ajaxobj.responseText;
		if(retvals=='')
			alert("Product id could not be found.");
		else{
			document.getElementById('viewprodid').value=retvals;
			document.getElementById('viewform').submit();
		}
	}
}
function displayproduct(imind){
	ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
	ajaxobj.onreadystatechange=displayproductcallback;
	ajaxobj.open("GET", "admindbutility.php?getprodfromimage="+encodeURIComponent(imagearray[imind]),true);
	ajaxobj.send(null);
}
function chkExists(imageurl){
	ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
	if(imageurl.substr(0,7).toLowerCase()!='http://'&&imageurl.substr(0,8).toLowerCase()!='https://'&&imageurl.substr(0,1)!='/') imageurl='../'+imageurl;
	ajaxobj.open('HEAD',imageurl,false);
	try{
		ajaxobj.send(null);
		return ajaxobj.status!=404;
	}catch(err){
		return false;
	}
}
function addtotable(imageurl,isfound){
	imagearray[imageindex]=imageurl;
	imgtable = document.getElementById('imagestable');
	newrow=imgtable.insertRow(-1);
	newrow.id='trX'+imageindex;
	newcell=newrow.insertCell(-1);
	newcell.style.border='1px solid';
	newcell.align='center';
	newcell.innerHTML='<input type="checkbox" title="Select" name="selectimage" value="'+imageindex+'" id="selectimage'+imageindex+'" />';
	newcell=newrow.insertCell(-1);
	newcell.style.border='1px solid';
	newcell.innerHTML=imageurl
	newcell=newrow.insertCell(-1);
	newcell.style.border='1px solid';
	newcell.align='center';
	newcell.innerHTML='<input type="button" value="Display Product" onclick="displayproduct(\''+imageindex+'\')" />';
	imageindex++;
}
function updatefound(){
	document.getElementById('foundspan').innerHTML=foundimages;
	document.getElementById('missingspan').innerHTML=missingimages;
	document.getElementById('checkedspan').innerHTML=foundimages+missingimages;
}
function vsdecimg(timg){
	return decodeURIComponent(timg.replace('|','prodimages/').replace('<','.gif').replace('>','.jpg').replace('?','.png'));
}
function ChK(imageurl){
	imageurl=vsdecimg(imageurl);
	if(chkExists(imageurl)){
		foundimages++;
	}else{
		missingimages++;
		addtotable(imageurl,false);
	}
	updatefound();
}
var ajaxobj;
function confirmdelimg(){
	if(ajaxobj.readyState==4){
		var retvals=ajaxobj.responseText;
		var row=document.getElementById('trX'+retvals);
		row.parentNode.removeChild(row);
	}
}
function deleteimages(deleteall){
	var selectimg=document.getElementById('imagesform').getElementsByTagName("input");
	var numselected=0;
	var idstack=[];
	for(var myobjind in selectimg){
		var myobj=selectimg[myobjind];
		if(myobj.id&&myobj.id.substr(0,11)=='selectimage'){
			if(myobj.checked||deleteall){
				var theid=myobj.id.substr(11);
				idstack.push(myobj.id.substr(11));
				numselected++;
			}
		}
	}
	if(!deleteall&&numselected==0){
		alert('No Images Selected.');
		return;
	}else{
		for(var myobjind in idstack){
			var theid=idstack[myobjind];
			ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
			ajaxobj.onreadystatechange=confirmdelimg;
			ajaxobj.open("GET", "admindbutility.php?act=delimages&iname="+theid+"&iu="+encodeURIComponent(imagearray[theid]),false);
			ajaxobj.send(null);
		}
	}
}
function finishup(shownextpage,currpage,numpages){
	imgtable = document.getElementById('imagestable');
	newrow=imgtable.insertRow(-1);
	newcell=newrow.insertCell(-1);
	newcell.style.border='1px solid';
	newcell.height=35;
	newcell.align='center';
	newcell.colSpan=3;
	if(foundimages+missingimages>0&&eCTtotalTime>0.01)
		document.getElementById('totaltimespan').innerHTML="("+(Math.round(eCTtotalTime/10)/100)+" seconds / "+((Math.round(((foundimages+missingimages)/eCTtotalTime)*100000))/100)+" per second)";
	if(imageindex==0){
		newcell.innerHTML='No broken image links detected';
	}else
		newcell.innerHTML='<input type="button" value="Delete Selected" onclick="deleteimages(false)" />&nbsp;&nbsp;<input type="button" value="Delete All" onclick="deleteimages(true)" />';
	if(shownextpage) newcell.innerHTML+='&nbsp;&nbsp;<input type="button" value="Next Batch ('+(currpage+1)+' of '+numpages+')" onclick="document.getElementById(\'nextbatchform\').submit()" />';
}
function checkall(tobj){
	var selectimg=document.getElementById('imagesform').getElementsByTagName("input");
	for(var myobjind in selectimg){
		var myobj=selectimg[myobjind];
		if(myobj.id&&myobj.id.substr(0,11)=='selectimage') myobj.checked=tobj.checked
	}
}
/* ]]> */
</script>
<form method="post" id="nextbatchform" action="admindbutility.php">
<input type="hidden" name="pg" value="<?php if(! is_numeric(getpost("pg"))) print 2; else print (int)getpost("pg")+1?>" />
<input type="hidden" name="batchesof" value="<?php print getpost("batchesof")?>" />
<input type="hidden" name="mainaction" value="checkimages">
<input type="hidden" name="subaction" value="gohttp">
<input type="hidden" name="posted" value="1">
</form>
<form method="post" name="imagesform" id="imagesform" action="">
<table id="imagestable" name="imagestable" class="imagestable" width="600" cellspacing="2" cellpadding="2" style="border-collapse:collapse;border:1px solid black;margin:0 auto">
<tr height="35"><td colspan="3" align="center" style="border:1px solid"><strong>Checked:</strong> <span id="checkedspan">0</span>, <strong>Found:</strong> <span id="foundspan">0</span>, <strong>Not Found:</strong> <span id="missingspan">0</span> <span id="totaltimespan"></span></td></tr>
<tr><td align="center" style="border:1px solid"><input type="checkbox" title="Select All" onchange="checkall(this)" /></td><td style="border:1px solid"><strong>Missing Image URL</strong></td><td align="center" style="border:1px solid"><strong>Display Product</strong></td></tr>
</table>
</form>
<?php	$fijs='<script>/* <![CDATA[ */' . "\r\n";
		$fijs.="var eCTtimer=new Date().getTime();\r\n";
		$sSQL="SELECT DISTINCT imageSrc FROM productimages ORDER BY imageSrc";
		if(is_numeric(getpost("batchesof"))) $batchesof=(int)getpost("batchesof"); else $batchesof="";
		$iNumOfPages=1;
		$CurPage=1;
		if(is_numeric(getpost("pg"))) $CurPage=(int)getpost("pg");
		$success=TRUE;
		$tpagesize=0;
		if($batchesof!='') $sSQL=preg_replace('/SELECT/','SELECT SQL_CALC_FOUND_ROWS',$sSQL,1) . ' LIMIT ' . ($batchesof*($CurPage-1)) . ', ' . $batchesof;
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)==0){
			$success=FALSE;
			$iNumOfPages=0;
		}else{
			$success=TRUE;
			$tpagesize=$batchesof;
			if($batchesof!=''){
				$numresults=ect_query('SELECT FOUND_ROWS() AS bar') or ect_error();
				$rs=ect_fetch_assoc($numresults);
				$iNumOfPages=ceil($rs['bar']/$batchesof);
				ect_free_result($numresults);
			}
		}
		while($rs=ect_fetch_assoc($result)){
			$fijs.="ChK('".dbencodeimage($rs['imageSrc'])."');\r\n";
		}
		$fijs.="var eCTtotalTime=new Date().getTime()-eCTtimer;" . "\r\n";
		$fijs.="finishup(".($CurPage<$iNumOfPages?"true":"false").",".$CurPage.",".$iNumOfPages.");\r\n";
		$fijs.="/* ]]> */</script>\r\n";
		print $fijs;
		gobackhome();
	}elseif(getpost("subaction")=="godisk"){
		if(@$GLOBALS['defaultprodimages']=='') $defaultprodimages='prodimages/'; else $defaultprodimages=$GLOBALS['defaultprodimages'];
		if(substr($defaultprodimages,0,1)=='/')
			$filepath=$_SERVER['DOCUMENT_ROOT'] . $defaultprodimages;
		else
			$filepath='../' . $defaultprodimages;
		$mappedfilepath=realpath($filepath);
		$direxists=$mappedfilepath!==FALSE;
		if(! $direxists){
			print '<h1 style="text-align:center;margin:40px 0">That directory (' . $defaultprodimages . ') does not exist</h1>';
		}else{
			print '<h1 style="text-align:center;margin:40px 0">Checking for images in: ' . $mappedfilepath . '</h1>';
			print '<table>';
			$sSQL="SELECT imageProduct,imageSrc FROM productimages ORDER BY imageProduct";
			$result=ect_query($sSQL) or ect_error();
			$rowcounter=0;
			$badlinks=0;
			$foundinarchive=0;
			while($rs=ect_fetch_assoc($result)){
				if(strpos($rs['imageSrc'],':')===FALSE){
					$basefilename=basename($rs['imageSrc']);
					$filename=$mappedfilepath . DIRECTORY_SEPARATOR . $basefilename;
					if(!file_exists($filename)){
						print '<tr><td>' . $rs['imageProduct'] . '</td><td>' . $basefilename;

						$archivedfilename=$mappedfilepath . DIRECTORY_SEPARATOR . 'archived' . DIRECTORY_SEPARATOR . $basefilename;
						if(file_exists($archivedfilename)){
							print ' - IN ARCHIVE';
							//if($foundinarchive<200){
							//	rename($archivedfilename,$filename);
							//}
							$foundinarchive++;
						}
						
						$unreffilename=$mappedfilepath . DIRECTORY_SEPARATOR . 'unreferenced' . DIRECTORY_SEPARATOR . $basefilename;
						if(file_exists($unreffilename)){
							print ' - IN UNREFERENCED';
							//if($foundinarchive<200){
							//	rename($archivedfilename,$filename);
							//}
						}
						
						print '</td></tr>' . "\n";
						$badlinks++;
					}
				}
				$rowcounter++;
				if($badlinks>1000) break;
			}
			print '</table>';
			print 'totalchecked: ' . $rowcounter . "<br>";
			print 'badlinks: ' . $badlinks . "<br>";
			print 'foundinarchive: ' . $foundinarchive . "<br>";
		}
		gobackhome();
	}else{
		$numimages=0;
		$sSQL="SELECT COUNT(DISTINCT imageSrc) AS numimages FROM productimages";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			if(! is_null($rs['numimages'])) $numimages=$rs['numimages'];
		}
		ect_free_result($result); ?>
<table style="margin:0 auto">
<tr><td width="100%">
<?php	$isfirefox=(strpos(@$_SERVER['HTTP_USER_AGENT'],"Firefox")!==FALSE); ?>
<form action="admindbutility.php" method="post" id="checkbrokenimages">
<input type="hidden" name="mainaction" value="checkimages">
<input type="hidden" name="subaction" id="subaction" value="">
<input type="hidden" name="posted" value="1">
<p>This script will check your Ecommerce Plus templates database for broken image links.</p>
<p>Please make sure you have backed up your site and database before proceeding.</p>
<p>&nbsp;</p>
<?php		if($numimages>1500){ ?>
<p>
	<select name="batchesof">
	<option value="">Check all</option>
	<option value="1000">Check in batches of 1000</option>
	<option value="5000">Check in batches of 5000</option>
	<option value="10000" selected="selected">Check in batches of 10000</option>
	<option value="20000">Check in batches of 20000</option>
	<option value="30000">Check in batches of 30000</option>
	<option value="40000">Check in batches of 40000</option>
	</select>
</p><p>&nbsp;</p><p>
	<select name="pg">
	<option value="1">Start at beginning</option>
<?php			for($index=1;$index<=20;$index++){ ?>
	<option value="<?php print $index+1?>">Skip first <?php print $index?> batch(s)</option>
<?php			} ?>
	</select>
</p><p>&nbsp;</p>
<?php		} ?>
<script>
function checkbrokenimages(tmethod){
	if(confirm('This can take a long time if you have a lot of images. Continue?\n')){
		document.getElementById('subaction').value=tmethod=='http'?'gohttp':'godisk';
		document.getElementById('checkbrokenimages').submit();
	}
}
</script>
<p>Please click below to start checking<?php if($numimages>0) print " <strong>(" . $numimages . " images)</strong>"?>.</p>
<p>&nbsp;</p>
<p><input type="button" value="Check for Broken Image Links via Disk" onclick="checkbrokenimages('disk')" style="margin:15px auto;max-width:600px;width:100%;display:block"></p>
<p><input type="button" value="Check for Broken Image Links via HTTP (<?php if($isfirefox) print 'Slow'; else print 'Only FireFox'?>)" onclick="checkbrokenimages('http')" style="margin:15px auto;max-width:600px;width:100%;display:block"<?php if(!$isfirefox) print ' disabled'?>></p>
<p>&nbsp;</p>
<p>Please note, images can only be checked at the rate of about 5 a second. If you have<br>many images this process can take a long time so please be patient.</p>
</form>
<?php	gobackhome(); ?>
</td></tr>
</table>
<?php
	}
}else{
?>
<form id="mainactionform" action="admindbutility.php" method="post">
<input type="hidden" name="mainaction" id="mainaction" value="">
<div style="margin:30px">
	<table style="margin:0 auto">
	<tr><td colspan="2"><strong>Please choose from the following options</strong></td></tr>
	<tr><td>Check database integrity</td><td><input type="button" value="Go" onclick="document.getElementById('mainaction').value='checkdatabase';document.getElementById('mainactionform').submit()" /></td></tr>
<?php if(FALSE){ ?>
	<tr><td>Recreate database caches</td><td><input type="button" value="Go" onclick="document.getElementById('mainaction').value='buildcache';document.getElementById('mainactionform').submit()" /></td></tr>
<?php } ?>
	<tr><td>Check for broken image links</td><td><input type="button" value="Go" onclick="document.getElementById('mainaction').value='checkimages';document.getElementById('mainactionform').submit()" /></td></tr>
	<tr><td>Check for unreferenced product images</td><td><input type="button" value="Go" onclick="document.getElementById('mainaction').value='checkimagerefs';document.getElementById('mainactionform').submit()" /></td></tr>
	<tr><td>Reorder images in database</td><td><input type="button" value="Go" onclick="document.getElementById('mainaction').value='reorderimages';document.getElementById('mainactionform').submit()" /></td></tr>
	<tr><td>Set database collation</td><td><input type="button" value="Go" onclick="document.getElementById('mainaction').value='setcollation';document.getElementById('mainactionform').submit()" /></td></tr>
	<tr><td>Optimize database</td><td><input type="button" value="Go" onclick="document.getElementById('mainaction').value='optimize';document.getElementById('mainactionform').submit()" /></td></tr>
	<tr><td>Check duplicate indexes</td><td><input type="button" value="Go" onclick="document.getElementById('mainaction').value='dupindexes';document.getElementById('mainactionform').submit()" /></td></tr>
	<tr><td>Update Discount Statistics</td><td><input type="button" value="Go" onclick="document.getElementById('mainaction').value='discountstats';document.getElementById('mainactionform').submit()" /></td></tr>
	<tr><td>US / CA State Names to Abbreviations</td><td><input type="button" value="Go" onclick="document.getElementById('mainaction').value='stateabbrev';document.getElementById('mainactionform').submit()" /></td></tr>
	<tr><td>Remove all stock notifications</td><td><input type="button" value="Go" onclick="document.getElementById('mainaction').value='removestocknotify';if(confirm('Are you sure you want to remove all stock notifications?'))document.getElementById('mainactionform').submit()" /></td></tr>
<?php /*
	<tr><td>Storage Engine</td><td><input type="button" value="Go" onclick="document.getElementById('mainaction').value='storageengine';document.getElementById('mainactionform').submit()" /></td></tr>
	<tr><td>Size Of Row</td><td><input type="button" value="Go" onclick="document.getElementById('mainaction').value='sizeofrow';document.getElementById('mainactionform').submit()" /></td></tr>
	*/
?>
	</table>
</div>
</form>
<?php
}
?>