<?php
// Reset Password, copyright 2012, EB Dynamics, Inc., Ed Lemmers
// For licensing, see license.txt.
// Created: 11/5/2014	ELL
//
//
session_start();

$server_name = $_SERVER['SERVER_NAME'];
$server_name_www = "www." . $server_name;
$referers = array($server_name_www, $server_name);

$mask = "captcha/*.captcha";
array_map("unlink", glob($mask));

// Module for performaing actual email operation.
include("lib/mime_mail.inc");
// DB connection for retrieving HTML message format for message back to inquirer, etc.
include ("../connect/db_connect.php");
include ("../connect/config.php");
include("lib/generate_password.php");

$email = $_POST['email'];
$challenge = $_SESSION['captcha'];
$response = $_POST['captcha_response'];
unset($_SESSION['captcha']);

$go_back = "index.php";
$html = 1;	// html
$no_mime = 0;
if (isset($email) && ($email != ""))
	$go_back .= "?email=$email";

$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "captcha";
$result = $bwb_dbh->query($query);
$correct_responses = array();
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
	$tmp_challenge = hash('sha256', $row['challenge']);
	if ($tmp_challenge == $challenge)
		$correct_responses[] = $row['response'];
}

$got_correct = false;
foreach ($correct_responses as $answer)
{
	if ($answer == $response)
		$got_correct = true;
}
if ($got_correct !== true)
{
	$err_code = "captcha";
	DisplayError($err_code, $go_back);
}
	
// Used in conjunciton with $referers to eliminate atacks from remote servers.
$valid_env = array('REMOTE_HOST', 'REMOTE_ADDR', 'REMOTE_USER', 'HTTP_USER_AGENT');

if (!check_email_address($email))
{
	$err_code = "bad_email";
	DisplayError($err_code, $go_back);
}

// Check referers to make sure SPAM bot is not trying to brake in.
if (!check_referer($referers))
{
	$err_code = "bad_referer";
	DisplayError($err_code, $go_back);
}

// Get user ID from users table by email.
$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "users WHERE email = :email";
$stmt = $bwb_dbh->prepare($query);
$stmt->execute(array(':email' => $email));
$num_results = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT);

if ($num_results < 1)
{
	$err_code = "bad_user";
	DisplayError($err_code, $go_back);
}
$UserID = $row['UserID'];

// Create new password.
$password = GeneratePassword();
// Insert salt into password.
$pos = rand(0, (strlen($password)-1) );
$pass1 = substr($password, 0, $pos);
$pass2 = substr($password, $pos);
$salted_pass = $pass1 . BWB_SALT . $pass2;
// Encrypt password.
$encrypt_password = doEncrypt($salted_pass, $UserID);
// Update user table with new password.
$query = "UPDATE `" . BWB_TABLE_PREFIX . "users` SET `password`='" . $encrypt_password . "' WHERE `UserID`='" . $UserID . "'";
$cnt = $bwb_dbh->exec($query);


//Mail fields to recipient.
$mail = new mime_mail;

$content_type = "application/octet-stream";
$from_email = "Password Reset Form <$email>";
$to_email = $email;
$subject = "Password Reset for Breeze Website Builder Login";
//$cc_email = "ed@ebdynamics.com";	//for testing

if ($html == 1)
	$lf = "<br>";
else
	$lf = "\n";
	
$protocol  = empty($_SERVER['HTTPS']) ? 'http' : 'https';
$port      = $_SERVER['SERVER_PORT'];
$disp_port = ($protocol == 'http' && $port == 80 || $protocol == 'https' && $port == 443) ? '' : ":$port";
$domain    = $_SERVER['SERVER_NAME'];
$protocol_String  = "$protocol://{$domain}{$disp_port}";

if ($html == 1)
{
	$msg = "<b>To return to our website,  click here: </b>  " . "<a href=\"" . $protocol_String . "/manage/index.php\">RETURN</a>";
	$msg = "Your user name is <b>" . $UserID  . "</b> and your temporary password is <b>" . $password . "</b>" . $lf . $lf . $msg;
	$msg = "<b>$subject</b>" . $lf . $msg;
}
else
{
	$msg = "To return to our website, go to this web address: www." . $protocol_String . "/manage/index.php";
	$msg = "Your user name is " . $UserID  . " and your temporary password is " . $password . $lf . $msg;
	$msg = $subject . $lf . $msg;
}

$mail->from = $from_email;
$mail->to = $to_email;
$mail->cc = $cc_email;
$mail->replyto = $reply_to;
$mail->subject = $subject;
$mail->body = $msg;
$mail->html = $html;
$mail->no_mime = $no_mime;

$mail->send();

// Go to desired next page.
header("Location: index.php?err=password_reset");
exit;

/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// Check for valid emails. //////////////////////////////////////////////
function check_email_address($email) {
	 if (!filter_var($email, FILTER_VALIDATE_EMAIL))
	 	return false;
	else
		return true;
}

/****************************************************************
 * check_referer() breaks up the enviromental variable		*
 * HTTP_REFERER by "/" and then checks to see if the second	*
 * member of the array (from the explode) matches any of the	*
 * domains listed in the $referers array (declaired at top)	*
 ****************************************************************/

function check_referer($referers)
{
	global $errors;
	if (count($referers)) {
		if (getenv('HTTP_REFERER')) {
			$temp = explode('/', getenv('HTTP_REFERER'));
			$found = false;
			while (list(,$stored_referer) = each($referers)) {
				if (preg_match('/^' . $stored_referer . '$/i', $temp[2]))
					$found = true;
			}
			if (!$found) {
				$errors[] = '1|You are coming from an unauthorized domain.  Please read the manual section titled &quot;<a href="' . MANUAL . '#setting_up" target="_blank">Setting Up the PHPFormMail Script</a>&quot;.';
				error_log('[PHPFormMail] Illegal Referer. (' . getenv('HTTP_REFERER') . ')', 0);
			}
			return $found;
		} else {
			$errors[] = '0|Sorry, but I cannot figure out who sent you here.  Your browser is not sending an HTTP_REFERER.  This could be caused by a firewall or browser that removes the HTTP_REFERER from each HTTP request you submit.';
			error_log('[PHPFormMail] HTTP_REFERER not defined. Browser: ' . getenv('HTTP_USER_AGENT') . '; Client IP: ' . getenv('REMOTE_ADDR') . '; Request Method: ' . getenv('REQUEST_METHOD') . ';', 0);
			return false;
		}
	} else {
		$errors[] = '1|There are no referers defined.  All submissions will be denied.  Please read the manual section titled &quot;<a href="' . MANUAL . '#setting_up" target="_blank">Setting Up the PHPFormMail Script</a>&quot;.';
		error_log('[PHPFormMail] You have no referers defined.  All submissions will be denied.', 0);
		return false;
	}
}

/////////////////////////////////
function doEncrypt($Data, $Key)
{
// encrypting  a[] with key k[] into e[]
// a[] = array to be encrypted
// k[] = key of truly random gibberish
// e[] = encrypted data

	for( $i = 0; $i < strlen($Data); $i++)
	{
		$c = substr($Data, $i, 1);
		$a[$i] = ord($c);
	}
	
	for( $i = 0; $i < strlen($Data); $i++)
	{
		if ($i < strlen($Key))
		{
			$c = substr($Key, $i, 1);
			$k[$i] = ord($c);
		}
		else
			$k[$i] = 65 + $i;
	}
	
	for ( $i=0; $i < strlen($Data); $i++ )
   	{
   		$e[$i] = $k[$i] ^ $a[$i];
   	}
	
	$encrypted = "";
	for ( $i = 0; $i < strlen($Data); $i++ )
	{
		$encrypted = $encrypted. decToHex($e[$i]);
	}
	return($encrypted);
	
}

function decToHex($dec)
{
	$hexStr = "0123456789ABCDEF";
	$low = $dec % 16;
	$high = ($dec - $low)/16;
	$hex = "";
	$hex = substr($hexStr, $high, 1) . substr($hexStr, $low, 1);
	return $hex;
}

/////////////////////////////////////////////////////////////
function DisplayError($err_code, $go_back)
{
	if (strpos($go_back, "?") === false)
		$go_back .= "?err=" . $err_code;
	else
		$go_back .= "&err=" . $err_code;
		
	header("Location: $go_back");
	exit;
}

?>