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

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


$oLEPTON = new LEPTON_core();
if ($oLEPTON->is_authenticated()==false) die( header('Location: '.LEPTON_URL.'/account/login.php') );

$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 = array();
			$database->execute_query(
				"SELECT `password` from `".TABLE_PREFIX."users` where `user_id`='".$user_id."' ",
				true,
				$results_array,
				false
			);			
			
			if( count($results_array) > 0) {
				$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 = array();
	
	// timezone must match a value in the table
	$timezone_string = $oLEPTON->get_timezone_string();
	if (in_array($_POST['timezone_string'], LEPTON_basics::get_timezones() )) {
		$timezone_string = $_POST['timezone_string'];
	}
	
	// language must be 2 upercase letters only
	$language         = strtoupper($oLEPTON->get_post('language'));
	$language         = (preg_match('/^[A-Z]{2}$/', $language) ? $language : DEFAULT_LANGUAGE);

	// email should be validatet by core
	$email = ( $oLEPTON->get_post('email') == null ? '' : $oLEPTON->get_post('email') );
	if( false == LEPTON_handle::checkEmailChars( $email ) )
	{
		$email = '';
		$errors[]  = $MESSAGE['USERS_INVALID_EMAIL']." [1]";
	
	} else {
	    if ( false === LEPTON_handle::checkEmailChars( $email ) )
	    {
            $email = '';
            $errors[]  = $MESSAGE['USERS_INVALID_EMAIL']." [2]";
	    
	    } else {
        	// check that email is unique in whoole system
            $email = addslashes($email);
            $sql  = 'SELECT COUNT(*) FROM `'.TABLE_PREFIX.'users` ';
            $sql .= 'WHERE `user_id` <> '.(int)$oLEPTON->get_user_id().' AND `email` LIKE "'.$email.'"';
            if( $database->get_one($sql) > 0 )
            {
                $errors[] = $MESSAGE['USERS_EMAIL_TAKEN'];
            }
	    }
	}
	
	$display_name = addslashes( $oLEPTON->get_post('display_name') );

	if ( strlen($display_name) < AUTH_MIN_LOGIN_LENGTH ) {
		$errors[] = $MESSAGE['USERS_USERNAME_TOO_SHORT'];
	}
	
    // new in L* 4.2.0
    if( false === LEPTON_handle::checkUsernameChars( $display_name ) )
	{
	    $errors[] = $MESSAGE['USERS_NAME_INVALID_CHARS'];
	}
	
	// date_format must be a key from /interface/date_formats
	$date_format      = $oLEPTON->get_post('date_format');
	// $date_format_key  = str_replace(' ', '|', $date_format);
	$user_time = true;
	$DATE_FORMATS = LEPTON_basics::get_dateformats(); 
	$date_format = (array_key_exists($date_format, $DATE_FORMATS) ? $date_format : '');
	// $date_format = ($date_format == 'system_default' ? '' : $date_format);
	unset($DATE_FORMATS);
	
	// time_format must be a key from /interface/time_formats	
	$time_format      = $oLEPTON->get_post('time_format');
	// $time_format_key  = str_replace(' ', '|', $time_format);
	$user_time = true;
	$TIME_FORMATS = LEPTON_basics::get_timeformats(); 
	$time_format = (array_key_exists($time_format, $TIME_FORMATS) ? $time_format : '');
	// $time_format = ($time_format == 'system_default' ? '' : $time_format);
	unset($TIME_FORMATS);
	
	$fields = array(
		'display_name'	=> $display_name,		# not empty - min AUTH_MIN_LOGIN_LENGTH chars
		'language'		=> $language,
		'email'			=> $email,				# not empty and valid
		'timezone_string'	=> $timezone_string,
		'time_format'	=> $time_format,
		'date_format'	=> $date_format
	);
		
	if (isset($_POST['new_password']) && (isset($_POST['new_password2'])) && ($_POST['new_password'] === $_POST['new_password2'])) {
		if ($_POST['new_password'] != "") $fields['password'] = password_hash($_POST['new_password'], PASSWORD_DEFAULT);
	} else {
		if (($_POST['new_password'] != $_POST['new_password2'])) {
			$errors[] = $MESSAGE['PREFERENCES_PASSWORD_MATCH'];
		}
	}
	
	if (count($errors) == 0) {
		/*
		$q = "UPDATE `".TABLE_PREFIX."users` SET ";
		foreach($fields as $key=>$value) $q .= "`".$key."`='".$value."', ";
		$q = substr($q, 0, -2) . " WHERE `user_id`='".$_SESSION['USER_ID']."'";
		$oStatement = $database->db_handle->prepare( $q );
		$oStatement->execute();
		*/
		
		$database->build_and_execute(
		    "update",
		    TABLE_PREFIX."users",
		    $fields,
		    "user_id=".$_SESSION['USER_ID']
		);
		if ($database->is_error()) {
			$errors[] = $database->get_error();
		} else {
			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']);
			}
		}
	}
	if (count($errors) > 0) {
		$_SESSION['result_message'] = implode("<br />", $errors );
	} else {
		$_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');

?>