<?php
/*
	FusionPBX
	Version: MPL 1.1

	The contents of this file are subject to the Mozilla Public License Version
	1.1 (the "License"); you may not use this file except in compliance with
	the License. You may obtain a copy of the License at
	http://www.mozilla.org/MPL/

	Software distributed under the License is distributed on an "AS IS" basis,
	WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
	for the specific language governing rights and limitations under the
	License.

	The Original Code is FusionPBX

	The Initial Developer of the Original Code is
	Mark J Crane <markjcrane@fusionpbx.com>
	Portions created by the Initial Developer are Copyright (C) 2008-2020
	the Initial Developer. All Rights Reserved.

	Contributor(s):
	Mark J Crane <markjcrane@fusionpbx.com>
*/

//add multi-lingual support
	$language = new text;
	$text = $language->get(null,'core/user_settings');

//get action, if any
	if (isset($_REQUEST['action'])) {
		$action = $_REQUEST['action'];
	}

//retrieve parse reset key
	if ($action == 'define') {
		$key = $_GET['key'];
		$key_part = explode('|', decrypt($_SESSION['login']['password_reset_key']['text'], $key));
		$username = $key_part[0];
		$domain_uuid = $key_part[1];
		$password_submitted = $key_part[2];

		//get current salt, see if same as submitted salt
			$sql = "select password from v_users ";
			$sql .= "where domain_uuid = :domain_uuid ";
			$sql .= "and username = :username ";
			$parameters['domain_uuid'] = $domain_uuid;
			$parameters['username'] = $username;
			$database = new database;
			$password_current = $database->select($sql, $parameters, 'column');
			unset($sql, $parameters);

		//set flag
			if ($username != '' && $password_submitted == $password_current) {
				$password_reset = true;
				$_SESSION['valid_username'] = $username;
				$_SESSION['valid_domain'] = $domain_uuid;
			}
			else {
				header("Location: /login.php");
				exit;
			}
	}

//send password reset link
	if ($action == 'request') {
		if (valid_email($_REQUEST['email'])) {
			$email = $_REQUEST['email'];

			//see if email exists
				$sql = "select ";
				$sql .= "username, ";
				$sql .= "password, ";
				$sql .= "domain_uuid ";
				$sql .= "from ";
				$sql .= "v_users ";
				$sql .= "where user_email = :email ";
				$parameters['email'] = $email;
				$database = new database;
				$results = $database->select($sql, $parameters, 'all');
				unset($sql, $parameters);

			//check for duplicates
				if (is_array($results) && @sizeof($results) != 0) {

					if (@sizeof($results) == 1) {
						$result = $results[0];

						if ($result['username'] != '') {

							//generate reset link email and body variables
								$key = encrypt($_SESSION['login']['password_reset_key']['text'], $result['username'].'|'.$result['domain_uuid'].'|'.$result['password']);
								$reset_link = "https://".$_SESSION['domain_name'].PROJECT_PATH."/login.php?action=define&key=".urlencode($key);
								$reset_button = email_button(strtoupper($text['label-reset_password']), $reset_link, '#2e82d0', '#fff');
								$logo_full = 'data:image/png;base64,[encoded data, 29316 characters]';
								$logo_shield = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB8AAAAeCAYAAADU8sWcAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAACVVJREFUeNqcVgtwlNUV/v59b3Y3u2Gzm2XJg7wJIUASSBShToECArUwjhAqVVt8tEVn+lBbRtFAtQ4gPlBaFftQUSi+WpmkKPJQCkyCgBBDSMhrEzab3Wyy2ezj3/0f+/f8a9JBC07wzny789+593z3nHPPdy4jSRJGh2L0P4Grj1TCRIKDMIGgJjCj63nCEMFD6CNEMI6hGjVwNVI7oVqGGI9XBFyuyUPd3bZQf39aNBBQCrEYEqJIFlTQ6PVItVgEg9MZMGRleUxOZ4fBaGwiw6dofwNh4GrkzBWey0NHWEpY6b1wYf6lI0ecPY2N8LW0INjTg3gwCFEmHV0sjbosn36SUgmrxQJDZiashYVIKSqCQf4vKPA4ysoOm8zmF0cP8n/kZsK9bCBwT+OePcVf7NuHS8eOYSSRSMbWQDARtFotGPJU9piPxyHSXp3ZDE1GBkw8nzxAqtUKY3o6DDTPmExgJk5EkNYWrFnTbCsre53MeAnvyamRw54X9Pk+OLB16/Rju3ahd2QENposLilBzuzZyJ5WknAU5klmm1XSGVLAKBSQBA4DHj/jbutmXP85ruhqbICgViPKMNCEw9AQqYFgzc+HY9EiXDp0CMFhNts22LbJ9daz+kl3P3WXKtVaI5OXHtq1a/qz27fjlqJi3P7oBqFq1Y8E/eQSZjSiT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nT6PWGaXWKL8BdIh7u6AyWZH78N/PKLQpcp4D35VcHjN83lD9ksXPO8+eO4+yWZU4eviR6ASTQnT/9XcmbsgHQ0E5JIpA3NOBRCyCSeu2dKot9ltob9u3WpbJx4HyAe9I79yKWjrpQml60aNSX180QvMD/rqdQu/fHpM8+7ZJva8+JMX97naanzoeu+MllzE1znKtq5dsp13VUobpLunzU+4QzbuGT3wQd+/eLPFD/efou2C8Nq+HXIaNsP+pje/RzjmEQmnTE+/QlHRcksQH6d9+Pfaul3wMmw78u1GqqnhA2v3GoSh9z/8udsZz4a41fkCgZo63x14m1zv+K8AAzpBEP7qfQcsAAAAASUVORK5CYII=';
								$domain = $_SESSION['domains'][$_SESSION['domain_uuid']]['domain_name'];

							//get email template from db
								$sql = "select template_subject, template_body from v_email_templates ";
								$sql .= "where template_language = :template_language ";
								$sql .= "and (domain_uuid = :domain_uuid or domain_uuid is null) ";
								$sql .= "and template_category = 'password_reset' ";
								$sql .= "and template_subcategory = 'default' ";
								$sql .= "and template_type = 'html' ";
								$sql .= "and template_enabled = 'true' ";
								$parameters['template_language'] = $_SESSION['domain']['language']['code'];
								$parameters['domain_uuid'] = $_SESSION['domain_uuid'];
								$database = new database;
								$row = $database->select($sql, $parameters, 'row');
								$email_subject = $row['template_subject'];
								$email_body = $row['template_body'];
								unset($sql, $parameters, $row);

							//replace variables in email body
								$email_body = str_replace('${reset_link}', $reset_link, $email_body);
								$email_body = str_replace('${reset_button}', $reset_button, $email_body);
								$email_body = str_replace('${logo_full}', $logo_full, $email_body);
								$email_body = str_replace('${logo_shield}', $logo_shield, $email_body);
								$email_body = str_replace('${domain}', $domain, $email_body);

							//send reset link
								if (send_email($email, $email_subject, $email_body)) {
									//email sent
										message::add($text['message-reset_link_sent'], 'positive', 2500);
								}
								else {
									//email failed
										message::add($eml_error, 'negative', 5000);
								}
						}
						else {
							//not found
								message::add($text['message-invalid_email'], 'negative', 5000);
						}

					}
					else {
						//matched multiple users
							message::add($text['message-email_assigned_mutliple_users'], 'negative', 5000);
					}

				}
				else {
					//not found
						message::add($text['message-invalid_email'], 'negative', 5000);
				}

		}
		else {
			//invalid email
				message::add($text['message-invalid_email'], 'negative', 5000);
		}
	}

//reset password
	if ($action == 'reset') {
		$username = trim($_REQUEST['username']);
		$password_new = trim($_REQUEST['password_new']);
		$password_repeat = trim($_REQUEST['password_repeat']);

		if ($username != '' &&
			$username == $_SESSION['valid_username'] &&
			$password_new != '' &&
			$password_repeat != '' &&
			$password_new == $password_repeat
			) {

			if (!check_password_strength($password_new, $text, 'user')) {
				$password_reset = true;
			}
			else {
				$salt = uuid();
				$sql  = "update v_users set ";
				$sql .= "password = :password, ";
				$sql .= "salt = :salt ";
				$sql .= "where domain_uuid = :domain_uuid ";
				$sql .= "and username = :username ";
				$parameters['domain_uuid'] = $_SESSION['valid_domain'];
				$parameters['password'] = md5($salt.$password_new);
				$parameters['salt'] = $salt;
				$parameters['username'] = $username;
				$database = new database;
				$database->execute($sql, $parameters);
				unset($sql, $parameters);

				message::add($text['message-password_reset'], 'positive', 2500);
				unset($_SESSION['valid_username'], $_SESSION['valid_domain']);

				header('Location: //'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
				exit;

			}
		}
		else {
			//not found
				message::add($text['message-invalid_username_mismatch_passwords'], 'negative', 5000);
				$password_reset = true;
		}
	}

//get the http values and set as variables
	$msg = isset($_GET["msg"]) ? $_GET["msg"] : null;

//set variable if not set
	if (!isset($_SESSION['login']['domain_name_visible']['boolean'])) { $_SESSION['login']['domain_name_visible']['boolean'] = null; }

//set a default login destination
	if (strlen($_SESSION['login']['destination']['url']) == 0) {
		$_SESSION['login']['destination']['url'] = PROJECT_PATH."/core/user_settings/user_dashboard.php";
	}

//add the header
	$document['title'] = $text['title-login'];
	include "resources/header.php";

//show the content
	echo "<script>";
	echo "	var speed = 350;";
	echo "	function toggle_password_reset(hide_id, show_id, focus_id) {";
	echo "		if (focus_id == undefined) { focus_id = ''; }";
	echo "		$('#'+hide_id).slideToggle(speed, function() {";
	echo "			$('#'+show_id).slideToggle(speed, function() {";
	echo "				if (focus_id != '') {";
	echo "					$('#'+focus_id).trigger('focus');";
	echo "				}";
	echo "			});";
	echo "		});";
	echo "	}";
	echo "</script>";

	echo "<br />\n";

	if (!$password_reset) {

		echo "<div id='login_form'>\n";
		echo "<form name='login' method='post' action='".$_SESSION['login']['destination']['url']."'>\n";
		echo "<input type='text' class='txt login' style='text-align: center; min-width: 200px; width: 200px; margin-bottom: 8px;' name='username' id='username' placeholder=\"".$text['label-username']."\"><br />\n";
		echo "<input type='password' class='txt login' style='text-align: center; min-width: 200px; width: 200px; margin-bottom: 8px;' name='password' placeholder=\"".$text['label-password']."\"><br />\n";
		if ($_SESSION['login']['domain_name_visible']['boolean'] == "true") {
			if (count($_SESSION['login']['domain_name']) > 0) {
				$click_change_color = ($_SESSION['theme']['login_input_text_color']['text'] != '') ? $_SESSION['theme']['login_input_text_color']['text'] : (($_SESSION['theme']['input_text_color']['text'] != '') ? $_SESSION['theme']['input_text_color']['text'] : '#000000');
				$placeholder_color = ($_SESSION['theme']['login_input_text_placeholder_color']['text'] != '') ? 'color: '.$_SESSION['theme']['login_input_text_placeholder_color']['text'].';' : 'color: #999999;';
				echo "<select name='domain_name' class='txt login' style='".$placeholder_color." width: 200px; text-align: center; text-align-last: center; margin-bottom: 8px;' onclick=\"this.style.color='".$click_change_color."';\" onchange=\"this.style.color='".$click_change_color."';\">\n";
				echo "	<option value='' disabled selected hidden>".$text['label-domain']."</option>\n";
				sort($_SESSION['login']['domain_name']);
				foreach ($_SESSION['login']['domain_name'] as &$row) {
					echo "	<option value='".escape($row)."'>".escape($row)."</option>\n";
				}
				echo "</select><br />\n";
			}
			else {
				echo "<input type='text' name='domain_name' class='txt login' style='text-align: center; min-width: 200px; width: 200px; margin-bottom: 8px;' placeholder=\"".$text['label-domain']."\"><br />\n";
			}
		}
		echo "<input type='submit' id='btn_login' class='btn' style='width: 100px; margin-top: 15px;' value='".$text['button-login']."'>\n";
		if (
			function_exists('openssl_encrypt') &&
			$_SESSION['login']['password_reset_key']['text'] != '' &&
			$_SESSION['email']['smtp_host']['text'] != ''
			) {
			echo "<br><br><a class='login_link' onclick=\"toggle_password_reset('login_form','request_form','email');\">".$text['label-reset_password']."</a>";
		}
		echo "</form>";
		echo "<script>$('#username').trigger('focus');</script>";
		echo "</div>";

		echo "<div id='request_form' style='display: none;'>\n";
		echo "<form name='request' method='post' action=''>\n";
		echo "<input type='hidden' name='action' value='request'>\n";
		echo "<input type='text' class='txt login' style='text-align: center; min-width: 200px; width: 200px; margin-bottom: 8px;' name='email' id='email' placeholder=\"".$text['label-email_address']."\"><br />\n";
		echo "<input type='submit' id='btn_reset' class='btn' style='width: 100px; margin-top: 15px;' value='".$text['button-reset']."'>\n";
		echo "<br><br><a class='login_link' onclick=\"toggle_password_reset('request_form','login_form','username');\">".$text['label-cancel']."</a>";
		echo "</form>";
		echo "</div>";

	}
	else {

		echo "<script>\n";
		echo "	function compare_passwords() {\n";
		echo "		if (document.getElementById('password') === document.activeElement || document.getElementById('password_confirm') === document.activeElement) {\n";
		echo "			if ($('#password').val() != '' || $('#password_confirm').val() != '') {\n";
		echo "				if ($('#password').val() != $('#password_confirm').val()) {\n";
		echo "					$('#password').removeClass('formfld_highlight_good');\n";
		echo "					$('#password_confirm').removeClass('formfld_highlight_good');\n";
		echo "					$('#password').addClass('formfld_highlight_bad');\n";
		echo "					$('#password_confirm').addClass('formfld_highlight_bad');\n";
		echo "				}\n";
		echo "				else {\n";
		echo "					$('#password').removeClass('formfld_highlight_bad');\n";
		echo "					$('#password_confirm').removeClass('formfld_highlight_bad');\n";
		echo "					$('#password').addClass('formfld_highlight_good');\n";
		echo "					$('#password_confirm').addClass('formfld_highlight_good');\n";
		echo "				}\n";
		echo "			}\n";
		echo "		}\n";
		echo "		else {\n";
		echo "			$('#password').removeClass('formfld_highlight_bad');\n";
		echo "			$('#password_confirm').removeClass('formfld_highlight_bad');\n";
		echo "			$('#password').removeClass('formfld_highlight_good');\n";
		echo "			$('#password_confirm').removeClass('formfld_highlight_good');\n";
		echo "		}\n";
		echo "	}\n";

		$setting['length'] = $_SESSION['users']['password_length']['numeric'];
		$setting['number'] = ($_SESSION['users']['password_number']['boolean'] == 'true') ? true : false;
		$setting['lowercase'] = ($_SESSION['users']['password_lowercase']['boolean'] == 'true') ? true : false;
		$setting['uppercase'] = ($_SESSION['users']['password_uppercase']['boolean'] == 'true') ? true : false;
		$setting['special'] = ($_SESSION['users']['password_special']['boolean'] == 'true') ? true : false;

		echo "	function check_password_strength(pwd) {\n";
		echo "		if ($('#password').val() != '' || $('#password_confirm').val() != '') {\n";
		echo "			var msg_errors = [];\n";
		if (is_numeric($setting['length']) && $setting['length'] != 0) {
			echo "		var re = /.{".$setting['length'].",}/;\n"; //length
			echo "		if (!re.test(pwd)) { msg_errors.push('".$setting['length']."+ ".$text['label-characters']."'); }\n";
		}
		if ($setting['number']) {
			echo "		var re = /(?=.*[\d])/;\n";  //number
			echo "		if (!re.test(pwd)) { msg_errors.push('1+ ".$text['label-numbers']."'); }\n";
		}
		if ($setting['lowercase']) {
			echo "		var re = /(?=.*[a-z])/;\n";  //lowercase
			echo "		if (!re.test(pwd)) { msg_errors.push('1+ ".$text['label-lowercase_letters']."'); }\n";
		}
		if ($setting['uppercase']) {
			echo "		var re = /(?=.*[A-Z])/;\n";  //uppercase
			echo "		if (!re.test(pwd)) { msg_errors.push('1+ ".$text['label-uppercase_letters']."'); }\n";
		}
		if ($setting['special']) {
			echo "		var re = /(?=.*[\W])/;\n";  //special
			echo "		if (!re.test(pwd)) { msg_errors.push('1+ ".$text['label-special_characters']."'); }\n";
		}
		echo "			if (msg_errors.length > 0) {\n";
		echo "				var msg = '".$text['message-password_requirements'].": ' + msg_errors.join(', ');\n";
		echo "				display_message(msg, 'negative', '6000');\n";
		echo "				return false;\n";
		echo "			}\n";
		echo "			else {\n";
		echo "				return true;\n";
		echo "			}\n";
		echo "		}\n";
		echo "		else {\n";
		echo "			return true;\n";
		echo "		}\n";
		echo "	}\n";

		echo "	function show_strenth_meter() {\n";
		echo "		$('#pwstrength_progress').slideDown();\n";
		echo "	}\n";
		echo "</script>\n";

		echo "<span id='reset_form'>\n";
		echo "<form name='reset' id='frm' method='post' action=''>\n";
		echo "<input type='hidden' name='action' value='reset'>\n";
		echo "<input type='text' class='txt login' style='text-align: center; min-width: 200px; width: 200px; margin-bottom: 8px;' name='username' id='username' placeholder=\"".$text['label-username']."\"><br />\n";
		echo "<input type='password' class='txt login' style='text-align: center; min-width: 200px; width: 200px; margin-bottom: 4px;' name='password_new' id='password' autocomplete='off' placeholder=\"".$text['label-new_password']."\" onkeypress='show_strenth_meter();' onfocus='compare_passwords();' onkeyup='compare_passwords();' onblur='compare_passwords();'><br />\n";
		echo "<div id='pwstrength_progress' class='pwstrength_progress pwstrength_progress_password_reset'></div>";
		echo "<input type='password' class='txt login' style='text-align: center; min-width: 200px; width: 200px; margin-top: 4px; margin-bottom: 8px;' name='password_repeat' id='password_confirm' autocomplete='off' placeholder=\"".$text['label-repeat_password']."\" onfocus='compare_passwords();' onkeyup='compare_passwords();' onblur='compare_passwords();'><br />\n";
		echo "<input type='button' class='btn' style='width: 100px; margin-top: 15px;' value='".$text['button-save']."' onclick=\"if (check_password_strength(document.getElementById('password').value)) { submit_form(); }\">\n";
		echo "<br><br><a class='login_link' onclick=\"document.location.href='login.php';\">".$text['label-cancel']."</a>";
		echo "</form>";

		echo "<script>\n";
		echo "	$('#username').trigger('focus');\n";
		// convert password fields to text
		echo "	function submit_form() {\n";
		echo "		$('input:password').css('visibility','hidden');\n";
		echo "		$('input:password').attr({type:'text'});\n";
		echo "		$('form#frm').submit();\n";
		echo "	}\n";
		echo "</script>\n";
		echo "</span>";

	}

//add the footer
	$default_login = true;
	include "resources/footer.php";

?>