<?php
/********************************************************************************
 MachForm
  
 Copyright 2007-2014 Appnitro Software. This code cannot be redistributed without
 permission from http://www.appnitro.com/
 
 More info at: http://www.appnitro.com/
 ********************************************************************************/	
	require('includes/init.php');
	
	require('config.php');
	require('includes/db-core.php');
	require('includes/helper-functions.php');
	require('lib/swift-mailer/swift_required.php');
	require('lib/password-hash.php');
	
	$target_email = strtolower(trim($_POST['target_email']));

	if(empty($target_email)){
		die("پارامترها نامعتبر است.");
	}
	
	
	$dbh = mf_connect_db();
	$mf_settings = mf_get_settings($dbh);
	
	//validate the email address
	$is_registered_email = false;
	
	$query  = "SELECT count(`user_email`) total_email FROM `".MF_TABLE_PREFIX."users` WHERE `user_email`=? and `status`=1";
	$params = array($target_email);
	
	$sth = mf_do_query($query,$params,$dbh);
	$row = mf_do_fetch_result($sth);
	if(!empty($row['total_email'])){
		$is_registered_email = true;
	}

	//if the wrong email addess being entered, return error message
	if($is_registered_email === false){
		echo '{"status" : "error", "message" : "آدرس ایمیل اشتباه است. لطفا دوباره امتحان کنید."}';
		return true;
	}

	$new_password = generate_random_string('ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789',10);
	$hasher 	  = new PasswordHash(8, FALSE);
	$new_password_hash = $hasher->HashPassword($new_password);
	$ip_address = $_SERVER['REMOTE_ADDR'];

    $subject = "reset my password in formsaz";
    $email_content =<<< EOT
<table style='font-family:Tahoma;font-size:12px;text-align:right;direction:rtl;-webkit-border-radius: 8px;-moz-border-radius: 8px;border-radius: 8px;border:1px solid;background:#F3F3F3;'>
<tbody><tr>
<td style='font-family:Tahoma;font-size:12px;border-bottom:1px solid #dedede;padding:5px 10px'><strong>
با عرض سلام ، رمز عبور جدید برای شما صادر شد . شما میتوانید از طریق رمز عبور زیر به سامانه فرم ساز خود وارد شوید<br>از طریق این آی پی دستور رمز عبور جدید صادر شده : {$ip_address}</strong></td>
</tr>
<tr style='background-color:#f3f7fb'>
<td style='font-family:Tahoma;font-size:12px;border-bottom:1px solid #dedede;padding:5px 10px;'><strong>
رمز عبور جدید : {$new_password}
</strong></td>
</tr>
</tbody>
</table>
EOT;
    	
    $subject = utf8_encode($subject);
    	
    //create the mail transport
	if(!empty($mf_settings['smtp_enable'])){
		$s_transport = Swift_SmtpTransport::newInstance($mf_settings['smtp_host'], $mf_settings['smtp_port']);
			
		if(!empty($mf_settings['smtp_secure'])){
			$s_transport->setEncryption('tls');
		}
			
		if(!empty($mf_settings['smtp_auth'])){
			$s_transport->setUsername($mf_settings['smtp_username']);
  			$s_transport->setPassword($mf_settings['smtp_password']);
		}
	}else{
		$s_transport = Swift_MailTransport::newInstance(); //use PHP mail() transport
	}
    	
    //create mailer instance
	$s_mailer = Swift_Mailer::newInstance($s_transport);
		
	$from_name  = html_entity_decode($mf_settings['default_from_name'],ENT_QUOTES);
	$from_email = $mf_settings['default_from_email'];
		
	if(!empty($target_email)){
		$s_message = Swift_Message::newInstance()
		->setCharset('utf-8')
		->setMaxLineLength(1000)
		->setSubject($subject)
		->setFrom(array($from_email => $from_name))
		->setSender($from_email)
		->setReturnPath($from_email)
		->setTo($target_email)
		->setBody($email_content, 'text/html');

		//send the message
		$send_result = $s_mailer->send($s_message);
		if(empty($send_result)){
			echo "خطا در ارسال ایمیل";
		}else{
			//commit the new password into the database
			$query = "UPDATE ".MF_TABLE_PREFIX."users SET user_password = ? WHERE user_email = ? and `status`=1";
		   	$params = array($new_password_hash,$target_email);
		   	mf_do_query($query,$params,$dbh);
		}
	}
	
   	echo '{"status" : "ok", "message" : "رمز عبور جدید به آدرس ایمیل شما ارسال شد."}';
   	
   	function generate_random_string($valid_chars, $length){
	   
	    $random_string = "";
	    $num_valid_chars = strlen($valid_chars);

	    for ($i = 0; $i < $length; $i++){
	        $random_pick = mt_rand(1, $num_valid_chars);
	        $random_char = $valid_chars[$random_pick-1];
	        $random_string .= $random_char;
	    }
	    return $random_string;
	}
?>