<?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 protect 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/languageadmin.php";
include 'inc/incfunctions.php';
if(@$storesessionvalue=="") $storesessionvalue="virtualstore";
if(!@$GLOBALS['disallowlogin']) include 'inc/incloginfunctions.php';
if(@$_SESSION["loggedon"]!=$storesessionvalue || @$GLOBALS['disallowlogin'] || @$GLOBALS['ectdemostore']){
	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;
}
$isprinter=FALSE;
ob_clean();
if(@$GLOBALS['ectdemostore']){
}elseif(substr(@$_SESSION['loggedonpermissions'],5,1)!='X')
	print '<table width="100%" border="0" bgcolor=""><tr><td width="100%" colspan="4" align="center"><p>&nbsp;</p><p>&nbsp;</p><p><strong>'.$yyOpFai.'</strong></p><p>&nbsp;</p><p>'.$yyNoPer.' <br />&nbsp;<br />&nbsp;<br />&nbsp;<br />&nbsp;<br /><a href="admin.php"><strong>'.$yyAdmHom.'</strong></a>.</p><p>&nbsp;</p></td></tr></table>';
else{

if(getget('dodeleteall')=='true'){
	$sSQL="SELECT imageSrc FROM productimages WHERE imageProduct='" . escape_string(getget('prodid')) . "' ORDER BY imageSrc";
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$sSQL="SELECT imageProduct FROM productimages WHERE imageSrc='" . escape_string($rs['imageSrc']) . "' AND imageProduct<>'" . escape_string(getget('prodid')) . "'";
		$result2=ect_query($sSQL) or ect_error();
		$usedonotherproduct=ect_num_rows($result2)>0;
		
		$imagefilename=$impath=$rs['imageSrc'];
		$impath=str_replace(array($GLOBALS['storeurl'],$GLOBALS['storeurlssl']),'',$impath);
		$impath=str_replace('/',DIRECTORY_SEPARATOR,$impath);
		if(substr($impath,0,1)=='/' || substr($impath,0,1)=='\\')
			$thepath=$_SERVER['DOCUMENT_ROOT'].$impath;
		else
			$thepath='..' . DIRECTORY_SEPARATOR . $impath;
		if($usedonotherproduct){
			print '! ';
			$retval=FALSE;
		}elseif(@unlink($thepath)){
			print '\\u2713 ';
			$retval='\\u2713';
		}else{
			print '\\u274C ' ;
			$retval=FALSE;
		}
		if(strlen($imagefilename)>40)
			print '...' . substr($imagefilename,-40) . "\n";
		else
			print $imagefilename . "\n";
		logevent(@$_SESSION['loginuser'],"DELETEIMAGE",$retval,'doupload()',$impath,$impath);
	}
	ect_free_result($result);
	$sSQL="DELETE FROM productimages WHERE imageProduct='" . escape_string(getget('prodid')) . "'";
	ect_query($sSQL) or ect_error();
}elseif(getget('dodelete')=='true'){
	if(dodeleteimage(getget('imgfname'),$errmsg))
		print 'SUCCESS:'.getget('imob').':'.getget('imnum').':';
	else
		print $errmsg;
}elseif(getget("uploadform")!=''){
	$hasimageresize=FALSE;
	if(extension_loaded('gd')) $hasimageresize=TRUE;
	$imfield=substr(getget("imfield"),0,2);
	$filetypes=".bmp,.gif,.jpg,.jpe,.jpeg,.png,.tif,.tiff,.webp";
	if(getget("uploadform")=="adminprods" || getget("uploadform")=="admincats"){
		$defaultprodimages=getget("defaultprodimages");
		if($defaultprodimages==""){
			if(getget("uploadform")=="adminprods") $defaultprodimages="prodimages/"; else $defaultprodimages="images/";
		}
		$addthumb=0;
		if($imfield=="pG" || $imfield=="gt") $addthumb=2;
		if($imfield=="pL" || $imfield=="lg") $addthumb=1; ?>
		<div class="ectsoftwrapper" id="ectsoftwrapper">
			<h1><?php print $yyUplIma?></h1>
			<div id="drag-area" class="imageupload imageuploadfile">
				<h4 class="header" id="uploadheader">Drag &amp; Drop Files to Upload Here</h4>
				<p>Or browse for the files</p>
				<button type="button" id="browsebutton" class="ectbutton">Browse Files</button>
				<input id="fileselectinput" type="file" accept="<?php print $filetypes?>" name="imagefile" hidden="hidden">
			</div>
			<div class="imageupload imageuploadprogress"><progress id="progressBar" value="0" max="100" style="width:80%"></progress></div>
			<table border="" cellspacing="1" cellpadding="3" width="100%">
<?php	if($hasimageresize){ ?>
			<tr><td colspan="2">&nbsp;</td></tr><tr><td align="right"><select size="1" id="thumbdim0" onchange="document.getElementById('newdim0').disabled=this.selectedIndex==0"><option value="">Don't Resize Image</option><option value="1"<?php print (@$_COOKIE['thumbdim0']=='1'?' selected':'')?>>Resize to Width:</option><option value="2"<?php print (@$_COOKIE['thumbdim0']=='2'?' selected':'')?>>Resize to Height:</option></select></td><td><input type="text" id="newdim0" size="3" value="<?php print @$_COOKIE['newdim0']?>"<?php print @$_COOKIE['thumbdim0']==""?" disabled":""?>>:px&nbsp;&nbsp;</td></tr>
<?php		if($imfield=="pL" || $imfield=="lg" || $imfield=="pG" || $imfield=="gt"){
				$isdisabled=(@$_COOKIE['thumbdim1']==""?" disabled":"")?>
			<tr><td align="right"><select size="1" id="thumbdim1" onchange="document.getElementById('suffix1').disabled=document.getElementById('newdim1').disabled=this.selectedIndex==0"><option value="">No <?php print $yyImage?></option><option value="1"<?php print (@$_COOKIE['thumbdim1']=='1'?' selected':'')?>><?php print $yyImage?> Width:</option><option value="2"<?php print (@$_COOKIE['thumbdim1']=='2'?' selected':'')?>><?php print $yyImage?> Height:</option></select></td><td><input type="text" id="newdim1" size="3" value="<?php print @$_COOKIE['newdim1']?>"<?php print $isdisabled?>>:px&nbsp;&nbsp;Suffix:<input type="text" id="suffix1" size="6" value="<?php print (@$_COOKIE['suffix1']!=''?$_COOKIE['suffix1']:'_small')?>"<?php print $isdisabled?>></td></tr>
<?php		}
			if($imfield=="pG" || $imfield=="gt"){
				$isdisabled=(@$_COOKIE['thumbdim2']==""?" disabled":"")?>
			<tr><td align="right"><select size="1" id="thumbdim2" onchange="document.getElementById('suffix2').disabled=document.getElementById('newdim2').disabled=this.selectedIndex==0"><option value="">No <?php print $yyLgeImg?></option><option value="1"<?php print (@$_COOKIE['thumbdim2']=='1'?' selected':'')?>><?php print $yyLgeImg?> Width:</option><option value="2"<?php print (@$_COOKIE['thumbdim2']=='2'?' selected':'')?>><?php print $yyLgeImg?> Height:</option></select></td><td><input type="text" id="newdim2" size="3" value="<?php print @$_COOKIE['newdim2']?>"<?php print $isdisabled?>>:px&nbsp;&nbsp;Suffix:<input type="text" id="suffix2" size="6" value="<?php print (@$_COOKIE['suffix2']!=''?$_COOKIE['suffix2']:'_medium')?>"<?php print $isdisabled?>></td></tr>
<?php		}
		} ?>
			<tr><td colspan="2" align="center">&nbsp;<br><input type="button" value="<?php print $yyClsWin?>" onclick="document.getElementById('preloaderdiv').style.display='none'"> <input type="button" value="<?php print $yySubmit?>" onclick="dosubmitimage()"></td></tr>
			</table>
		</div>
<?php
	}
}else{
function dogetfilepath($impath, $imname){
	if(substr($impath, 0, 1)=='/' || substr($impath, 0, 1)=='\\')
		$thepath = (realpath($_SERVER['DOCUMENT_ROOT'].$impath));
	else
		$thepath = (realpath('../' . $impath));
	if(substr($thepath, -1)!='/' && substr($thepath, -1)!='\\') $thepath .= '/';
	return($thepath . $imname);
}
function writeimagejs($impath, $fdname, $whichfield){
	$impath = str_replace('\\', '/', $impath);
	if(substr($impath, -1)!='/') $impath .= '/';
	$impath .= $fdname;
	//$fieldnumber = str_replace('pImage', '', str_replace('pGiantImage', '', str_replace('pLargeImage', '', @$_POST['imagefield'])));
	if($whichfield==0) // Populate Caller
		$thefield=@$_POST['imagefield'];
	elseif($whichfield==1){ // Populate Small Image
		$thefield=str_replace('gtim', 'smim', str_replace('lgim', 'smim', @$_POST['imagefield']));
	}else{ // ($whichfield==2) Populate Large Image
		$thefield=str_replace('gtim', 'lgim', @$_POST['imagefield']);
	}
	//$thefield=@$_POST['imagefield'];
	print '<script>' . "\n";
	//if($whichfield==1 && $fieldnumber!='') print "if(window.opener.document.getElementById('x_pImage1').value!='1') window.opener.moreimages('', 'pImage', '');\r\n";
	//if($whichfield==2 && $fieldnumber!='') print "if(window.opener.document.getElementById('x_pLargeImage1').value!='1') window.opener.moreimages('', 'pLargeImage', '');\r\n";
	if($thefield=='smim0') print 'window.opener.document.getElementById("pImage").value="'.$impath.'";' . "\n";
	if($thefield=='lgim0') print 'window.opener.document.getElementById("pLargeImage").value="'.$impath.'";' . "\n";
	if($thefield=='gtim0') print 'window.opener.document.getElementById("pGiantImage").value="'.$impath.'";' . "\n";
	print 'window.opener.document.getElementById("'.$thefield.'").value="'.$impath.'";' . "\n";
	print 'if(window.opener.document.getElementById(\'secimage\'))window.opener.changeimage(window.opener.document.getElementById(\'secimage\'));' . "\n";
	print '</script>';
}
function showfiledetails($fdsuccess, $fdname, $fdsize){
	global $yyDetai,$yyFileUp,$yyNoWrFl,$yyChkFP;
	if($fdsuccess){
		print '<p align="center">&nbsp;<br /><strong>'.$yyFileUp.'</strong><br />&nbsp;<br />';
		print $yyDetai . ': ' . $fdname . ' (' . $fdsize . ' bytes)</p>';
	}else
		writeerror($yyNoWrFl.'<br /><br />'.$yyChkFP.'<br />('.@$_POST['defimagepath'].')');
}
function writeerror($theerr){
	print '<p align="center">&nbsp;<br /><strong>ERROR! '.$theerr.'</strong></p>';
	print '<p>&nbsp;</p>';
	print '<p style="text-align:center;font-weight:bold">Debug Information</p>';
	print '<p style="text-align:center">post_max_size:' . ini_get('post_max_size') . '</p>';
	print '<p style="text-align:center">upload_max_filesize:' . ini_get('upload_max_filesize') . '</p>';
	print '<p style="text-align:center">file_uploads:' . ini_get('file_uploads') . '</p>';
	print '<p>&nbsp;</p>';
}
	$success=FALSE;
	$hasimres=FALSE;
	for($index=0;$index<=2;$index++){
		setacookie('newdim'.$index,getpost("newdim".$index),365);
		setacookie('thumbdim'.$index,getpost("thumbdim".$index),365);
		setacookie('suffix'.$index,getpost("suffix".$index),365);
	}
	$fieldvalues="";
	$imagefile = $_FILES['myFiles'];
	if($imagefile['error']=='1'){
		$max_size = ini_get('upload_max_filesize');
		$errmsg='Image File was not uploaded successfully. This could be that it is larger than the maximum upload size or that the temporary upload directory is not writeable.';
		$errmsg.=' '.'The maximum upload filesize is ' . $max_size . '.';
		writeerror($errmsg);
	}else{
		if(strpos($imagefile['type'], 'image/')!==FALSE && validextension(strtolower($imagefile['name']))){
			$filepath = dogetfilepath(@$_POST['defimagepath'], $imagefile['name']);
			$tfile = file_get_contents($imagefile['tmp_name']);
			if(validimagecontent($tfile)){
				if(@$_POST['newdim0']!='' && @$_POST['thumbdim0']!=''){
					$id = getimagesize($imagefile['tmp_name']);
					$imtype = $id[2];
					// Calculate new width and height
					if($_POST['thumbdim0']=='1'){ // Width
						$newwidth = (float)$_POST['newdim0'];
						$newheight = $id[1] / ($id[0] / $newwidth);
					}elseif($_POST['thumbdim0']=='2'){ // Height
						$newheight = (float)$_POST['newdim0'];
						$newwidth = $id[0] / ($id[1] / $newheight);
					}
					$imres=imagecreatefromstring($tfile);
					$hasimres=TRUE;
					$newimres=imagecreatetruecolor($newwidth, $newheight);
					imagecopyresampled($newimres, $imres, 0, 0, 0, 0, $newwidth, $newheight, $id[0], $id[1]);
					if($imtype==IMAGETYPE_JPEG){
						$success = @imagejpeg($newimres, $filepath, 80);
					}elseif($imtype==IMAGETYPE_GIF){
						$success = @imagegif($newimres, $filepath);
					}elseif($imtype==IMAGETYPE_PNG){
						$success = @imagepng($newimres, $filepath);
					}elseif($imtype==IMAGETYPE_WEBP){
						$success = @imagewebp($newimres, $filepath);
					}else
						writeerror($yyIlFlT);
					//imagedestroy($imres);
					imagedestroy($newimres);
					if($success){
						$fieldvalues.=getpost("imagefield") . "=" . @$_POST['defimagepath'] . getpost("filename") . "&";
					}else
						writeerror($yyNoWrFl.'<br /><br />'.$yyChkFP.'<br />('.@$_POST['defimagepath'].')');
				}else{
					if(!is_uploaded_file($_FILES['myFiles']['tmp_name'])||!copy($_FILES['myFiles']['tmp_name'], $filepath))
						print $yyNoWrFl;
					else{
						$success=TRUE;
						$fieldvalues.=getpost("imagefield") . "=" . @$_POST['defimagepath'] . getpost("filename") . "&";
					}
				}
			}else
				writeerror($yyIlFlT);
		}else
			writeerror($yyIlFlT);
	}
	if($success){
		for($index=1; $index<=2; $index++){
			if(@$_POST['newdim'.$index]!='' && @$_POST['thumbdim'.$index]!=''){
				$id = getimagesize($imagefile['tmp_name']);
				$imtype = $id[2];
				// Calculate new width and height
				if($_POST['thumbdim'.$index]=='1'){ // Width
					$newwidth=(int)$_POST['newdim'.$index];
					$newheight=(int)($id[1] / ($id[0] / $newwidth));
				}elseif($_POST['thumbdim'.$index]=='2'){ // Height
					$newheight=(int)$_POST['newdim'.$index];
					$newwidth=(int)($id[0] / ($id[1] / $newheight));
				}
				if(!$hasimres){
					$imres = imagecreatefromstring($tfile);
					$hasimres=TRUE;
				}
				$lastdot = strrpos($filepath, '.');
				if($lastdot!==FALSE){
					$thesuffix = @$_POST['suffix'.$index];
					if($thesuffix=='') $thesuffix='_small';
					$thumbname = substr_replace($filepath, $thesuffix.'.', $lastdot, 1);
					$newimres = imagecreatetruecolor($newwidth, $newheight);
					imagecopyresampled($newimres, $imres, 0, 0, 0, 0, $newwidth, $newheight, $id[0], $id[1]);
					if($imtype==IMAGETYPE_JPEG){
						imagejpeg($newimres, $thumbname, 80);
					}elseif($imtype==IMAGETYPE_GIF){
						imagegif($newimres, $thumbname);
					}elseif($imtype==IMAGETYPE_PNG){
						imagepng($newimres, $thumbname);
					}elseif($imtype==IMAGETYPE_WEBP){
						imagewebp($newimres, $thumbname);
					}
					if($index==1){ // Populate Small Image
						$thefield=str_replace('gtim', 'smim', str_replace('lgim', 'smim', @$_POST['imagefield']));
					}else{ // ($whichfield==2) Populate Large Image
						$thefield=str_replace('gtim', 'lgim', @$_POST['imagefield']);
					}
					$fieldvalues.=$thefield . "=" . @$_POST['defimagepath'] . basename($thumbname) . "&";
				}
				//imagedestroy($imres);
				imagedestroy($newimres);
			}
		}
		print "SUCCESS:" . $fieldvalues;
	}
}

} ?>