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

// Make sure the login is enabled
if(!FRONTEND_LOGIN)
{
header('Location: '.LEPTON_URL.'/index.php');
exit(0);
} 


$oLEPTON = LEPTON_frontend::getInstance();
if ($oLEPTON->is_authenticated()=== false) 
{
	header('Location: '.LEPTON_URL.'/account/login.php');
	die();
}

$submit_ok = false;
if (isset($_POST['save']) && ($_POST['save']=='account_settings')) 
{
	if (isset ($_SESSION['wb_apf_hash']) && ($_SESSION['wb_apf_hash'] === $_POST['hash']) ) 
	{
		if ( ( TIME() - $_POST['r_time'] ) <= (60*5) ) 
		{
			// user-password correct?
			$user_id = $_SESSION['USER_ID'];
			
			$results_array = [];
			$database->execute_query(
				"SELECT `password` from `".TABLE_PREFIX."users` where `user_id` = ".$user_id,
				true,
				$results_array,
				false
			);			
			
			if (!empty ($results_array)) 
			{
				$check = password_verify($_POST['current_password'],$results_array['password']);
				if($check == 1) 
				{
					$submit_ok = true;
				} 
			}				
		
			unset($user_id);
			unset($query);
			unset($result);
			unset($_POST['save']);
		}
	}
}

if (true === $submit_ok) 
{
	unset($_SESSION['wb_apf_hash']);
	unset($_POST['hash']);
	
	$errors = [];
	
	// 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;
	}
	
	// language must be 2 upercase letters only
	$language = (is_null(strtoupper(LEPTON_core::getValue('language'))) ? DEFAULT_LANGUAGE : strtoupper(LEPTON_core::getValue('language') ));

	// 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
		$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 email LIKE '".$email."' ");
		if(!is_null($result))
		{
			$errors[] = $MESSAGE['USERS_EMAIL_TAKEN'];
		}
	}
	
	$display_name = LEPTON_core::getValue('display_name','username','post');
	
    if(is_null($display_name))
	{
	    $errors[] = $MESSAGE['USERS_NAME_INVALID_CHARS'];
	}	

	if ( strlen($display_name) < AUTH_MIN_LOGIN_LENGTH ) 
	{
		$errors[] = $MESSAGE['USERS_USERNAME_TOO_SHORT'];
	}
	
	// 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);
	
	$fields = array(
		'display_name'	=> $display_name,
		'language'		=> $language,
		'email'			=> $email,
		'timezone_string'	=> $timezone_string,
		'time_format'	=> $time_format,
		'date_format'	=> $date_format
	);
		
	$pw = LEPTON_core::getValue('new_password','password','post');
	$pw2 = LEPTON_core::getValue('new_password2','password','post');
	
	if (isset($pw) && isset($pw2) && $pw === $pw2 )
	{
		if ($pw != "")
		{
			$fields['password'] = password_hash($pw, PASSWORD_DEFAULT);
		}
	} 
	else 
	{
		if ($pw != $pw2)
		{
			$errors[] = $MESSAGE['PREFERENCES_PASSWORD_MATCH'];
		}
	}
	
	if (empty($errors)) 
	{		
		$database->build_and_execute(
		    "update",
		    TABLE_PREFIX."users",
		    $fields,
		    "user_id=".$_SESSION['USER_ID']
		);

		if (isset($fields['password']))
		{
			unset($fields['password']);
		}			
		foreach($fields as $k=>$v) 
		{
			$_SESSION[ strtoupper($k) ] = $v;
		}
	
		// Update timezone
		$_SESSION['TIMEZONE_STRING'] = $timezone_string;
		date_default_timezone_set($timezone_string);
	
		// Update time format
		if ( $_SESSION['TIME_FORMAT'] != '' ) 
		{
			if(isset($_SESSION['USE_DEFAULT_TIME_FORMAT']))
			{
				unset($_SESSION['USE_DEFAULT_TIME_FORMAT']);	
			}
		} 
		else 
		{
			$_SESSION['USE_DEFAULT_TIME_FORMAT'] = true;
			unset($_SESSION['TIME_FORMAT']);
		}
	
		// Update date format
		if ( $_SESSION['DATE_FORMAT'] != '' ) 
		{
			if(isset($_SESSION['USE_DEFAULT_DATE_FORMAT']))
			{
				unset($_SESSION['USE_DEFAULT_DATE_FORMAT']);	
			}
		} 
		else 
		{
			$_SESSION['USE_DEFAULT_DATE_FORMAT'] = true;
			unset($_SESSION['DATE_FORMAT']);
		}
	}

	$_SESSION['result_message'] = $MESSAGE['PREFERENCES_DETAILS_SAVED']."!<br /><br />";
} 
else 
{
	$_SESSION['result_message'] = "";
}

unset($submit_ok);

// Required page details
$page_id = 0;
$page_description = '';
$page_keywords = '';
define('PAGE_ID', 0);
define('ROOT_PARENT', 0);
define('PARENT', 0);
define('LEVEL', 0);
define('PAGE_TITLE', $MENU['PREFERENCES']);
define('MENU_TITLE', $MENU['PREFERENCES']);
define('MODULE', '');
define('VISIBILITY', 'public');

// Set the page content include file
define('PAGE_CONTENT', LEPTON_PATH.'/account/preferences_form.php');

// Include the index (wrapper) file
require(LEPTON_PATH.'/index.php');
