<?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


$admin = LEPTON_admin::getInstance('Preferences');
$js_back = "javascript: history.go(-1);"; // Create a javascript back link

function save_preferences()
{
	global $MESSAGE;
	$err_msg = [];

	$database = LEPTON_database::getInstance();
	$admin = LEPTON_admin::getInstance();

	// Get entered values and validate all and remove any dangerouse chars from display_name
	$display_name     = LEPTON_core::getValue('display_name');
	$display_name     = ( is_null($display_name) ? LEPTON_core::getValue('display_name','string_clean','session') : $display_name );
	
	// check that display_name is unique in whoole system (prevents from User-faking)
	$user_id = LEPTON_core::getValue('USER_ID','integer','session');
	$result = $database->get_one('SELECT user_id FROM '.TABLE_PREFIX.'users WHERE user_id <> '.$user_id.' AND display_name = "'.$display_name.'"');
	
	if(!is_null($result))
	{ 
		$err_msg[] = $MESSAGE['USERS_USERNAME_TAKEN']; 
	}
	
	// language must be 2 upercase letters only
	$language = ( is_null(strtoupper(LEPTON_core::getValue('language'))) ? DEFAULT_LANGUAGE : strtoupper(LEPTON_core::getValue('language') ));
	
	// timezone must match a value in the table
	$timezone_string = LEPTON_core::getValue('timezone_string','string_clean','session');
	if (!in_array($timezone_string, LEPTON_date::get_timezones() )) 
	{
		DEFAULT_TIMEZONE_STRING;
	}
	
	// date_format must be a key from /interface/date_formats
	$date_format = LEPTON_core::getValue('date_format');
	$DATE_FORMATS = LEPTON_date::get_dateformats(); 
	$date_format = (array_key_exists($date_format, $DATE_FORMATS) ? $date_format : '');
	unset($DATE_FORMATS);	
	
	// time_format must be a key from /interface/time_formats	
	$time_format = LEPTON_core::getValue('time_format');
	$TIME_FORMATS = LEPTON_date::get_timeformats(); 
	$time_format = (array_key_exists($time_format, $TIME_FORMATS) ? $time_format : '');
	unset($TIME_FORMATS);	

	// email should be validatet by core
	$email = LEPTON_core::getValue('email','email','post');
	if( null === $email )
	{
		$email = '';
		$errors[]  = $MESSAGE['USERS_INVALID_EMAIL']." [1]";
	
	} 
	else 
	{
		// check that email is unique in whoole system
		$result = $database->get_one("SELECT user_id FROM ".TABLE_PREFIX."users WHERE user_id <> ".$user_id." AND email = '".$email."' ");
		if(!is_null($result))
		{
			$errors[] = $MESSAGE['USERS_EMAIL_TAKEN'];
		}
	}

	// receive password vars and calculate needed action
	$current_password =  LEPTON_core::getValue('current_password','password','post');
	$new_password_1 = LEPTON_core::getValue('new_password_1','password','post');
	$new_password_2 = LEPTON_core::getValue('new_password_2','password','post');
	if (is_null($new_password_1) && $_POST['new_password_1'] != '')
	{
		$err_msg[] = $MESSAGE['PREFERENCES_INVALID_CHARS'].' [101]';
	}

	if (strlen($new_password_1) < AUTH_MIN_PASS_LENGTH  && $_POST['new_password_1'] != '')
	{
		$err_msg[] = $MESSAGE['USERS_PASSWORD_TOO_SHORT'];
	}
	
	

	// password_1 matching password_2 ?
	if( $new_password_1 != $new_password_2 )
	{
		$err_msg[] = $MESSAGE['USERS_PASSWORD_MISMATCH'];
	}	
	
	$current_password = (is_null($current_password) ? '' : $current_password);
	$new_password_1   = (($new_password_1 == '') ? '' : $new_password_1);
	
	if($current_password == '')
	{
		$err_msg[] = $MESSAGE['PREFERENCES_CURRENT_PASSWORD_INCORRECT'];
	} 
	else 
	{
		// if new_password is empty, still let current one
		if( $new_password_1 == '' )
		{
			$new_password_1 = $current_password;
			$new_password_2 = $current_password;
		}
	}

	$new_password_1   = password_hash( $new_password_1, PASSWORD_DEFAULT);
	
	// if no validation errors, try to update the database, otherwise return errormessages
	if(empty($err_msg))
	{
		// 1. current password correct?
		$admin_user_id = LEPTON_core::getValue('USER_ID','integer','session');

		$result = $database->get_one("SELECT `password` from ".TABLE_PREFIX."users where user_id = ".$admin_user_id);
			
		if(!is_null($result))
		{
			$check = password_verify($current_password,$result);
			
			if($check != 1)
			{
				$err_msg[] = $MESSAGE['PREFERENCES_CURRENT_PASSWORD_INCORRECT']." [save: #7]";
				return ( (!empty($err_msg) ) ? implode('<br />', $err_msg) : '' );					
			}
			else
			{
				$fields = [
					'display_name'  => $display_name,
					'password' 		=> $new_password_1,	
					'email' 		=> $email,
					'language' 		=> $language,
					'timezone_string'	=> $timezone_string,				
					'date_format' 		=> $date_format,
					'time_format' 		=> $time_format
				];

				$database->build_and_execute(
					'update',
					TABLE_PREFIX.'users',
					$fields,
					'user_id = '.$admin_user_id
				);

				
				// update successfull, takeover values into the session
				$_SESSION['DISPLAY_NAME'] = $display_name;
				$_SESSION['LANGUAGE'] = $language;
				$_SESSION['EMAIL'] = $email;
				
				// Set timezone
				$_SESSION['TIMEZONE_STRING'] = $timezone_string;
				date_default_timezone_set($timezone_string);
				
				// Update date format
				if($date_format != '')
				{
					$_SESSION['DATE_FORMAT'] = $date_format;
					if(isset($_SESSION['USE_DEFAULT_DATE_FORMAT'])) { unset($_SESSION['USE_DEFAULT_DATE_FORMAT']); }
				} 
				else
				{
					$_SESSION['USE_DEFAULT_DATE_FORMAT'] = true;
					if(isset($_SESSION['DATE_FORMAT'])) { unset($_SESSION['DATE_FORMAT']); }
				}
				
				// Update time format
				if($time_format != '')
				{
					$_SESSION['TIME_FORMAT'] = $time_format;
					if(isset($_SESSION['USE_DEFAULT_TIME_FORMAT'])) { unset($_SESSION['USE_DEFAULT_TIME_FORMAT']); }
				} 
				else
				{
					$_SESSION['USE_DEFAULT_TIME_FORMAT'] = true;
					if(isset($_SESSION['TIME_FORMAT'])) { unset($_SESSION['TIME_FORMAT']); }
				}
			}
		}
	}
	return ( (!empty($err_msg) ) ? implode('<br />', $err_msg) : '' );
}

$retval = save_preferences();
if( $retval == '')
{
    if(class_exists("initial_page", true))
    {
	    initial_page::getInstance()->update_user( (int)$_SESSION['USER_ID'], $_POST['init_page_select'] );
    }

	$admin->print_success($MESSAGE['PREFERENCES_DETAILS_SAVED']);
} 
else
{
	$admin->print_error($retval, $js_back);
}
