<?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(@$forceloginonhttps && (@$_SERVER['HTTPS']!='on' && @$_SERVER['SERVER_PORT']!='443') && strpos(@$storeurlssl,'https:')!==FALSE){ header('Location: '.$storeurlssl.'vsadmin/'.basename($_SERVER['PHP_SELF']).(getget('loginkey')!=''?'?loginkey='.getget('loginkey'):'')); exit; }
$success=TRUE;
$dorefresh=FALSE;
$loginkeyerror=FALSE;
$floodcontrol=FALSE;
if($success){
	$alreadygotadmin = getadminsettings();
	if(getpost('posted')=="1" || getget("loginkey")!=@$loginkey){
		ect_query("DELETE FROM ajaxfloodcontrol WHERE afcAction=3 AND afcDate<'" . date('Y-m-d H:i:s',time()-5) . "'") or ect_error();
		$sSQL="SELECT afcID FROM ajaxfloodcontrol WHERE afcAction=3";
		$result=ect_query($sSQL) or ect_error();
		$floodcontrol=ect_num_rows($result)>0;
		ect_free_result($result);
	}
	if($floodcontrol){
		$success=FALSE;
		$floodcontrol=TRUE;
		$GLOBALS['disallowlogin']=TRUE;
	}elseif(@$loginkey!='' && getget("loginkey")!=@$loginkey){
		$success=FALSE;
		$loginkeyerror=TRUE;
		$GLOBALS['disallowlogin']=TRUE;
		ect_query("INSERT INTO ajaxfloodcontrol (afcAction,afcIP,afcSession,afcDate) VALUES (3,'127.0.0.1','sid','" . date('Y-m-d H:i:s') . "')") or ect_error();
	}elseif(getpost('posted')=="1"){
		ect_query("INSERT INTO ajaxfloodcontrol (afcAction,afcIP,afcSession,afcDate) VALUES (3,'127.0.0.1','sid','" . date('Y-m-d H:i:s') . "')") or ect_error();
		if(recaptchaenabled(16)) $success=checkrecaptcha($errmsg);
		$thashedpw=dohashpw(getpost('pass'));
		$adminuser="";
		$adminpassword="";
		if($success){
			$sSQL = "SELECT adminEmail,adminUser,adminPassword,adminPWLastChange FROM admin WHERE adminID=1";
			$result=ect_query($sSQL) or ect_error();
			$rs=ect_fetch_assoc($result);
			$datelastchanged=$rs['adminPWLastChange'];
			$adminuser = $rs['adminUser'];
			$adminpassword = $rs['adminPassword'];
			ect_free_result($result);
		}
		if(@$storesessionvalue=='') $storesessionvalue='virtualstore';
		if(!$success){
		}elseif(@$GLOBALS['disallowlogin']){
			$success=FALSE;
			$errmsg = $yyLogSor;
		}elseif(! (getpost('user')==$adminuser && $thashedpw==$adminpassword)){
			$sSQL="SELECT adminloginid,adminloginname,adminloginpassword,adminloginpermissions,dropShipper FROM adminlogin WHERE adminloginname='" . escape_string(getpost('user')) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if($rs['adminloginname']==getpost('user') && $rs['adminloginpassword']==$thashedpw){
					$_SESSION['loggedon'] = $storesessionvalue;
					$_SESSION['loggedonpermissions'] = $rs['adminloginpermissions'];
					$_SESSION['loginid']=$rs['adminloginid'];
					$_SESSION['loginuser']=$rs['adminloginname'];
					$_SESSION['dropshipper']=$rs['dropShipper'];
					$dorefresh=TRUE;
				}else{
					$success=FALSE;
					$errmsg = $yyLogSor;
				}
			}else{
				$success=FALSE;
				$errmsg = $yyLogSor;
			}
			ect_free_result($result);
		}else{
			$_SESSION['loggedon'] = $storesessionvalue;
			$_SESSION['loggedonpermissions'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
			$_SESSION['loginid']=0;
			$_SESSION['loginuser']=$adminuser;
			if($thashedpw=='50481f28d0f9c62842ad64b8985ab91c'&&!@$GLOBALS['ectdemostore']&&!@$GLOBALS['ectmastersite']) $_SESSION['mustchangepw']='A';
			if(time()-strtotime($datelastchanged)>(90*60*60*24) && @$padssfeatures==TRUE) $_SESSION['mustchangepw']='B';
			$dorefresh=TRUE;
		}
		logevent(getpost('user'),"LOGIN",$success,"LOGIN","");
		if(@$notifyloginattempt==TRUE&&!@$GLOBALS['disallowlogin']){
			if(@$htmlemails==TRUE) $emlNl = "<br />"; else $emlNl="\n";
			$sMessage = "This is notification of a login attempt at your store."  . $emlNl;
			$sMessage.=$storeurl . $emlNl;
			if($success || (getpost('user')==$adminuser && getpost('pass')==$adminpassword))
				$sMessage.="A correct login / password was used." . $emlNl;
			else{
				$sMessage.="An incorrect login was used." . $emlNl .
					"Username: " . getpost('user') . $emlNl .
					"Password: " . getpost('pass') . $emlNl;
			}
			$sMessage.="User Agent: " . @$_SERVER["HTTP_USER_AGENT"] . $emlNl .
				"IP: " . @$_SERVER["REMOTE_ADDR"] . $emlNl;
			dosendemail($emailAddr, $emailAddr, '', 'Login attempt at your store', $sMessage);
		}
		if($success && getpost('cook')=='ON'){
			setcookie("WRITECKL",getpost('user'),time()+(60*60*24*365), '/', '', @$_SERVER['HTTPS']=='on');
			setcookie("WRITECKP",$thashedpw,time()+(60*60*24*365), '/', '', @$_SERVER['HTTPS']=='on');
			setcookie("loginkey",getget("loginkey"),time()+(60*60*24*365), '/', '', @$_SERVER['HTTPS']=='on');
		}
		if($dorefresh){
			print '<meta http-equiv="refresh" content="1; url=admin.php">';
		}
	}
}
	if(!@$GLOBALS['disallowlogin']&&@$GLOBALS['allowlostpassword']&&getget('golostpw')=='true'){
		$checktime=getget('checktime');
		$checkhash=getget('checkhash');
		$success=TRUE;
		$errmsg='';
		if(!is_numeric($checktime)){$success=FALSE;$errmsg='Invalid check time.';}else $checktime=(int)$checktime;
		if($success){
			if((time()-$checktime)>3600||time()-$checktime<0){$success=FALSE;$errmsg='Timecheck timeout. Please try again.';}
		}
		if($success){
			$comphash=strtoupper(hash_hmac('sha512',$checktime.$emailAddr."what is the time",$GLOBALS['adminSecret']));
			if($comphash!=$checkhash){$success=FALSE;$errmsg='Hash check mismatch. Please try again';}
		}
		if($success){
			$sSQL='SELECT adminPwReset FROM admin WHERE adminID=1';
			$result=ect_query($sSQL) or ect_error();
			$rs=ect_fetch_assoc($result);
			if(getget('checktime')!=$rs['adminPwReset']){$success=FALSE;$errmsg='Time check setting invalid.';}
			ect_free_result($result);
		} ?>
	<div class="row centerit">
        <div class="login_form round_all">
            <div class="login_header" onclick="document.location='admin.php'"></div>
			<div style="padding:10px">
				<h2>Forgot Password</h2>
<?php	if($success){
			$_SESSION['loggedon'] = $storesessionvalue;
			$_SESSION['loggedonpermissions'] = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
			$_SESSION['loginid']=0;
			$_SESSION['loginuser']=$adminuser;
			header('Location: adminlogin.php');
?>
				<p style="text-align:left">You will be forwarded to a page to reset your password.</p>
<?php	}else{ ?>
				<p style="text-align:left">An error occurred: <?php print $errmsg ?></p>
<?php	} ?>
			</div>
			<p class="credit"><a href="https://www.ecommercetemplates.com/">Shopping Cart Software</a> by Ecommerce Templates</p>
        </div>
    </div>
<?php
	}elseif(!@$GLOBALS['disallowlogin']&&@$GLOBALS['allowlostpassword']&&getget('act')=='dolostpw'){
		$checktime=getpost('checktime');
		$checkhash=getpost('checkhash');
		$success=TRUE;
		$errmsg='';
		if(!is_numeric($checktime)){$success=FALSE;$errmsg='Invalid check time.';}else $checktime=(int)$checktime;
		if($success){
			if(time()-$checktime>180||time()-$checktime<0){$success=FALSE;$errmsg='Timecheck timeout. Please try again.';}
		}
		if($success){
			$comphash=strtoupper(hash_hmac('sha512',$checktime."this is the time",$GLOBALS['adminSecret']));
			if($comphash!=$checkhash){$success=FALSE;$errmsg='Hash check mismatch. Please try again';}
		}
		if($success){
			ect_query("DELETE FROM ajaxfloodcontrol WHERE afcAction=4 AND afcDate<'" . date('Y-m-d H:i:s',time()-3600) . "'") or ect_error();
			$sSQL="SELECT afcID FROM ajaxfloodcontrol WHERE afcAction=4";
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0){$success=FALSE;$errmsg='Flood control. A reset email was requested within the last hour.';}
			ect_free_result($result);
		}
		if($success){
			$sSQL="INSERT INTO ajaxfloodcontrol (afcAction,afcIP,afcSession,afcDate) VALUES (4,'','','" . date('Y-m-d H:i:s') . "')";
			ect_query($sSQL) or ect_error();
			$checktime=time();
			$checkhash=strtoupper(hash_hmac('sha512',$checktime.$emailAddr."what is the time",$GLOBALS['adminSecret']));
			$emailtxt='Please click on the link to reset your password.'.$GLOBALS['emlNl'];
			$emailtxt.=$storeurlssl.'vsadmin/login.php?golostpw=true&checktime='.$checktime.'&checkhash='.$checkhash.$GLOBALS['emlNl'];
			ect_query("UPDATE admin SET adminPwReset='" . escape_string($checktime) . "' WHERE adminID=1") or ect_error();
			dosendemail($emailAddr,$emailAddr,'','ECT Store Password Reset',$emailtxt);
		} ?>
	<div class="row centerit">
        <div class="login_form round_all">
            <div class="login_header round_top" onclick="document.location='admin.php'"></div>
			<div style="padding:10px">
				<h2>Forgot Password</h2>
<?php	if($success){ ?>
				<p style="text-align:left">An email has been sent with a password reset link. This link will expire after one hour.</p>
<?php	}else{ ?>
				<p style="text-align:left">An error occurred: <?php print $errmsg ?></p>
<?php	} ?>
			</div>
			<p class="credit"><a href="https://www.ecommercetemplates.com/">Shopping Cart Software</a> by Ecommerce Templates</p>
        </div>
    </div>
<?php
	}elseif(!@$GLOBALS['disallowlogin']&&@$GLOBALS['allowlostpassword']&&getget('forgotpw')=='true'){
		$checktime=time();
		$checkhash=strtoupper(hash_hmac('sha512',$checktime."this is the time",$GLOBALS['adminSecret']));
?>
	<form method="post" name="mainform" action="login.php?act=dolostpw">
	<input type="hidden" name="checktime" value="<?php print $checktime?>" />
	<input type="hidden" name="checkhash" value="<?php print $checkhash?>" />
	<div class="row centerit">
        <div class="login_form round_all">
            <div class="login_header round_top" onclick="document.location='admin.php'"></div>
			<div style="padding:10px">
				<h2>Forgot Password</h2>
				<p style="text-align:left">Please click here to send a password reset email. Then click on the link in the email to reset your password.</p>
				<p><input type="submit" value="Send Password Reset Email"></p>
			</div>
			<p class="credit"><a href="https://www.ecommercetemplates.com/">Shopping Cart Software</a> by Ecommerce Templates</p>
        </div>
    </div>
	</form>
<?php
	}elseif(getpost('posted')=="1" && $success){ ?>
	<div class="row centerit">
      <div class="login_message">
            <h2 class="centerit"><?php print $yyLogCor?></h2>
            <p><?php print $yyNowFrd?></p>
            <p><?php print $yyNoAuto?><a href="admin.php"><strong><?php print $yyClkHer?></strong></a>.</p>
      </div>
    </div>
<?php
	}else{
		if(@$GLOBALS['disallowlogin']){
			$success=FALSE;
			$errmsg='<div class="login_message">' . 'Login Disabled:<br />';
			if($loginkeyerror) $errmsg.='<br />(Admin Login Key Error)';
			if($floodcontrol) $errmsg.='<br />(Flood Control. Please wait 5 seconds between login attempts)';
			if($floodcontrol&&getpost('posted')=="1") $errmsg.='<br /><br /><input type="button" class="ectbutton" value="Go Back" onclick="history.go(-1)" />';
			$errmsg.='</div>';
		} ?>
	<form method="post" name="mainform" action="login.php<?php print (getget("loginkey")!=''?'?loginkey='.htmlspecials(getget('loginkey')):'')?>" id="loginform" onsubmit="return checkloginform()">
	<input type="hidden" name="posted" value="1">
	<div class="row centerit">
        <div class="login_form round_all">
            <div class="login_header round_top" onclick="document.location='admin.php'"></div>
<?php	if(! $success){ ?>
			  <div class="ectred"><?php print $errmsg?></div>
<?php	}
		if(!@$GLOBALS['disallowlogin']){ ?>
			<table>
              <tr>
                <td width="30%" align="right"><strong><?php print $yyUname?>: </strong></td>
				<td align="left"><input type="text" name="user" id="user" size="20" /></td>
			  </tr>
			  <tr>
                <td align="right"><strong><?php print $yyPass?>: </strong></td>
				<td align="left"><input type="password" name="pass" size="20" autocomplete="off" /></td>
			  </tr>
			  <tr>
                <td align="right"><input type="checkbox" name="cook" value="ON" /></td>
				<td align="left" class="small"><strong><?php print $yyWrCoo?></strong><br /><span style="font-size:10px"><?php print $yyNoRec?></span></td>
			  </tr>
<?php			if(recaptchaenabled(16)){ ?>
			  <tr>
				<td align="center" colspan="2"><?php displayrecaptchajs('adminlogincaptcha',TRUE,FALSE)
				?><div id="adminlogincaptcha" class="g-recaptcha recaptchaadminlogin"></div>
				</td>
			  </tr>
<?php			} ?>
			</table>
			<p><input type="submit" value="<?php print $yySubmit?>"></p>
<?php	}
		if(@$GLOBALS['allowlostpassword']){ ?>
			  <p class="credit"><a href="login.php?forgotpw=true">Forgot password</a></p>
<?php	} ?>
			  <p class="credit"><a href="https://www.ecommercetemplates.com/">Shopping Cart Software</a> by Ecommerce Templates</p>
        </div>
    </div>
	</form>
<script>
<!--
function checkloginform(){
	var frm=document.getElementById('loginform');
	if(frm.user.value==''){
		alert("<?php print jscheck($yyPlsEntr.' "'.$yyUname.'"')?>");
		frm.user.focus();
		return(false);
	}
<?php	if(recaptchaenabled(16)) print 'if(!adminlogincaptchaok){ alert("Please show you are a real human by completing the reCAPTCHA test");return(false); }' ?>
	return true;
}
document.getElementById('user').focus();
// -->
</script>
<?php
	} ?>
     