<?php
###############################################################################
# ConfigRoot.php
#
#
# @author Anil Kumar <akumar@codepunch.com>
# @link   https://codepunch.com
#
############################################################################### 

namespace 	CodePunch\Config;
use 		Exception;
use			CodePunch\Base\Text as TEXT;

###############################################################################

class ConfigRoot {
	
	const DEFAULT_SESSION_TIMEOUT 		= 10;
	const DEFAULT_MAX_LOGIN_COUNT 		= 6;
	const DEFAULT_LOGIN_LOCKOUT_MINUTES = 10;
	const DEFAULT_HOME_PAGE				= "domains";
	
	###########################################################################
	// Authentication Status
	
	const ERROR			= -3;
	const UNKNOWN 		= -2;
	const INVALID 		= -1;
	const VALID 		= 0;
	const TIMEDOUT 		= 1;
	const LIMITED		= -3;
	
	###########################################################################
	
	const SETUPADMIN_USERID	= 0;
	const CLI_ACCESS_USERID	= -1;
	const INVALID_USERID	= -2;
	
	###########################################################################
	// Session Constants, keep these unique to allow different versions of
	// SED to run from same server and accessed simultaneously from same  
	// browser without conflicts.
	
	const LOGGEDIN 		= 'sed5state';
	const TIMEOUT		= 'sed5time';
	const REMOTEIP		= 'sed5addr';
	const USERNAME		= 'sed5name';
	const USERINFO		= 'sed5info';
	const COLORSCHEME	= 'sed5colr';
	const VALIDITY		= 'sed5user';
	const TIMEOUTAUDIT	= 'sed5taudit';
	const SAMLUSER		= 'sed5samlu';
	const SAMLIDP		= 'sed5idp';
	
	// Used to specify the return page after login.
	
	const DESTINATION 	= 'return';
	
	// ionCube
	
	const IONCUBE_NOT_REQUIRED = 0;
	const IONCUBE_REQUIRED_AVAILABLE = 1;
	const IONCUBE_REQUIRED_NOT_AVAILABLE = -1;
	const IONCUBE_REQUIRED_WRONG_VERSION = -2;
	const IONCUBE_REQUIRED_UNSUPPORTED_PHP = -3;
	
	###########################################################################

	public static function check_ioncube_status()
	{
		$filename = \CodePunch\Base\Util::get_install_folder_path() . "lib/php/CodePunch/Config/ConfigBase.0.0.php";
		if(is_file($filename))
			return self::IONCUBE_NOT_REQUIRED;
		
		$filename = \CodePunch\Base\Util::get_install_folder_path() . "lib/php/CodePunch/Config/ConfigBase.php";
		if(is_file($filename)) {
			$handle = fopen($filename, 'r');
			fseek($handle, 0);
			$content = fread($handle, 1024);
			if(stristr($content, "if(!extension_loaded('ionCube Loader'))") !== false) {
				$icversion = \CodePunch\Base\Util::ioncube_loader_version_array();
				if(version_compare(PHP_VERSION, '8.0.0') >= 0 && version_compare(PHP_VERSION, '8.1.0') < 0)
					return self::IONCUBE_REQUIRED_UNSUPPORTED_PHP;
				else if(version_compare(PHP_VERSION, '8.4.0') >= 0)
					return self::IONCUBE_REQUIRED_UNSUPPORTED_PHP;
				else if($icversion['version'] == 0) 
					return self::IONCUBE_REQUIRED_NOT_AVAILABLE;
				else if($icversion['version'] < 10) 
					return self::IONCUBE_REQUIRED_WRONG_VERSION;
				else if($icversion['version'] < 12 && version_compare(PHP_VERSION, '8.1.0') >= 0)
					return self::IONCUBE_REQUIRED_WRONG_VERSION;
				else
					return self::IONCUBE_REQUIRED_AVAILABLE;
			}
			else if(stristr($content, "class ConfigBase extends ConfigRoot") !== false)
				return self::IONCUBE_NOT_REQUIRED;
		}
		return self::IONCUBE_NOT_REQUIRED;
	}
	
	###########################################################################
	
	public static function get_config_path($defaultcfg="")
	{
		$rootFolder = \CodePunch\Base\Util::get_install_folder_path();
		if($defaultcfg == null || $defaultcfg == "") {
			$defaultcfg = "config.php";
			$drivertype = \CodePunch\Base\Util::get_sanitized_request_string("db", "mysql");
			if($drivertype != "")
				$defaultcfg = "config." . $drivertype . ".php";
			$configPath = $rootFolder . $defaultcfg;
			if(!is_file($configPath))
				$defaultcfg = "config.php";
		}
		return $rootFolder . $defaultcfg;
	}
	
	###########################################################################
	
	public static function load_global_config_data($defaultcfg="")
	{
		$configPath = self::get_config_path($defaultcfg);
		if(is_file($configPath)) {
			include($configPath);
			if(isset($cfg_base_install_path)) {
				if(is_dir($cfg_base_install_path))
					$GLOBALS['cfg_base_install_path'] = $cfg_base_install_path;
			}
			if(isset($cfg_log_folder_path)) {
				if(is_dir($cfg_log_folder_path))
					$GLOBALS['cfg_log_folder_path'] = $cfg_log_folder_path;
			}
			if(isset($cfg_http_protocol)) {
				$cfg_http_protocol = strtolower($cfg_http_protocol);
				if($cfg_http_protocol == "detect" || $cfg_http_protocol == "http" || $cfg_http_protocol == "https")
					$GLOBALS['cfg_http_protocol'] = $cfg_http_protocol;
			}
		}
	}
	
	###########################################################################
	
	public static function loadcfg($defaultcfg="") 
	{
		$configPath = self::get_config_path($defaultcfg);
		if(!is_file($configPath)) {
			$rootFolder = \CodePunch\Base\Util::get_install_folder_path();
			$configPath = $rootFolder . "config-sample.php";
			if(is_file($configPath))
				throw new Exception(TEXT::get("config_file_not_setup"));
			else
				throw new Exception(TEXT::get("config_file_missing"));
		}

		include($configPath);
		
		if(isset($db_extended_config_name) && isset($db_extended_config) && $db_extended_config_name != "" && isset($db_extended_config[$db_extended_config_name]) && \CodePunch\Base\Util::iskeys_set($db_extended_config[$db_extended_config_name], array('dbname','dbuser','dbpass','dbhost','dbdriver'))) {
			$db_config_database	= $db_extended_config[$db_extended_config_name]['dbname'];
			$db_config_username = $db_extended_config[$db_extended_config_name]['dbuser'];
			$db_config_password = $db_extended_config[$db_extended_config_name]['dbpass'];
			$db_config_host		= $db_extended_config[$db_extended_config_name]['dbhost'];
			$db_config_driver	= $db_extended_config[$db_extended_config_name]['dbdriver'];
		}
		if(isset($db_extended_config_name) && isset($db_extended_config) && $db_extended_config_name != "" && isset($db_extended_config[$db_extended_config_name]) && isset($db_extended_config[$db_extended_config_name]['port'])) {
			if($db_extended_config[$db_extended_config_name]['port'] != "")
				$db_config_port	= $db_extended_config[$db_extended_config_name]['port'];
		}

		// Check if default variables are defined.
		if(!isset($db_config_database) || !isset($db_config_username) || 
			!isset($db_config_password) || !isset($db_config_host) || 
			!isset($db_config_driver) || !isset($db_config_table_prefix) || 
			!isset($db_config_publickey))
			throw new Exception(TEXT::get("db_invalidconfig"));
			
		$driverlist = array('pdo_mysql', 'mysqli', 'pdo_sqlite', 'pdo_pgsql', 'pdo_oci', 'oci8', 'pdo_sqlsrv', 'sqlsrv');
		if(!in_array($db_config_driver, $driverlist))
			throw new Exception(TEXT::get("db_invaliddriver"));

		$dbconfig = array(
			'dbname' => $db_config_database,
			'user' => $db_config_username,
			'password' => $db_config_password,
			'host' => $db_config_host,
			'driver' => $db_config_driver,
			'prefix' => $db_config_table_prefix,
			'key' => $db_config_publickey,
			'setupuser' => isset($db_config_setup_name) ? $db_config_setup_name : "",
			'setuppass' => isset($db_config_setup_password) ? $db_config_setup_password : "",
			'serverid' => isset($this_server_id) ? $this_server_id : ""
		);
		if(isset($db_config_port))
			$dbconfig['port'] = $db_config_port;
		return $dbconfig;
	}
	
	###########################################################################
	
	public static function loadExtendedConfig()
	{
	}
}

###############################################################################
