<?php
/*+**********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.1
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 ************************************************************************************/

class Users_Login_Action extends Vtiger_Action_Controller {

	function loginRequired() {
		return false;
	}

	function checkPermission(Vtiger_Request $request) {
		return true;
	} 

	function process(Vtiger_Request $request) {
		$username = $request->get('username');
		$password = $request->getRaw('password');
		$password = empty($password) ? $password : base64_decode(str_rot13($password));
		$token = $request->get('g-recaptcha-response');

		$user = CRMEntity::getInstance('Users');
		$user->column_fields['user_name'] = $username;
		$captchaScore = $this->getCaptchaScore($token);

		if ($user->doLogin($password)) {
			session_regenerate_id(true); // to overcome session id reuse.

			$userid = $user->retrieve_user_id($username);
			Vtiger_Session::set('AUTHUSERID', $userid);

			// For Backward compatability
			// TODO Remove when switch-to-old look is not needed
			$_SESSION['authenticated_user_id'] = $userid;
			$_SESSION['app_unique_key'] = vglobal('application_unique_key');
			$_SESSION['authenticated_user_language'] = vglobal('default_language');

			//Enabled session variable for KCFINDER 
			$_SESSION['KCFINDER'] = array(); 
			$_SESSION['KCFINDER']['disabled'] = false; 
			$_SESSION['KCFINDER']['uploadURL'] = "test/upload"; 
			$_SESSION['KCFINDER']['uploadDir'] = "../test/upload";
			$deniedExts = implode(" ", vglobal('upload_badext'));
			$_SESSION['KCFINDER']['deniedExts'] = $deniedExts;
			// End

			//Track the login History
			$moduleModel = Users_Module_Model::getInstance('Users');
			$moduleModel->saveLoginHistory($user->column_fields['user_name']);
			//End
						
			if(isset($_SESSION['return_params'])){
				$return_params = $_SESSION['return_params'];
			}

			header ('Location: index.php?module=Users&parent=Settings&view=SystemSetup');
			exit();
		} else {
			
			#Elias: Si el usuario ha sido bloqueado lo manda por la URL para que se muestre el mensaje en la vista
			if($_SESSION['loginBloqueado'] == 1) { $errorParam = 'loginBloqued'; }
			elseif ($captchaScore < 0.5) { $errorParam = 'failCaptcha'; }
			else { 
				$errorParam = 'login'; }

			header ('Location: index.php?module=Users&parent=Settings&view=Login&error='.$errorParam);
			exit;
		}
	}

	function getCaptchaScore($token)
	{
		$param = [
			'secret' => '6LehXnseAAAAAEGKXfNUvZa-7cq-A0e9DABTjHHj', #Google CAPTCHA secret Key
			'response' => $token
		];

		$url = 'https://www.google.com/recaptcha/api/siteverify';

		$cu = curl_init();
		curl_setopt($cu, CURLOPT_URL, $url);
		curl_setopt($cu, CURLOPT_POST, 1);
		curl_setopt($cu, CURLOPT_POSTFIELDS, http_build_query($param));
		curl_setopt($cu, CURLOPT_RETURNTRANSFER, true);
		$response = curl_exec($cu);
		curl_close($cu);

		$datos = json_decode($response, true);

		return $datos['success'] == 1 ? $datos['score'] : false;
	}
}
