<?php 
require_once "app/class-user-manager.php";
require_once "app/class-wf-engine.php";


/**
 * Performs login operations
 * 
 * Shows login page and performs authentication
 * 
 * @author balexandre
 * @version 1.0.1
 * @package Backend
 * 
 */

class context_login extends context {
  
	
  	/**
  	 * 
  	 * Context entry point, shows login screen
  	 */
	function index()  {
	   
		LanguageManager::load_resources(__DEFAULTLANG);
		$this->screen('login',null,'login');
		
	}
	
	/**
	 * 
	 * Performs authentication of the given credentials
	 */
	
	function authenticate() {

		if ($_POST['captcha'] && __CAPTCHA_LOGIN) {
			
			if ($_POST['captcha']!= $_SESSION['captcha']['code']) {
				$this->screen('login',array('error'=>3),"login");
				exit();
			}
		}
	
	
		if ($_POST['username'] && $_POST['password']) {
                    
                
			$em = new EntityManager('users');
			

			$result = $em->load("username=?",array($_POST['username']));

			$user = $result[0];
			
			if(UserManager::validate_user($user,$_POST['username'],filter_input(INPUT_POST, 'password')))  {
				
				$user->loginattempts=0;
				
				$user->save();
				
				
				Session::reset();
				Session::set_active();
				
				Session::set_user($user);
  				
  				$um = new UserManager();
  				$um->load_user_roles();
  				$um->get_active_userrole(); //load default role;
  				$um->get_user_org(); // load user org
  				
  				$wfe = new WFEngine();
  				//$wfe->get_workflows();  // load user workflows
  				
  				/** log login */
  				LogManagement::log("User login sucessfull","login","login",__LOGTYPE_SECURITY);
  				/** end log login*/
  				
  				$languageid = $user->languageid ? $user->languageid : __DEFAULTLANG;

  				$language = new Entity("languages",$languageid);
  					  				
  				// language descriptions load
				if(!Session::get_language()){
					Session::set_language($language);
					
					LanguageManager::load_descriptions();	
					LanguageManager::load_resources();
				}
  				//-------
  				
				if(Session::get_URI()) {
					$goto = Session::get_URI();
					Session::set_URI(null);
  					header("Location: ".$goto);
  				} else {
    				header("Location: ".__SITEBASE."/");
  				}
	  			
		  			
		   	} else {
		   		
		   		if ($user) {   /* BLOCK USER */
		   			$already_blocked = $user->blocked;
		   			$user->loginattempts++;
		   			if ($user->loginattempts>=__LOGIN_ATTEMPTS){
		   				$user->blocked = true;
		   				if (!$already_blocked) {
		   					//AlertManager::new_alert(1, __ROLE_SECURITY_MANAGER, $user->organisationid, $contextid,"User ".$user->username." have been blocked",  $user->id);
		   					AlertManager::new_alert(Alert::TYPE_USER_LOCKED, __ROLE_SECURITY_MANAGER, __DATA_COLLECTOR_ORGANISATION, $user->id,$user->username);
		   				}
		   			}
		   			$user->save();
		   		}
		   		
		   		
		   		if($user->blocked) {
		   			
		   			/** log login Error*/
	  				LogManagement::log("User blocked with username:".$_POST['username'],"Login","Login",__LOGTYPE_SECURITY);
	  				/** end log login Error*/
	  				$this->screen('login',array('error'=>2,'user'=>$user),"login"); //user blocked
		   		} else {
		   			/** log login Error*/
	  				LogManagement::log("Unsuccessfull Login with username:".$_POST['username'],"Login","Login",__LOGTYPE_SECURITY);
	  				/** end log login Error*/
	  				$this->screen('login',array('error'=>1),"login");
		   		}
		   		
		   		
		   	}
		}
		else {
			$this->screen('login',array('error'=>1),"login");
		}
	}
	
	/**
	 * 
	 * Requests a user unblock
	 */
	
	function requestunblock() {
		
		$username = $_REQUEST['u'];
		
		$em = new EntityManager('users');
		
		$result = $em->load('username=?',array($username));
		
		$user = $result[0];

		if ($user->blocked) {
			
			//AlertManager::new_alert(1, __ROLE_SECURITY_MANAGER, $user->organisationid, $contextid,"User ".$user->username." requested to be unblock",  $user->id);
			AlertManager::new_alert(Alert::TYPE_USER_REQUEST_UNLOCK, __ROLE_SECURITY_MANAGER, __DATA_COLLECTOR_ORGANISATION, $user->id,$user->username);
			LogManagement::log("User requested unlock with username:".$user->username,"Login","Login",__LOGTYPE_SECURITY);
				
			$this->screen('login',array('message_unblock_requested'=>1),"login");	
		
		} else {
			
			$this->screen('login',null,"login");
		}
		
		
	}
	
	/**
	 * 
	 * 
	 * Shows a lost password screen
	 */
	
	function lostpassword() {
		
		$this->screen('lost_password',null,"login");
		
	} 
	
	/**
	 * 
	 * Requests a new password
	 */
	function requestpassword() {
		
                $username = preg_replace('/[^A-Za-z0-9\-]/', '', $_POST['username']);
		//$username = $_REQUEST['username'];
		
		$em = new EntityManager('users');
		
		$result = $em->load('username=?',array($username));
		
		$user = $result[0];

		if ($user) {
			
			//AlertManager::new_alert(1, __ROLE_SECURITY_MANAGER, $user->organisationid, $contextid,"User ".$user->username." requested a new password",  $user->id);
			AlertManager::new_alert(Alert::TYPE_USER_REQUEST_UNLOCK, __ROLE_SECURITY_MANAGER, __DATA_COLLECTOR_ORGANISATION, $user->id,$user->username);
			LogManagement::log("User requested new password with username:".$user->username,"Login","Login",__LOGTYPE_SECURITY);
			
			$this->screen('login',array('message_password_requested'=>1),"login");	
		
		} else {
			
			$this->screen('login',null,"login");
		}
		
	}
    
}
 ?>