<?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          Website Baker Project, LEPTON Project
 * @copyright       2004-2010 Website Baker Org. e.V.
 * @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
 *
 */ 

// include class.secure.php to protect this file and the whole CMS!
if (defined('LEPTON_PATH')) {	
	include(LEPTON_PATH.'/framework/class.secure.php'); 
} else {
	$oneback = "../";
	$root = $oneback;
	$level = 1;
	while (($level < 10) && (!file_exists($root.'/framework/class.secure.php'))) {
		$root .= $oneback;
		$level += 1;
	}
	if (file_exists($root.'/framework/class.secure.php')) { 
		include($root.'/framework/class.secure.php'); 
	} else {
		trigger_error(sprintf("[ <b>%s</b> ] Can't include class.secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
	}
}
// end include class.secure.php
    
    if(!function_exists("lepton_autoloader"))
    {
        require_once __DIR__."/functions/function.lepton_autoloader.php";
        spl_autoload_register( "lepton_autoloader", true);
    }
    
    // Get an instance from class database
	$database = LEPTON_database::getInstance();
		
	LEPTON_handle::include_files(
		array(
			"/framework/summary.functions.php",
			"/framework/sys.constants.php"
		)			
	);
	
	LEPTON_handle::register( "get_leptoken" );

    // Get website settings (title, keywords, description, header, and footer)
	$sql = 'SELECT `name`,`value` FROM `' . TABLE_PREFIX . 'settings` ORDER BY `name`';
	$storage = array();
	$database->execute_query( $sql, true, $storage );
	foreach ( $storage as &$row )
	{
		if ( preg_match( '/^[0-7]{1,4}$/', $row[ 'value' ] ) == true )
		{
			$value = $row[ 'value' ];
		}
		elseif ( preg_match( '/^[0-9]+$/S', $row[ 'value' ] ) == true )
		{
			$value = intval( $row[ 'value' ] );
		}
		elseif ( $row[ 'value' ] == 'false' )
		{
			$value = false;
		}
		elseif ( $row[ 'value' ] == 'true' )
		{
			$value = true;
		}
		else
		{
			$value = $row[ 'value' ];
		}
		$temp_name = strtoupper( $row[ 'name' ] );
		if ( !defined( $temp_name ) )
			define( $temp_name, $value );
	}
	unset( $row );
	
	$string_file_mode = STRING_FILE_MODE;
	define( 'OCTAL_FILE_MODE', (int) octdec( $string_file_mode ) );
	$string_dir_mode = STRING_DIR_MODE;
	define( 'OCTAL_DIR_MODE', (int) octdec( $string_dir_mode ) );
	if ( !defined( 'CMS_INSTALL_PROCESS' ) )
	{
		// get CAPTCHA and ASP settings
		$setting = array();
		$sql = 'SELECT * FROM `' . TABLE_PREFIX . 'mod_captcha_control` LIMIT 1';
		$database->execute_query( $sql, true, $setting, false );
		
		if ( count($setting) == 0 )
		{
			die( "CAPTCHA-Settings not found" );
		}
		
		define( 'ENABLED_CAPTCHA', ( ( $setting[ 'enabled_captcha' ] == '1' ) ? true : false ) );		
		define( 'ENABLED_ASP', ( ( $setting[ 'enabled_asp' ] == '1' ) ? true : false ) );
		define( 'CAPTCHA_TYPE', $setting[ 'captcha_type' ] );
		define( 'ASP_SESSION_MIN_AGE', (int) $setting[ 'asp_session_min_age' ] );
		define( 'ASP_VIEW_MIN_AGE', (int) $setting[ 'asp_view_min_age' ] );
		define( 'ASP_INPUT_MIN_AGE', (int) $setting[ 'asp_input_min_age' ] );
		
		unset( $setting );	
	}
	
	/** 
	 *	set error-reporting
	 */
	if ( is_numeric( ER_LEVEL ) )
	{
		error_reporting( ER_LEVEL );
		if ( ER_LEVEL >= -1 )
			ini_set( 'display_errors', 1 );
	}

	// Start a session
	if ( !defined( 'SESSION_STARTED' ) )
	{
		// set name of session cookie
		session_name( APP_NAME . 'sessionid' );

		$cookie_settings = session_get_cookie_params();

		// transform from lifetime to expire option in setcookie
		if ( $cookie_settings[ "lifetime" ] <= 0 )
			{ $cookie_settings[ "lifetime" ] = 3 * 3600; }
		$cookie_settings[ "expires" ] = time() + (int) $cookie_settings[ "lifetime" ];
		unset( $cookie_settings[ "lifetime" ] );

		//	Initialize the session cookie with the defaults
		LEPTON_session::set_cookie( session_name(), "", $cookie_settings );

		unset($cookie_settings);

		// create the session
		session_start();
		
		// create constant so this part is not running again
		define( 'SESSION_STARTED', true );

		// save in session
		$_SESSION['LSH'] = password_hash( LEPTON_GUID, PASSWORD_DEFAULT);
	}

	//	Update the session cookie to the defaults
	if( true === isset($_COOKIE[ APP_NAME . 'sessionid' ]))
	{
		// debug echo LEPTON_tools::display( $_SESSION );
		LEPTON_session::set_cookie( session_name(), $_COOKIE[ APP_NAME . 'sessionid' ], array() );
	}

	if ( defined( 'ENABLED_ASP' ) && ENABLED_ASP && !isset( $_SESSION[ 'session_started' ] ) )
	{
		$_SESSION[ 'session_started' ] = time();
	}

	// logout if not properly initialized
	if(!defined("CMS_INSTALL_PROCESS"))
	{
		if( (!isset($_SESSION['LSH'])) || (!password_verify( LEPTON_GUID , $_SESSION['LSH'] ) ) )
		{
			$_SESSION = array();
			LEPTON_session::set_cookie( session_name(), "", array( "expires"=> time() - 1 ) );
			session_destroy();
			die(header('Location: ' . ADMIN_URL . '/login/index.php'));
		}
	}

	/**
	 *  Get users language
	 *  L* 4.4.0
	 */
	if ( isset( $_GET[ 'lang' ] ) && ( $_GET[ 'lang' ] != '') && (!is_numeric( $_GET[ 'lang' ]) ) && (strlen( $_GET[ 'lang' ] ) == 2 ) )
	{
		
		$iTempPageId = (isset($page_id) ? $page_id : (defined("PAGE_ID") ? PAGE_ID : 0 ));
		if( 0 != $iTempPageId )
		{
		    $sTempLang = $database->get_one("SELECT `language` FROM `".TABLE_PREFIX."pages` WHERE `page_id`=".$iTempPageId);
		    if(NULL != $sTempLang)
		    {
		        define( 'LANGUAGE', $sTempLang );
		    } else {
		        // more or less a theoretical case
		        define( 'LANGUAGE', DEFAULT_LANGUAGE );
		    }
		} else {
		    if(isset($_SESSION['USER_ID']))
		    {
				$sTempLang = $database->get_one("SELECT `language` FROM `".TABLE_PREFIX."users` WHERE `user_id`=".$_SESSION['USER_ID']);
		        if( NULL != $sTempLang)
		        {
		            define( 'LANGUAGE', $sTempLang );
		        } else {
		            define( 'LANGUAGE', strtoupper( $_GET[ 'lang' ] ) );
		        }
		    } else {
		        define( 'LANGUAGE', strtoupper( $_GET[ 'lang' ] ) );
		    }
		}

		$_SESSION[ 'LANGUAGE' ] = LANGUAGE;
	}
	else
	{
		if ( isset( $_SESSION[ 'LANGUAGE' ] ) && ( $_SESSION[ 'LANGUAGE' ] != '' ) )
		{
			
			$iTempPageId = (isset($page_id) ? $page_id : (defined("PAGE_ID") ? PAGE_ID : 0 ));
            if( 0 != $iTempPageId )
            {
                $sTempLang = $database->get_one("SELECT `language` FROM `".TABLE_PREFIX."pages` WHERE `page_id`=".$iTempPageId);
                if(NULL != $sTempLang)
                {
                    define( 'LANGUAGE', $sTempLang );
                } else {
                    // more or less a theoretical case
                    define( 'LANGUAGE', $_SESSION[ 'LANGUAGE' ] );
                }
            } else {
                if(isset($_SESSION['USER_ID']))
		        {
		            $sTempLang = $database->get_one("SELECT `language` FROM `".TABLE_PREFIX."users` WHERE `user_id`='".$_SESSION['USER_ID']."'");
    		        if( NULL != $sTempLang)
	    	        {
		                define( 'LANGUAGE', $sTempLang );
		            } else {
		                define( 'LANGUAGE', $_SESSION[ 'LANGUAGE' ] );
		            }
		        } else {
		            define( 'LANGUAGE', $_SESSION[ 'LANGUAGE' ] );
		        }
            }
		}
		else
		{
			define( 'LANGUAGE', DEFAULT_LANGUAGE );
		}
	}
	
	// Load Language file
	if ( !defined( 'LANGUAGE_LOADED' ) )
	{
		if ( !file_exists( LEPTON_PATH . '/languages/' . LANGUAGE . '.php' ) )
		{
			exit( 'Error loading language file ' . LANGUAGE . ', please check configuration' );
		}
		else
		{
			require_once (file_exists( LEPTON_PATH . '/languages/' . LANGUAGE . '_custom.php') )
			    ? LEPTON_PATH . '/languages/' . LANGUAGE . '_custom.php'
			    : LEPTON_PATH . '/languages/' . LANGUAGE . '.php'
			    ;
		}
	}
	
	/**
	 *	Setting the correct default timezone
	 *	to avoid "date" conflicts and warnings
	 *
	 */
	$timezone_string = ( isset( $_SESSION[ 'TIMEZONE_STRING' ] ) ? $_SESSION[ 'TIMEZONE_STRING' ] : DEFAULT_TIMEZONE_STRING );
	date_default_timezone_set( $timezone_string );
	 
	// Get users date format
	define( 'DATE_FORMAT', ( isset( $_SESSION[ 'DATE_FORMAT' ] ) ? $_SESSION[ 'DATE_FORMAT' ] : DEFAULT_DATE_FORMAT ) );
	
	// Get users time format
	define( 'TIME_FORMAT', ( isset( $_SESSION[ 'TIME_FORMAT' ] ) ? $_SESSION[ 'TIME_FORMAT' ] : DEFAULT_TIME_FORMAT ) );
	
	// Set Theme dir
	define( 'THEME_URL', LEPTON_URL . '/templates/' . DEFAULT_THEME );
	define( 'THEME_PATH', LEPTON_PATH . '/templates/' . DEFAULT_THEME );

	LEPTON_handle::include_files("/modules/lib_twig/library.php");

?>