<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Revised: 4/26/2010	ELL
// Added warning message about system requiring JavaScript.
// Revised: 11/16/2012	ELL
// Added sending of passwords as SHA-256 hashed.  Set focus on user ID upon body load.  Capture enter key for submitting form.
// Revised: 2/11/2013	ELL
// Added override to allow saving of password in browser.
// Revised: 11/5/2014	ELL
// Added link for "forgot password".
// Revised: 4/13/2015	ELL
// Fixed bug with refresh CAPTCHA routine sucking up tons of bandwidth if login screen left open.
//
	
	session_start();
	session_regenerate_id(true);
	
	$mask = "captcha/*.captcha";
	array_map("unlink", glob($mask));
	
	include ("../connect/config.php");
	include ("../connect/db_connect.php");
	
	if (defined(BWB_LANG))
		include ("lang/" . BWB_LANG . ".php");
	else
		include ("lang/en.php");
	
	$server_name = $_SERVER['SERVER_NAME'];
	$script_filename = $_SERVER['SCRIPT_NAME'];
	$url = "https://" . $server_name . $script_filename;
	if (BWB_REQUIRE_SSL == 1)
	{
		//if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' || $_SERVER['SERVER_PORT'] !== 443)
		if ($_SERVER['HTTPS'] !== 'on')
			header("Location: $url");
	}
	
	$doc_root = getenv('DOCUMENT_ROOT');
	$captcha_path = $doc_root . "/manage/captcha";
	$captcha_images = array();
	$i = 0;
	
	if ($handle = opendir($captcha_path)) {
		while (false !== ($entry = readdir($handle))) {
			if ($entry != "." && $entry != ".." && $entry != "index.php") {
				$captcha_images[$i] = $entry;
				$i++;
			}
		}
		closedir($handle);
	}
	
	$index = rand(0, $i - 1);
	$link = "captcha/" . time() . ".captcha";
	$target = "captcha/" . $captcha_images[$index];
	if (link($target , $link))	{
		$use_captcha = true;
		$captcha = hash('sha256', $captcha_images[$index]);
		$_SESSION['captcha'] = $captcha;
	}
	else
		$use_captcha = false;
		
	$err_code = $_GET['err'];
	
	$query = "SELECT `option_value` FROM `" . BWB_TABLE_PREFIX . "options_selected` WHERE `option_name`='Theme'";
	$result = $bwb_dbh->query($query);
	if ($result->rowCount() > 0)	{
		$row = $result->fetch(PDO::FETCH_ASSOC);
		$theme = $row['option_value'];
	}
	else
		$theme = "classic";
?>
<!DOCTYPE html>
<html>
<head>
<title>Breeze Website Builder</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="theme/<?php echo $theme; ?>/manager.css" type="text/css">
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon">
<style type="text/css">
#login_btn	{
	width:100px;
	margin-top:5px;
}
#reset_password_btn	{	width:100px;	}
#cancel_btn	{
	height:25px;
	width:90px;
	background-position: 5px 3px;
}
#login_logo	{
	text-align:center;
	padding:0px;
	margin:0px;
	height:110px;
}
</style>
<script language="javascript" src="js/hash.js" type="text/javascript"> </script>
<script language="javascript" type="text/javascript" src="js/browser_detect.js"></script>
<script language="javascript" type="text/javascript" src="js/mouse_position.js"></script>
<script language="javascript" type="text/javascript" src="js/popup_msg.js"></script>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>

<script language="javascript" type="text/javascript">
var browser = BrowserDetect.browser;
var browser_version = BrowserDetect.version;

var param_array = {'popup_msg_type' : 1, 'status_msg' : '', 'popup_timeout' : -1};
var popup_msg = new PopupMsg(param_array);

var err_code = "<?php echo $err_code; ?>";
var refresh_captcha_running = false;

function SubmitLogin()
{
	var password = document.getElementById("password_input").value;
	var hash = Sha256.hash(password);
	document.getElementById("password").value = hash;
	if (!document.getElementById("browser_save_password").checked)
		document.getElementById("password_input").value = '';
	document.forms["frmLogin"].submit();
}

function checkForEnter(e) {
	if (e.keyCode == 13) {
		SubmitLogin();	
	}
}

function WarnAboutSSL(show_warning)	{
	if (show_warning)
	{
		popup_msg.top_offset = 50;
		popup_msg.left_offset = 320;
		popup_msg.popup_msg_type = 2;
		popup_msg.popup_timeout = 30000;
		popup_msg.msg_width = 500;
		popup_msg.status_msg = "<?php echo LOGIN_SSL_WARNING_1 . $url . LOGIN_SSL_WARNING_2; ?>";
		popup_msg.ShowPopupMsg();
	}
}

function ShowPasswordReset(show_reset)
{
	if (show_reset == 1)	{
		document.getElementById('frmResetPassword').style.display = 'block';
		document.getElementById('frmLogin').style.display = 'none';
		if (refresh_captcha_running === false)	{
			mTimer = setInterval("RefreshCaptcha();", 30000);
			refresh_captcha_running = true;
		}
	}
	else	{
		document.getElementById('frmResetPassword').style.display = 'none';
		document.getElementById('frmLogin').style.display = 'block';
		if (refresh_captcha_running === true)	{
			clearInterval(mTimer);
			refresh_captcha_running = false;
		}
	}
}

function SubmitPasswordReset()
{
	document.forms["frmResetPassword"].submit();
}

function RefreshCaptcha()
{
	$.post( "refresh_captcha.php", { } ).done(CompleteRefreshCaptcha) ;
}
function CompleteRefreshCaptcha(data)
{
	document.getElementById("captcha_image").src = data;
}

function ResetRefreshTimer()
{
	clearInterval(mTimer);
	mTimer = setInterval("RefreshCaptcha();", 30000);
}
</script>
</head>

<body onLoad="document.getElementById('userid').focus();">
<div align="center" id="login_logo"><img src="theme/<?php echo $theme; ?>/images/Breeze_header_logo.png" alt="Breeze Website Builder"></div>
<div id="header_divider_login">&nbsp;</div>
<form name="frmLogin" id="frmLogin" method="post" action="login_verify.php">
<div align="center">
  <table border="0" cellspacing="0" cellpadding="0">
    <tbody>
      <tr>
        <td colspan="2" class="sub_title"><?php echo LOGIN_USERID_PASS_MSG; ?>:</td>
      </tr>
      <tr>
        <td><?php echo USERID_WORD; ?>:</td>
        <td><input type="text" name="userid" id="userid" /></td>
      </tr>
      <tr>
        <td><?php echo PASSWORD_WORD; ?>:</td>
        <td>
        	<input type="password" name="password_input" id="password_input" onKeyDown="checkForEnter(event);" />
            <input type="hidden" name="password" id="password" />
        </td>
      </tr>
      <tr>
        <td>
        	<input type="checkbox" name="browser_save_password" id="browser_save_password" <?php if ($_SERVER['HTTPS'] !== 'on') echo "onChange=\"WarnAboutSSL(this.checked);\""; ?> />
        	<span class="small_message"><?php echo LOGIN_SAVE_LOGIN_MSG; ?></span>
        </td>
        <td align="right">
        <div class='button_console_login' id="login_btn" onClick="SubmitLogin();"><span class='button_console_text_w_icon'><?php echo LOGIN_LOGIN_BTN; ?></span></div>
        </td>
      </tr>
<?php if ($use_captcha === true)	{	?>
      <tr>
      	<td>&nbsp;</td>
        <td><span class="small_message" onClick="ShowPasswordReset(1);" style="cursor:pointer; text-decoration:underline;"><?php echo LOGIN_FORGOT_PASSWORD_MSG; ?></span></td>
      </tr>
<?php }	?>
    </tbody>
  </table>
</div>
</form>

<?php if ($use_captcha === true)	{	?>
<form action="reset_password.php" id="frmResetPassword" method="post" name="frmResetPassword" style="display:none;">
<div align="center">
  <table border="0" cellspacing="0" cellpadding="0">
	<tbody>
		<tr>
			<td colspan="2" class="sub_title"><?php echo LOGIN_ENTER_EMAIL_MSG; ?>:</td>
		</tr>
		<tr>
			<td style="width:110px;"><?php echo EMAIL_WORD; ?>: </td>
			<td><input id="email" name="email" type="text" style="width:250px;" /></td>
		</tr>
        <tr>
        	<td colspan="2">&nbsp;</td>
        </tr>
		<tr>
			<td>&nbsp;</td>
			<td style="height:100px;"><img src="<?php echo $link; ?>" alt="chaptcha" id="captcha_image" /></td>
		</tr>
		<tr>
			<td colspan="2">
            <?php echo LOGIN_CAPTCHA_MSG; ?>:
            <input autocomplete="off" id="captcha_response" name="captcha_response" size="10" type="text" value="" onKeyPress="ResetRefreshTimer();" />
            <img src="images/icon_Reset.png" alt="Reset" style="cursor:pointer; display:inline; margin-top:1px; margin-bottom:-10px; margin-left:10px;" onClick="RefreshCaptcha();" />
            </td>
		</tr>
		<tr>
        	<td colspan="2">&nbsp;</td>
        </tr>
        <tr>
			<td>
                <div class='button_console_cancel_sm' id="cancel_btn" onClick="ShowPasswordReset(0);"><span class='button_console_text_w_sm_icon' style="top:6px;"><?php echo CANCEL_WORD; ?></span></div>
            </td>
            <td align="right">
                <div class='button_console_save' id="reset_password_btn" onClick="SubmitPasswordReset();"><span class='button_console_text_w_icon'><?php echo SUBMIT_WORD; ?></span></div>
			</td>
		</tr>
	</tbody>
  </table>
</div>
</form>
<?php }	?>

<div id="javascript_warning" align="center" class="warning_text">
<?php echo LOGIN_JS_WARNING_MSG; ?>
</div>

<?php include("lib/popup_msg.html"); ?>

<script language="javascript" type="text/javascript">
	document.getElementById("javascript_warning").innerHTML = "";
	HidePopupMsg();
	
	if (err_code != "")
	{
		popup_msg.top_offset = 50;
		popup_msg.left_offset = 400;
		popup_msg.popup_msg_type = 2;
		popup_msg.popup_timeout = 8000;
		popup_msg.msg_width = 500;
		var email = "<?php echo $_GET['email']; ?>";
		
		switch (err_code)
		{
			case "captcha":
				popup_msg.status_msg = "<?php echo LOGIN_CAPTCHA_ERR; ?>";
				break;
			case "bad_email":
				popup_msg.status_msg = "<?php echo LOGIN_BAD_EMAIL_ERR; ?>";
				break;
			case "bad_referer":
				popup_msg.status_msg = "<?php echo LOGIN_BAD_REFERER_ERR; ?>";
				break;
			case "bad_user":
				popup_msg.status_msg = "<?php echo LOGIN_BAD_USER_ERR; ?>";
				break;
			case "password_reset":
				popup_msg.status_msg = "<?php echo LOGIN_PASSWORD_RESET_ERR; ?>";
				break;
			default :
				popup_msg.status_msg = "<?php echo LOGIN_DEFAULT_ERR; ?>";
		}
	
		popup_msg.ShowPopupMsg();
		
		if (err_code == "password_reset")
			ShowPasswordReset(0);
		else	{
			ShowPasswordReset(1);
			document.getElementById('email').value = email;
		}
	}
</script>
</body>
</html>