<?php
/**
 * Copyright (C) DairyWindow 2018
 * admin@dairywindow.nz
 */

/* (C) DairyWindow 2012-2017 */

/*
 Fields needed:
 userFirst
 userEmail
 userPassword
 userActive
 userSite
 userPhone
*/


session_start(['cookie_lifetime' => 86400]);
$_SESSION = array();

sleep(1);

$error_msg = "
		<h1>Error</h1>
		<h2>Failed connecting to the MySQL database</h2>
		Check the following things:<br/>
		<ol>
			<li>Is your computer connected to the network?</li>
			<li>Is the username and password correct?</li>
			<li>The MySQL server might have errors, or might not be running. Ensure you can connect using the workbench tool</li>
			<li>Check the settings in the file <strong>connection_info.php</strong> are correct</li>
		</ol>
	";

function redirect($userarray)
{
	global $auth_link;
	global $link;
	global $debug;
	global $error_msg;

	if ($debug)
		print_r($userarray);

	foreach ($userarray as $key => $value) {
		if (!is_numeric($key))
			$_SESSION[$key] = $value;
	}
	$_SESSION['expires'] = date('Y-m-d H:i:s', strtotime('+12 hours'));

	$url = "";
	if (count($_GET) > 0 && strlen($_GET['url']) > 0 && isset($_GET['url']) && !stristr($_GET['url'], 'signin')) {
		foreach ($_GET as $key => $value) {
			if ($key == "url") {
				$url .= $value . "?";
			} else {
				if (substr($url, strlen($url) - 1) != "?") {
					$url .= "&" . $key . "=" . $value;
				} else {
					$url .= $key . "=" . $value;
				}
			}
		}
		if (substr($url, strlen($url) - 1) == "?")
			$url = substr($url, 0, strlen($url) - 1); //remove ? if there is nothing after it
	} else
		$url = "home.php"; //default page, if none is specified

	require 'inc/connection_info.php';
	$database .= $userarray['userSite'];

	$link = new mysqli($server, $dbusername, $dbpassword, $database);
	if (!$link)
		die($error_msg);

	$sql = "
			# get info for session
			Select *
			From dw_settings
			Where settingsID = ?
		";
	if (!$settingsqry = mysqli_prepared_query($link, $sql, "i", array($userarray['userSite']), __FILE__, __LINE__))
		reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
	if (mysqli_prepared_num_rows($settingsqry) == 1) {
		foreach ($userarray as $key => $value) {
			if (!is_numeric($key))
				$_SESSION[$key] = $value;
		}
	} else {
		die('More than 1 setting found');
	}

	if ($debug) {
		echo "<a href='" . $url . "'>" . $url . "</a><br>";
		foreach ($_SESSION as $key => $value) {
			echo $key . ": " . $value . "<br>";
		}
	} else {
		header("HTTP/1.1 303 See Other");
		if (stristr($url, 'signin'))
			header("Location: home.php");
		else
			header("Location: " . $url);
	}

	die();
}

if (isset($_GET['debug']))
	$debug = true;
else
	$debug = false;

$_SESSION['userEmail'] = "";

require "inc/connection_info.php";
require "inc/savesql.php";
require "inc/mysqli_prepared_query.php";
require "inc/mysqli_prepared_num_rows.php";
require "inc/func_email.php";

//$auth_link=@mysqli_connect($server, $dbusername, $dbpassword, $database);
$auth_link = new mysqli($server, $authusername, $authpassword, $authdb);
if (!$auth_link)
	die($error_msg);
global $auth_link;
require "inc/reporterror.php";

$status = 0;

if (isset($_POST['resetpwd']) && isset($_POST['userEmail']) && $_POST['userEmail'] != "") {

	//generate new password
	if ($debug) {
		echo "<pre>";
		print_r($_POST);
		echo "</pre>";
	}
	$words = file("inc/words.txt");
	$numwords = mt_rand(2, 4); //between 2 and 4 words
	$newpassword = "";
	for ($i = 0; $i < $numwords; $i++) {
		$rand = mt_rand(0, count($words) - 1);
		$newpassword .= trim(ucfirst($words[$rand])); //no spaces
	}
	$newpassword .= mt_rand(11, 99); //add a random number to the end

	$userEmail = mysqli_real_escape_string($auth_link, $_POST['userEmail']); //dont have access to clean() yet
	$sql = "
			UPDATE dw_auth SET
				userPassword = ?
			WHERE userEmail = ?
		";
	if (!savesql($auth_link, $sql, "ss", array((password_hash($newpassword, PASSWORD_DEFAULT)), $userEmail), __FILE__, __LINE__))
		reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);

	$sql = "
			Select
				userFirst,
				userPhone
			From
				dw_auth
			Where
				userEmail = ?
		";
	if (!$selquery = mysqli_prepared_query($auth_link, $sql, "s", array($userEmail), __FILE__, __LINE__))
		reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
	$user2array = $selquery[0];

	$userFirst = $user2array['userFirst'];

	$body .= 'Your password was automatically changed in DairyWindow at ' . date('D d M y H:m') . ' by IP address ' . $_SERVER['REMOTE_ADDR'] . '.<br>
			Your new password is <strong>' . $newpassword . '</strong><br>
			Your old one won\'t work anymore. Don\'t forget that passwords are cAsE sEnSiTiVe. Ensure you copy and paste <u>the whole thing</u>.<br>
			You can update your password (after logging in) by updating <a href="https://www.dairywindow.nz/profile.php">your profile</a>.<br>
			<br>
			If you didn\'t make this change, <a href="mailto:admin@dairywindow.nz">please let us know</a>.';

	$pwdemailed = email($userEmail, 'DW password change', $body);
	if (isset($user2array['userPhone']) && $user2array['userPhone'] != "" && $user2array['userPhone'] != null) {
		require "inc/sms.php";
		$text = substr("Your DW password has changed. It is now '" . $newpassword . "'. If you did not make this change, please contact admin@dairywindow.nz immediately", 0, 159);
		//sms($text, $user2array['userPhone']);
	}
	if (!$pwdemailed) {
		reporterror("Password could not be emailed to user. IP '" . $_SERVER['REMOTE_ADDR'] . "'. Password '" . $newpassword . "'. To '" . $to . "'. Subject '" . $subject . "'. Body '" . $body . "'. Headers '" . implode(' ', $headers) . "'. userEmail '" . $userEmail . "'. NEW password '" . $newpassword . "'.", "None", $_SERVER['REQUEST_URI'], __FILE__, __LINE__, "", False);
		$status = 3; //pwd could not be emailed
	} else
		$status = 4; //pwd changed ok
} else {
	if (isset($_POST['inputPassword']) && $_POST['inputPassword'] != "" && $_POST['inputPassword'] != null) {
		//password

		$banned = array('(', ')', '<', '>', ',', ';', ':', '[', ']');
		foreach ($banned as $char) {
			if (stristr($_POST['userEmail'], $char)) {
				email('admin@dairywindow.nz', 'Login error', 'Username ' . $_POST['userEmail'] . ' contains invalid character ' . $char);
				die('Sorry but your username contains invalid character "' . $char . '". Please see your administrator');
			}
		}

		$sql = "
				# get info for user
				Select
					userID,
					userFirst,
					userEmail,
					userPassword,
					userActive,
					userSite,
					userPhone
				From
					dw_auth
				Where
					userEmail = ? And
					userActive = 1
				Limit 1
			";
		if (!$userqry = mysqli_prepared_query($auth_link, $sql, 's', array($_POST['userEmail']), __FILE__, __LINE__))
			reporterror($auth_link->error, $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		//echo mysqli_prepared_num_rows($userqry);
		if (mysqli_prepared_num_rows($userqry) == 1) {
			//email address found
			$userarray = $userqry[0];
			$password_from_db = $userarray['userPassword'];

			//$2y$10$b8axrW6zOGve6SFK165zAe9gUuSiUtGe1f5xcff6bD0
			//$password_from_form=password_hash(, PASSWORD_DEFAULT);
			if (password_verify($_POST['inputPassword'], $password_from_db)) {
				if (isset($_SESSION['userSite'])) {
					@setcookie('userSite', $_SESSION['userSite']); //this is for uploading images in shiftnotes (\js\tinymce\plugins\jbimages\config.php)
				}
				redirect($userarray);
			} else {
				//incorrect password
				$status = 1;

				$userFirst = $userarray['userFirst'];

				if (empty($_POST['signin-agent']))
					$extra_details = 'none';
				else
					$extra_details = $_POST['signin-agent'];
				$body = "On " . date('D d M y H:m') . " someone with IP " . $_SERVER['REMOTE_ADDR'] . " tried to log into DairyWindow as " . $_POST['userEmail'] . ", but entered an INCORRECT password (dont forget passwords are cAsE sEnSiTiVe). If you suspect someone is trying to access your account, please change your password by editing your profile or contact admin@dairywindow.nz.<br>Extra details: " . $extra_details;

				if (stristr($_POST['userEmail'], '@'))
					email($_POST['userEmail'], 'DW login attempt', $body);
				if (isset($phone) && $phone != "" && $phone != null) {
					require "inc/sms.php";
					$text = substr("Someone tried to access your account, but they used an incorrect password. If this was not you, please contact admin@dairywindow.nz", 0, 159);
					sms($text, $phone);
				}
			}
		} else
			$status = 2; //could not find email address (0 records returned)
	}
}

$title = "Sign in";
require "inc/head.php";
require "inc/showdebug.php";
if ($debug)
	showdebug();
?>

<div class="container login" role="main">
	<img src="inc/logo.php" class="img-responsive center-block">
	<form class="form-signin center-block text-center" method="post" style="max-width:300px;" autocomplete="off">
		<h2 class="form-signin-heading">Please sign in</h2>

		<div class="input-group" title="Email address">
			<label for="userEmail" class="sr-only">Email address</label>
			<div class="input-group-addon"><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span></div>
			<input type="text" name="userEmail" id="userEmail" class="form-control" placeholder="Email address" required
				autofocus <?php if (isset($_POST['userEmail']))
					echo "value='" . $_POST['userEmail'] . "'"; ?>>
		</div>

		<div class="popover fade bottom in bg-danger danger" role="tooltip" id="email-div"
			style="display:none;position:relative;">
			<div class="arrow" style="left: 50%;"></div>
			<h3 class="popover-title" style="display: none;">Error</h3>
			<div class="popover-content" id="email-content"><span class="glyphicon glyphicon-exclamation-sign"
					aria-hidden="true"></span>&nbsp;Incorrect email address</div>
		</div>

		<div class="input-group" title="Password">
			<label for="inputPassword" class="sr-only">Password</label>
			<div class="input-group-addon"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span></div>
			<input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password"
				autocomplete="off" onkeyup="hidediv('password-content');">
		</div>

		<input type="hidden" name="signin-agent" id="signin-agent">
		<script>
			$("#signin-agent").val("appCodeName:" + navigator.appCodeName + " appName:" + navigator.appName + " appVersion:" + navigator.appVersion + " platform:" + navigator.platform);
		</script>
		<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
	</form>
	<form class="center-block text-center" method="post" autocomplete="off">
		<div class="popover fade bottom in bg-danger danger center-block text-center" role="tooltip" id="password-div"
			style="display:none;position:relative;">
			<div class="arrow" style="left: 50%;"></div>
			<h3 class="popover-title" style="display: none;">Error</h3>
			<div class="popover-content center-block text-center" id="password-content1">
				<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>&nbsp;Incorrect password.
				<input class="btn" name="resetpwd" type="submit" value="Reset password">
				<input name="userEmail" type="hidden" value="<?php if (isset($_POST['userEmail']))
					echo $_POST['userEmail']; ?>">
			</div>
		</div>

		<div class="popover fade bottom in bg-danger danger center-block text-center" role="tooltip"
			id="newpassword-div" style="display:none;position:relative;">
			<div class="arrow" style="left: 50%;"></div>
			<h3 class="popover-title" style="display: none;">Error</h3>
			<div class="popover-content center-block text-center" id="password-content2">
				<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>&nbsp;Your password could
				not be emailed to you. Your new password is
				<strong><?php if (isset($newpassword))
					echo $newpassword;
				else
					echo "undefined"; ?></strong>
			</div>
		</div>

		<div class="popover fade bottom in bg-danger danger center-block text-center" role="tooltip" id="pwdsuccess-div"
			style="display:none;position:relative;">
			<div class="arrow" style="left: 50%;"></div>
			<h3 class="popover-title" style="display: none;">Success</h3>
			<div class="popover-content center-block text-center" id="password-content3">
				<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>&nbsp;Your NEW password was emailed to
				you. Please allow up to 5 minutes. If you don't see the email, ensure you check your junk mail folder.
				If you still cant log in, please contact <a
					href="mailto:admin@dairywindow.nz">admin@dairywindow.nz</a>
			</div>
		</div>

	</form>
</div> <!-- /container -->

<script src="js/jquery.min.js?v=2.1"><!-- jQuery (necessary for Bootstrap's JavaScript plugins) --></script>
<script src="js/bootstrap.min.js?v=2.1"></script>
<script src="js/common.js?v=2.5"></script>
<script>
	<?php
	switch ($status) {
		case 1:
			echo "$('#password-div').css('display', 'block');";
			echo "$('#password-content1').css('display', 'block');";
			break;
		case 2:
			echo "$('#email-div').css('display', 'block');";
			break;
		case 3:
			echo "$('#newpassword-div').css('display', 'block');";
			break;
		case 4:
			echo "$('#pwdsuccess-div').css('display', 'block');";
			break;
	}
	?>
</script>
</body>

</html>