<?php

/**
 * This file is part of LEPTON Core, released under the GNU GPL
 * Please see LICENSE and COPYING files in your package for details, specially for terms and warranties.
 * 
 * NOTICE:LEPTON CMS Package has several different licenses.
 * Please see the individual license in the header of each single file or info.php of modules and templates.
 *
 * @author          LEPTON Project
 * @copyright       2010-2021 LEPTON Project
 * @link            https://lepton-cms.org
 * @license         http://www.gnu.org/licenses/gpl.html
 * @license_terms   please see LICENSE and COPYING files in your package
 *
 */

class LEPTON_tfa
{
	public $key_new = 0;

   /**
     *  @var    object  The reference to the *Singleton* instance of this class.
     *  @notice         Keep in mind that a child-object has to have his own one!
     */
    static $instance;
	
    /**
     *  Return the instance of this class.
     *
     */
    public static function getInstance()
    {
        if (null === static::$instance)
        {
            static::$instance = new static();
            static::$instance->initialize();
        }
        return static::$instance;
    }
	
	public function initialize( $user = 'xxx')
	{
		$database = LEPTON_database::getInstance();
		

		$temp_value = $database->get_one("SELECT pin FROM ".TABLE_PREFIX."users WHERE username = '".$user."' ");
		if($temp_value == -1)
		{
			$this->key_new = true;
		} 
		else 
		{
			$this->key_new = false;
		}

	}

	public function set_fe_pin($id = '') 
	{
		if ( $id == 'create') 
		{
			if(isset($_SESSION['USERNAME']) && isset($_SESSION['Tokens']))
			{
				
				$token = $_SESSION['Tokens'][0];
				$oTWIG = lib_twig_box::getInstance();
				$pin = random_int(100000, 999999);

				$page_values = array(
					'oTFA'			=> $this,
					'ACTION_URL'	=> LEPTON_URL."/account/tfa.php",
					'token'			=> $token,
					'post_login'	=> $_POST,
//					'hash'			=> time(),
					'pin'			=> $pin,
					'new'			=> $this->key_new,
				);

				$oTWIG->registerPath( LEPTON_PATH."/account/templates/" );
				echo $oTWIG->render(
					"tfa_form.lte",
					$page_values
				);					
				
			} 
		}
		
		elseif ( $id == 'save') 
		{
			if(isset($_POST['save']) && strlen($_POST['save']) == 6 )
			{
				
				$user = $_SESSION['USERNAME'];
				$key_temp = intval($_POST['save']);
				$pin_encode = password_hash( $key_temp, PASSWORD_DEFAULT);
				
				// save pin
				$database = LEPTON_database::getInstance();
				$database->simple_query("UPDATE ".TABLE_PREFIX."users SET `pin` = '".$pin_encode."' WHERE username = '".$user."' ");
				if ( $database->is_error() ) {
					echo LEPTON_tools::display($database->get_error(),'pre','ui red message');
			
				}
				// modify pin_set
				$database->simple_query("UPDATE ".TABLE_PREFIX."users SET `pin_set` = 1 WHERE username = '".$user."' ");
				if ( $database->is_error() ) {
					echo LEPTON_tools::display($database->get_error(),'pre','ui red message');
			
				}
				header('Location: '.LEPTON_URL.'/account/logout.php');
				exit();
				
			} 

		}
		else 
		{
			header('Location: '.LEPTON_URL.'/account/logout.php');
		}		
	
	}	

	public function display_fe_pin( $id )	
	{
		if ( $id == 'display') 
		{
			$oTWIG = lib_twig_box::getInstance();

			$page_values = array(
				'oTFA'			=> $this,
				'ACTION_URL'	=> LEPTON_URL."/account/tfa.php",
				'post_login'	=> $_POST,
				'token'			=> $_SESSION['Tokens'][0],
				'new'			=> false,
			);

			$oTWIG->registerPath( LEPTON_PATH."/account/templates/" );
			echo $oTWIG->render(
				"tfa_form.lte",
				$page_values
			);		
			
		} 

		elseif ( $id == 'forward') 
		{
		
			if(isset($_POST['token']) && strlen($_POST['pin']) == 6 )
			{			
				$user = $_SESSION['USERNAME'];
				$postKey = intval($_POST['pin']);	
			
				// get PIN from database
				$database = LEPTON_database::getInstance();
				$result = $database->get_one("SELECT pin FROM ".TABLE_PREFIX."users WHERE username = '".$user."' ");
				if($result){
					$dbKey = $result;
				}
				
				$redirect = strip_tags((isset($_POST['redirect'])) ? $_POST['redirect'] : ((isset($_GET['redirect'])) ? $_GET['redirect'] : ''));
				
				if($redirect != '')
				{
					$set_redirect = '?redirect='.$redirect.'&leptoken='.get_leptoken();
				}
				else
				{
					$set_redirect = '?leptoken='.get_leptoken();
				}
				
				// validate PIN
				if(password_verify ($postKey, $dbKey) === true)
				{
					// prevent logout
					$database->simple_query("UPDATE ".TABLE_PREFIX."users SET `pin_set` = 2 WHERE username = '".$user."' ");
					if ( $database->is_error() ) {
						echo LEPTON_tools::display($database->get_error(),'pre','ui red message');
				
					}	
				
					header('Location: '.LEPTON_URL.$set_redirect.'');					
				} 
				else
				{
					header('Location: '.LEPTON_URL.'/account/logout.php');
				}
				
			} 
		} 
		else 
		{
			header('Location: '.LEPTON_URL.'/account/logout.php');
		}		
			
	}
	
	public function set_be_pin( $id ) 
	{
		if ( $id == 'create') 
		{
			if(isset($_SESSION['USERNAME']))
			{
				$oTWIG = lib_twig_box::getInstance();
				$pin = random_int(100000, 999999);

				$page_values = array(
					'oTFA'			=> $this,
					'ACTION_URL'	=> ADMIN_URL."/login/tfa.php",
					'token'			=> $_SESSION['Tokens'][0],
					'post_login'	=> $_POST,
					'pin'			=> $pin,
					'new'			=> $this->key_new,
				);

				$oTWIG->registerPath( THEME_PATH."theme","tfa" );
				echo $oTWIG->render(
					"@theme/tfa_form.lte",
					$page_values
				);					
				
			} 
			else 
			{
				header('Location: '.LEPTON_URL);			
			}
		}

		if ( $id == 'save') 
		{
			
			if(isset($_POST['save']) && strlen($_POST['save']) == 6 )
			{
				
				$user = $_SESSION['USERNAME'];
				$key_temp = intval($_POST['save']);
				$pin_encode = password_hash( $key_temp, PASSWORD_DEFAULT);
				
				// save PIN
				$database = LEPTON_database::getInstance();
				$database->simple_query("UPDATE ".TABLE_PREFIX."users SET `pin` = '".$pin_encode."' WHERE username = '".$user."' ");
				if ( $database->is_error() ) {
					echo LEPTON_tools::display($database->get_error(),'pre','ui red message');
			
				}
				// modify pin_set
				$database->simple_query("UPDATE ".TABLE_PREFIX."users SET `pin_set` = 1 WHERE username = '".$user."' ");
				if ( $database->is_error() ) {
					echo LEPTON_tools::display($database->get_error(),'pre','ui red message');
			
				}				
				header('Location: '.ADMIN_URL.'/logout/index.php');
				exit();
				
			} 
			else 
			{
				header('Location: '.ADMIN_URL.'/logout/index.php');
			}
		}
	}	
	public function display_be_pin( $id )	
	{
		if ( $id == 'display') 
		{
			$oTWIG = lib_twig_box::getInstance();

			$page_values = array(
				'oTFA'			=> $this,
				'ACTION_URL'	=> ADMIN_URL."/login/tfa.php",
				'token'			=> $_SESSION['Tokens'][0],
				'new'			=> false,
			);

			$oTWIG->registerPath( THEME_PATH."theme","tfa" );
			echo $oTWIG->render(
				"@theme/tfa_form.lte",
				$page_values
			);		
			
		} 

		elseif ( $id == 'forward') 
		{
				
			if(isset($_POST['token']) && strlen($_POST['pin']) == 6 )

			{							
				$user = $_SESSION['USERNAME'];
				$postKey = intval($_POST['pin']);	
			
				// get PIN from database
				$database = LEPTON_database::getInstance();
				$result = $database->get_one("SELECT pin FROM ".TABLE_PREFIX."users WHERE username = '".$user."' ");
				if($result){
					$dbKey = $result;
				}

				// validate PIN
				if(password_verify ($postKey, $dbKey) === true)
				{
					// modify pin_set
					$database->simple_query("UPDATE ".TABLE_PREFIX."users SET `pin_set` = 2 WHERE username = '".$user."' ");
					if ( $database->is_error() ) 
					{
						echo LEPTON_tools::display($database->get_error(),'pre','ui red message');				
					}	
					
					header('Location: '.ADMIN_URL.'/start/index.php?leptoken='.$_POST['token']);				
				} 
				else
				{
					header('Location: '.ADMIN_URL.'/logout/index.php');
				}
				
			} 
		} 
		else 
		{
			header('Location: '.ADMIN_URL.'/logout/index.php');
		}		
			
	}
	
}
