<?php
// Reset Password, copyright 2012, EB Dynamics, Inc., Ed Lemmers
// For licensing, see license.txt.
//
// 
session_start();
$userid = $_SESSION['userid'];

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


// Module for performaing actual email operation.
include("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("clean_var.php");

// If alternate go back specified, then use that if any errors.  This is usefule if sending page session expires if back button is used.
if ($_POST['alt_go_back'])
{
	$go_back = $_POST['alt_go_back'];
	$delim = "?";
	foreach($_POST as $key => $val)
	{
		$go_back .= $delim . $key . "=" . $val;
		$delim = "&";
	}
}
else
	$go_back = "javascript:history.go(-1);";

$UserID = $_POST['UserID'];
$password = $_POST['password'];
$password_confirm = $_POST['password_confirm'];
$redirect = $_POST['redirect'];
$user_table = CleanVar($_POST['user_table']);
$subject = $_POST['subject'];
$reply_to = $_POST['reply_to'];
$from = $_POST['from'];

if ($_POST['html'])
	$html = $_POST['html'];	// html
else
	$html = 0;	// text
	
if ($_POST['no_mime'])
	$no_mime = 1;	// Certain servers can't handle mime messages such as GoDaddy hosting.
else
	$no_mime = 0;
	
// Used in conjunciton with $referers to eliminate atacks from remote servers.
$valid_env = array('REMOTE_HOST', 'REMOTE_ADDR', 'REMOTE_USER', 'HTTP_USER_AGENT');

// Check hack attempt.  Sent user ID should be same as logged-in user ID.
if ($userid != $UserID)
	exit;

// Check referers to make sure SPAM bot is not trying to brake in.
if (!check_referer($referers))
{
	$err = "You do not appear to be a valid.  If this is in error, go back and try again.<br />\n<a href='$go_back'>Click here</a> to return to the previous page, or use your 'Back' button.";
	$button_label = "OK";
	include("error_msg.php");
	exit;
}

// Verify that 'password' has been filled in and 'password_confirm' matches 'password'.
if ((!$password) || ($password != $password_confirm))
{
	$err = "Your password is blank or does not match the confirm.  Please fill in your password.<br />\n<a href='$go_back'>Click here</a> to return to the previous page, or use your 'Back' button.";
	$button_label = "OK";
	include("error_msg.php");
	exit;
}

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

if ($num_results < 1)
	exit;
$email = $row['email'];

// Insert salt into password.
$pos = rand(0, (strlen($password)-1) );
$pass1 = substr($password, 0, $pos);
$pass2 = substr($password, $pos);
$salted_pass = $pass1 . BWB_PUB_SALT . $pass2;
// Encrypt password.
$encrypt_password = doEncrypt($salted_pass, $UserID);
// Update user table with new password.
$query = "UPDATE `$user_table` SET `password`='" . $encrypt_password . "' WHERE `UserID`=:UserID";
$stmt = $bwb_dbh->prepare($query);
$stmt->execute(array(':UserID' => $UserID));


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

$content_type = "application/octet-stream";

if ($from)
	$from_email = "$from";
else
	$from_email = "Password Change Form <$email>";
	
$to_email = $email;
//$cc_email = "ed@ebdynamics.com";	//for testing

	
if ($html == 1)
	$lf = "<br>";
else
	$lf = "\n";

if ($html == 1)
{
	$msg = "Your new password is <b>" . $password . "</b>.";
	$msg = "<b>$subject</b>$lf" . $msg;
}
else
{
	$msg = "Your new password is " . $password . ".";
	$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();

$email_ext = substr($to_email, strlen($to_email) - 8);
if ($email_ext == "@aol.com")	// AOL emails
	mail($to_email, $subject, $msg);



// Go to desired next page.
$go_back = $redirect;
$err = "Your password of $password has been updated.  Please make a note of it and save it in a safe place.<br />\n<a href='$go_back'>Click here</a> to continue.";
	$button_label = "Continue";
	include("error_msg.php");
exit;

/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// Check for valid emails. //////////////////////////////////////////////
function check_email_address($email) {
// First, we check that there's one @ symbol, and that the lengths are right
	if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
		// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
		return false;
	}
	// Split it into sections to make life easier
	$email_array = explode("@", $email);
	$local_array = explode(".", $email_array[0]);
	for ($i = 0; $i < sizeof($local_array); $i++) {
		if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
		return false;
		}
	}
	if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
		$domain_array = explode(".", $email_array[1]);
		if (sizeof($domain_array) < 2) {
			return false; // Not enough parts to domain
		 }
		for ($i = 0; $i < sizeof($domain_array); $i++) {
			 if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
				return false;
			 }
		}
	 }
	 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 (eregi('^' . $stored_referer . '$', $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;
}

?>