<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: ForgotpasswordController.php, v 1.0 2011/06/14 20:52:11
//
class ForgotpasswordController extends Controller {
    //FUNCTION TO SEND PASSWORD 
    public function indexAction() {
        $ObjAdminuser     = new AdminuserModel();
        $ObjEmailtemplate = new EmailtemplateModel();
        $languageIDs      = $this->ObjView->languageIDs;
        $enableCaptcha    = $this->getSettingValue('security_settings', 'enable_captcha');
		$rateLimit = $this->getSettingValue('security_settings', 'security_account_blocking_attempts');
		if(empty($rateLimit) || $rateLimit<=0) {
			$rateLimit  =3;
		}
		$ipAddress = $_SERVER['REMOTE_ADDR']; 
		$attemptCount = 0;
		// Get login attempts information
		$attemptInfo = $ObjAdminuser->getLoginAttemptsInfo($ipAddress,'F');
		$attemptCount = $attemptInfo['attemptCount'];
		$firstAttemptTimestamp = $attemptInfo['firstAttemptTime'];
		// Calculate remaining attempts and time until reset for headers
		
		
        $emailbody        = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'product-assistance-password');
        if ($this->ObjForm->isValid('formForgotPassword', 'SendPassword')) {
            $valid = true;
            //If Captcha enabled
            if ($enableCaptcha) {
                $adminSecurityCode = $_REQUEST['adminSecurityCode'];
                $sesCode           = $this->ObjSession->getSession("ses_code");
                $adminSecurityCode = isset($adminSecurityCode) ? $adminSecurityCode : '';
                if ($adminSecurityCode != $sesCode) {
                    $this->setMessage("language.errInvalidSecurityCode", "message_error");
                    $this->setRedirect();
                }
            }
            if ($valid && $attemptCount < $rateLimit) {
                $emailID        = trim(addslashes($_POST['adminUserEmail']));
                $resUserDetails = $ObjAdminuser->getAdminDetailsForgotPwd($emailID);
				if(empty($resUserDetails )) {					
					$ObjAdminuser->recordLoginAttempt($ipAddress,'F');
				}
                $userStatus     = $resUserDetails['adminUserStatus'];
                if ($userStatus == 'Locked') {
                    $lockedTime     = strtotime($resUserDetails['adminUserLockedDate']);
                    $currentTime    = strtotime(date("Y-m-d H:i:s"));
                    $diff           = abs($currentTime - $lockedTime);
                    $years          = floor($diff / (365 * 60 * 60 * 24));
                    $months         = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
                    $days           = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));
                    $hours          = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24) / (60 * 60));
                    $diff_minuts    = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60) / 60);
                    $diff_minuts    = $diff / 60;
                    $blockingPeriod = $this->getSettingValue('security_settings', 'blocking_period');
                    if ($diff_minuts > $blockingPeriod) {
                        $resActivateUserAccount = $ObjUser->activateUserAccount($emailID);
                    }
                }
                if ($resUserDetails && $userStatus == 'Active') {
					$ObjAdminuser->clearOldAttempts('F','',$ipAddress);
                    $siteName                       = $this->getSettingValue('site_settings', 'site_name');
                    $siteUrl                        = $this->getSettingValue('site_settings', 'global_http_url');
                    $companyLogo                    = $this->getSettingValue('company_information', 'company_logo');
                    $mail_settings                  = $this->getSettingValue('mail_settings');
                    $mail_settings['smtp_password'] = $this->encryptDecrypt("decrypt", $mail_settings['smtp_password']);
                    $from                           = array(
                        $emailbody['emailFromEmail'],
                        $emailbody['emailFromName']
                    );
                    $subject                        = $emailbody['emailSubject'];
                    $bodytag                        = str_replace('{$siteName}', $siteName, $emailbody['emailHtml']);
                    $adminUserLoginPass             = $ObjAdminuser->ChangeAdminuserPassword($emailID);
                    $bodytag                        = str_replace('{$password}', $adminUserLoginPass, $bodytag);
                    $bodytag                        = str_replace('{$siteName}', $siteName, $bodytag);
                    $bodytag                        = str_replace('{$userName}', $resUserDetails['adminUserLoginName'], $bodytag);
                    $bodytag                        = str_replace('{$companyLogo}', $companyLogo, $bodytag);
                    $this->ObjView->assign('emailbody', $bodytag);
                    $this->ObjView->assign('companyLogo', $companyLogo);
                    $this->ObjView->assign('siteUrl', $siteUrl);
                    $this->ObjView->assign('siteName', $siteName);
                    $body    = $this->ObjCommon->fetch("email_templates/Layout.tpl");
                    $ObjMail = new Mail($mail_settings);
                    $ObjMail->IsHTML();
                    $ObjMail->sendMail($from, $emailID, $subject, $body);
                    if ($ObjMail->Send()) {
                        $this->setMessage("language.msgNewsletterSent", "message_success");
                        $this->setRedirect();
                    }
                } else if ($resUserDetails && ($resUserDetails['adminUserStatus'] == 'Blocked' || $resUserDetails['adminUserStatus'] == 'Inactive')) {
					$ObjAdminuser->recordLoginAttempt($ipAddress,'F');
                    $this->setMessage("language.errMailNotSent", "message_error");
                } else {
					$ObjAdminuser->recordLoginAttempt($ipAddress,'F');
                    $this->setMessage("language.errEmailDoesnotexistCustom", "message_error");					
                }
            } else {
				header('HTTP/1.1 429 Too Many Requests');
				$this->setMessage("Too many attempts. Please try again later.", "message_error");
                 
			}
        }
        $this->ObjView->assign('enableCaptcha', $enableCaptcha);
        $this->ObjView->assign('fromEmail', $emailbody['emailFromEmail']);
		$attemptInfo = $ObjAdminuser->getLoginAttemptsInfo($ipAddress,'F');
		$attemptCount = $attemptInfo['attemptCount'];
		$firstAttemptTimestamp = $attemptInfo['firstAttemptTime'];
		$remainingAttempts = $rateLimit - $attemptCount;//-1;		
		$rateLimitWindow = 15 * 60; // 15 minutes in seconds
		//$firstAttemptTimestamp = '';
		$firstAttemptTimestamp = strtotime($firstAttemptTimestamp);
		$timeUntilReset = ($firstAttemptTimestamp + $rateLimitWindow) - time();
		
		header('X-RateLimit-Limit: ' . $rateLimit);
		header('X-RateLimit-Remaining: ' . $remainingAttempts);
		header('X-RateLimit-Reset: ' . (time() + $timeUntilReset));
        $this->ObjView->display('ForgotPassword.tpl');
    }
    //END OF FUNCTION
    //TO DISPALY SECURITY CAPTCHA
    public function imageCaptchaAction() {
        $ObjAdminuser = new AdminuserModel();
        $style        = $this->getSettingValue('security_settings', 'captcha');
        $captcha      = $ObjAdminuser->CaptchaSecurityImages($this->ObjSession, '120', '40', '6', $style);
    }
    //END OF FUNCTION
}