<?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-2026 LEPTON Project
 * @link            https://lepton-cms.org
 * @license         https://gnu.org/licenses/gpl.html
 * @license_terms   please see LICENSE and COPYING files in your package
 *
 */ 

// include secure.php to protect this file and the whole CMS!
if(!defined("SEC_FILE")){define("SEC_FILE",'/framework/secure.php' );}
if (defined('LEPTON_PATH')) {	
	include LEPTON_PATH.SEC_FILE;
} else {
	$oneback = "../";
	$root = $oneback;
	$level = 1;
	while (($level < 10) && (!file_exists($root.SEC_FILE))) {
		$root .= $oneback;
		$level += 1;
	}
	if (file_exists($root.SEC_FILE)) { 
		include $root.SEC_FILE;   
	} else {
		trigger_error(sprintf("[ <b>%s</b> ] Can't include secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
	}
}
// end include secure file


global $MESSAGE, $TEXT;

// Getting the admin-instance and print the "admin header"
$admin = LEPTON_admin::getInstance('Settings', 'settings');
$database = LEPTON_database::getInstance();

// Create a back link
$js_back = ADMIN_URL.'/settings/index.php';

$messages = [];
$settings = [];
$old_settings = [];

// Query current settings in the db, then loop through them to get old values
$aCurrentValues = [];
$database->execute_query(
	"SELECT `name`, `value` FROM `".TABLE_PREFIX."settings` WHERE `name` <> 'lepton_version' ORDER BY `name`",
	true,
	$aCurrentValues,
	true
);

$allow_tags_in_fields = ['website_header', 'website_footer'];

// get old settings from DB and current settings from $POST
foreach ($aCurrentValues as &$ref)
{
	if (isset($_POST[$ref['name']]))
	{
		$old_settings[$ref['name']] = $ref['value'];
		
		if (!in_array($ref['value'], $allow_tags_in_fields))
		{
			$settings[$ref['name']] = LEPTON_core::getValue($ref['name']);
		}
		else
		{
			$settings[$ref['name']] = LEPTON_core::getValue($ref['name'],'string_chars','post');
		}
	}
}

$allow_empty_values = [
	'backend_title',
	'pages_directory',
	'sec_anchor',
	'website_description',
	'website_footer',
	'website_header',
	'website_keywords'
];

// language must be 2 upercase letters only
LEPTON_handle::register('file_list','save_filename');
$languages = file_list(LEPTON_PATH.'/languages', ['index.php'], false, 'php', LEPTON_PATH.'/languages/');

if (!in_array($settings['default_language'].'.php', $languages))
{
	$settings['default_language'] = DEFAULT_LANGUAGE;
}

// needed for the time/date/timezones here
$user_time = false;

// timezone must match a value in the table
if (!in_array($settings['default_timezone_string'], LEPTON_date::get_timezones() ))
{
	$settings['default_timezone_string'] = DEFAULT_TIMEZONE_STRING;
}

// date_format must be a key from /interface/date_formats
if (!array_key_exists($settings['default_date_format'], LEPTON_date::get_dateformats() ))
{
	 $settings['default_date_format'] = $old_settings['default_date_format'];
}

// time_format must be a key from /interface/time_formats
if (!array_key_exists($settings['default_time_format'], LEPTON_date::get_timeformats() ))
{
	$settings['default_time_format'] = $old_settings['default_time_format'];
}

// A valid error-level?
if ($settings['er_level'] == '')
{
	// use the system settings from php-ini
	$settings['er_level'] = ini_get("error_reporting");
}
else
{ 
	if (array_key_exists($settings['er_level'], LEPTON_basics::get_errorlevels() ))
	{
		$settings['er_level'] =  intval($settings['er_level']);
	}
	else
	{
		unset($settings['er_level']);
	}
}

// A valid frontend-signup group?
$gid = (int)$settings['frontend_signup'];
if ($gid == 0)
{
	$settings['frontend_signup'] = 0;  // no frontend_signup allowed
} 
else 
{
	$result = [];
	$database->execute_query(
		"SELECT * FROM `".TABLE_PREFIX."groups` WHERE `group_id` = ".$gid." ",
		true,
		$result,
		false
	);
	
	if (!empty ($result))
	{
		$settings['frontend_signup'] = $gid;
	} 
	else 
	{
		unset($settings['frontend_signup']);
	}
}

//  Is the page-level-limit between 0 and 10?
$page_level_limit = intval($settings['page_level_limit']);
$settings['page_level_limit'] = (($page_level_limit <= 10) && ($page_level_limit > -1)) ? $page_level_limit : 4;

//  Is the redirect-timer in range -1 ... 10000 ?
$redirect_timer = intval($settings['redirect_timer']);
$settings['redirect_timer'] = (($redirect_timer >= -1) && ($redirect_timer <= 10000)) ? $redirect_timer : 500;

// validate Leptoken lifetime
$settings['leptoken_lifetime'] = intval($settings['leptoken_lifetime']);
if ($settings['leptoken_lifetime'] < 0)
{
    unset($settings['leptoken_lifetime']);
}

// validate maximum logon attempts
$settings['max_attempts'] = intval($settings['max_attempts']);
if ($settings['max_attempts'] < 0)
{
    unset($settings['max_attempts']);
}

// check theme
// $settings['default_theme'] = isset ($settings['default_theme']) ? ($settings['default_theme']) : $old_settings['default_theme'];	
// $settings['default_template'] = isset ($settings['default_template']) ? ($settings['default_template']) : $old_settings['default_template'];
// $settings['sec_anchor'] = isset ($settings['sec_anchor']) ? $settings['sec_anchor'] : $old_settings['sec_anchor'];

// check TFA	
if ($settings['tfa'] != $old_settings['tfa'])
{
	$users = [];
	$database->execute_query(
		"SELECT user_id FROM `".TABLE_PREFIX."users` ",
		true,
		$users,
		true
	);

	foreach ($users as $user)
	{			
		$database->simple_query( "UPDATE `".TABLE_PREFIX."users` SET `pin` = '-1' WHERE user_id = ".$user['user_id']);
		$database->simple_query( "UPDATE `".TABLE_PREFIX."users` SET `pin_set` = 0 WHERE user_id = ".$user['user_id']);
	}
}

// Pages_directory could be empty, see line around 80(?) $allow_empty_values
if (isset($settings['pages_directory']))
{	
	if ($settings['pages_directory'] == '/' || $settings['pages_directory'] == '')
	{
		$settings['pages_directory'] = save_filename($settings['pages_directory']);
	}
	else
	{
		$settings['pages_directory'] = '/'.save_filename($settings['pages_directory']);
	}
}

// [3]	Has the name of the directory changed?
if ($old_settings['pages_directory'] != $settings['pages_directory'])
{
	if ($settings['pages_directory'] == "")
	{
		//	[3.1] directory will NOT be deleted automatically!	
		$message = 'Directory has been deleted in the settings, but you have to care about the access files manually!';
		echo(LEPTON_tools::display($message, 'pre','ui orange message'));
	
	} 
	elseif (($old_settings['pages_directory'] == "") && ($settings['pages_directory'] != "")) 
	{
		//	[3.2] Old directory name WAS empty (root!) and the new one ist created automtically!
		LEPTON_core::make_dir(LEPTON_PATH.'/'.$settings['pages_directory']);
		copy(LEPTON_PATH.'/backend/pages/master_index.php',LEPTON_PATH.'/'.$settings['pages_directory'].'/index.php');
		
		$message = 'Directory has been created in the settings, but you have to care about the access files manually!!!';
		echo(LEPTON_tools::display($message, 'pre','ui orange message'));
	} 
	else 
	{
		//	[3.3] Simple rename the current directory
		rename(LEPTON_PATH.$old_settings['pages_directory'], LEPTON_PATH.$settings['pages_directory']);
	}
}

// Media_directory could NOT be empty, see line 120 $allow_empty_values
if (isset($settings['media_directory']))
{	
	if( $settings['media_directory'] == '/' || $settings['media_directory'] == '')
	{
		$settings['media_directory'] = $old_settings['media_directory'];
	}
	else
	{
		$settings['media_directory'] = '/'.save_filename($settings['media_directory']);
	}
}		

// Has the name of the directory changed?
if ($old_settings['media_directory'] != $settings['media_directory']) 
{
	rename( LEPTON_PATH.$old_settings['media_directory'], LEPTON_PATH.$settings['media_directory'] );
}


if (!empty($settings['sec_anchor']))
{
	// must begin with a letter
	$pattern = '/^[a-z][a-z_0-9]*$/i';
	if (!preg_match($pattern, $settings['sec_anchor'], $array))
	{
		$messages[] = $TEXT['SEC_ANCHOR'].' '.$TEXT['INVALID_SIGNS'];
	}
}

// Work-out file mode, check if should be set to 777 or left alone
if (isset ($_POST['world_writeable']) && $_POST['world_writeable'] == 'true')
{
	$settings['string_file_mode'] = '0666';
	$settings['string_dir_mode'] = '0777';
}
else
{
	$settings['string_file_mode'] = '0644';
	$settings['string_dir_mode'] = '0755';
}

// @CHECK 20240309-> mfi:  check home folder settings, remove home folders for all users if the option is changed to "false"
if (($settings['home_folders'] == 'false') && ($old_settings['home_folders'] == 'true')) 
{
	$database->simple_query( "UPDATE `".TABLE_PREFIX."users` SET `home_folder` = '' ");	
}

// check webmailer settings, email should be validatet by core, work-out which mailer routine should be checked
if (!isset($settings['server_email']))
{
	$messages[] = $TEXT['MAILER_DEFAULT_SENDER_MAIL']." [1]";
} 
else 
{
	if (LEPTON_handle::checkEmailChars($settings['server_email']) === false)
	{
		$messages[] = $TEXT['MAILER_DEFAULT_SENDER_MAIL']." [2]";
	}
}


if ($settings['mailer_default_sendername'] == '')
{
	$messages[] = $MESSAGE['MOD_FORM_REQUIRED_FIELDS'].': '.$TEXT['MAILER_DEFAULT_SENDER_NAME'];
}

$bCheckModul = extension_loaded('openssl');

if ($settings['mailer_routine'] == 'smtp')
{
	// if mailer_routine = smtp -> authentication is mandantory! 20240309 erpe
	$settings['mailer_smtp_auth']  = true;
	
	if ($settings['mailer_smtp_host'] == '')
	{
		$messages[] = $MESSAGE['MOD_FORM_REQUIRED_FIELDS'].': '.$TEXT['MAILER_SMTP_HOST'];
	}
	
	if ($settings['mailer_smtp_username'] == '')
	{
		$messages[] = $TEXT['MAILER_SMTP'] . ': ' . $MESSAGE['LOGIN_USERNAME_BLANK'];
	}		
		
	if ($settings['mailer_smtp_password'] == '')
	{
		$messages[] = $TEXT['MAILER_SMTP'] . ': ' . $MESSAGE['LOGIN_PASSWORD_BLANK'];
	}
	
	if($bCheckModul === true)
	{
		$settings['mailer_smtp_host'] = LEPTON_database::cryptString($settings['mailer_smtp_host']);
		$settings['mailer_smtp_username'] = LEPTON_database::cryptString($settings['mailer_smtp_username']);
		$settings['mailer_smtp_password'] = LEPTON_database::cryptString($settings['mailer_smtp_password']);
	}
} 
else 
{
	if ($bCheckModul === true)
	{
		if (!empty($settings['mailer_smtp_host']))
		{
			$settings['mailer_smtp_host'] = LEPTON_database::cryptString($settings['mailer_smtp_host']);
		}
		
		if (!empty($settings['mailer_smtp_username']))
		{
			$settings['mailer_smtp_username'] = LEPTON_database::cryptString($settings['mailer_smtp_username']);
		}
		
		if (!empty($settings['mailer_smtp_password']))
		{
			$settings['mailer_smtp_password'] = LEPTON_database::cryptString($settings['mailer_smtp_password']);
		}
	}
}

// if no validation errors, try to update the database, otherwise return errormessages
if (empty($messages))
{
	// Query current settings from the db, then loop through them and update the db with the new value
	$update_fields = [];
	$current_settings_names = [];
	
	$database->execute_query(
		"SELECT `name` FROM `".TABLE_PREFIX."settings` WHERE `name` <> 'lepton_version' ORDER BY `name`",
		true,
		$current_settings_names,
		true
	);
	
	foreach ($current_settings_names as &$ref)
	{
		$setting_name = $ref['name'];
		
		if (!isset($settings[$setting_name]))
		{
			continue;
		}
		
		$value = $settings[$setting_name];
		
		if (!in_array($setting_name, $allow_tags_in_fields))
		{
			$value = strip_tags($value ?? "");
		}

		LEPTON_handle::restoreSpecialChars($value);
		
		$update_fields[] = [
			"value" => $value,
			"name"  => $setting_name
		];
	}
	
	$database->simple_query(
		"UPDATE `".TABLE_PREFIX."settings` SET `value`= :value WHERE `name`= :name",
		$update_fields
	);
	
	// Query current search settings in the db, then loop through them and update the db with the new value
	$search_update_values = [];
	$all_search_settings = [];
	$database->execute_query(
		"SELECT `name`, `value` FROM `".TABLE_PREFIX."search` WHERE `extra` = '' ",
		true,
		$all_search_settings,
		true
	);
			
	foreach ($all_search_settings as &$row) 
	{
		$old_value = $row['value'];
		$post_name = 'search_'.$row['name'];
		$value = LEPTON_core::getValue($post_name);
		
		// hold old value if post is empty
		if (isset ($value))
		{
			if ($post_name == 'search_template')
			{				
				// check for existing template
				$fe_template = $database->get_one("SELECT `directory` FROM ".TABLE_PREFIX."addons WHERE `directory` = '".$value."' ");
				
				if(!is_null($fe_template))
				{
					$value = $fe_template;
				}
				else
				{												
					$value = $settings['default_template'];
				}
			}
						
			$search_update_values[] = ["name" => $row['name'], "value" => $value];
		}
	}

	$database->simple_query(
		"UPDATE `".TABLE_PREFIX."search` SET `value`= :value WHERE `name`= :name AND `extra` = '' ",
		 $search_update_values
	);
}
    
if (!empty($messages))
{
	$messages = "<p><strong>" . implode("<br />", $messages) . "</strong><p><p>&nbsp;</p>";
} 
else 
{
	$messages = "";
}

$admin->print_success($messages . $MESSAGE['SETTINGS_SAVED'], $js_back);

