<?php
// Reset Password, copyright 2012, EB Dynamics, Inc., Ed Lemmers
// For licensing, see license.txt.
//
// 
$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_connection.php");
include("../connect/config.php");
include("generate_password.php");
include("../connect/captchakeys.php");

$email = $_POST['email'];
$redirect = $_POST['redirect2'];
$user_table = $_POST['user_table2'];
$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;

require_once('recaptchalib.php');
  $resp = recaptcha_check_answer (RECAPTCHA_PRIVATE_KEY,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

  if (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
    die ("<h2 align='center'>The CAPTCHA wasn't entered correctly. Go <a href='$redirect'>back</a> and try it again.</h2>" .
         "<p align='center'>(reCAPTCHA said: " . $resp->error . ")<p>");
  }

	
// 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))
{
	echo <<<END
	<br>
	<div align="center">
	<h2>The email address $email is not valid.  Please go back and type your email address again.</h2>
	<h2><a href="javascript:history.go(-1)">Click here</a> to return to the previous page, or use your 'Back' button.</h2>
	</div>
	<br>
END;

exit;
}

// Check referers to make sure SPAM bot is not trying to brake in.
if (!check_referer($referers))
{
	echo <<<END
	<br>
	<div align="center">
	<h2>You do not appear to be a valid.  If this is in error, go back and try again.</h2>
	<h2><a href="javascript:history.go(-1)">Click here</a> to return to the previous page, or use your 'Back' button.</h2>
	</div>
	<br>
END;

	exit;
}

if (!isset($user_table) || ($user_table == ""))
{
	echo "User table is blank.  Please contact your webmaster to have a user table assigned to this page.";
	exit;
}

// Get user ID from users table by email.
$query = "SELECT * FROM `" . $user_table . "` WHERE `email`='" . $email . "'";
$result = mysql_query($query, $bwb_link);
$row = mysql_fetch_array($result);

if (mysql_num_rows($result) < 1)
{
	echo "No user was found for the email " . $email . " that you presented.  Please click <a href='" . $redirect . "'>here</a> to re-enter your email address.";
	exit;
}
$UserID = $row['UserID'];

// Create new password.
$password = GeneratePassword();
// Encrypt password.
$encrypt_password = doEncrypt($password, $UserID);
// Update user table with new password.
$query = "UPDATE `" . $user_table . "` SET `password`='" . $encrypt_password . "' WHERE `UserID`='" . $UserID . "'";
$reselt = mysql_query($query, $bwb_link);


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

$content_type = "application/octet-stream";

if ($from)
	$from_email = "$from";
else
	$from_email = "Password Reset 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 user name is <b>" . $UserID  . "</b> and your temporary password is <b>" . $password . "</b>.";
	$msg = "<b>$subject</b>$lf" . $msg;
}
else
{
	$msg = "Your user name is " . $UserID  . " and your temporary password is " . $password . ".";
	$msg = "$subject$lf" . $msg;
}

/////////// Check for robots by counting URLs. ////////////////////
$http_cnt = 0;
$pos = stripos($msg, "http");
if ($pos !== false)
{
	$http_cnt++;
	$pos2 = stripos($msg, "http", $pos + 1);
	if ($pos2 !== false)
		$http_cnt++;
}
if ($http_cnt > 1)
{
	header("Location: $redirect");
	exit;
}
/////////// Check for robots by counting URLs. ////////////////////

$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.
header("Location: $redirect");
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;
}

?>