<?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
 * @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
 *
 */

$debug = true;

if (true === $debug) {
	ini_set('display_errors', 1);
	error_reporting(E_ALL);
}

// Start a session
if(!defined('SESSION_STARTED')) {
	session_name('lepton_session_id');
	session_start();
	define('SESSION_STARTED', true);
}
// Get random-part for session_name()
list($usec,$sec) = explode(' ',microtime());
srand(intval((float)$sec+((float)$usec*100000)));
$session_rand = rand(1000,9999);

// Load and register the LEPTON autoloader
require_once "../framework/functions/function.lepton_autoloader.php";
spl_autoload_register( "lepton_autoloader", true);

// check if guid is from index.php
if ((isset($_POST['guid'])) && ($_POST['guid'] == "E610A7F2-5E4A-4571-9391-C947152FDFB0"))
{
    define("LEPTON_INSTALL_PROCESS", true);
}

// define some constants
const LEPTON_VERSION = '7.5.0';

/**
 * Function to set up an error-message and leave the installation-process.
 *
 * @param string $message Any error-message.
 * @param string $field_name Any field-name. Could be an empty string.
 *
 */
function set_error(string $message = "", string $field_name = ""): void
{
    if (!empty($message))
    {
        /**
         *    Copy values entered into session so user doesn't have to re-enter everything
         *
         */
        if (isset($_POST['website_title']))
        {
            $keys = [
                'lepton_url',
                'default_timezone_string',
                'default_language',
                'database_host',
                'database_username',
                'database_password',
                'database_name',
                'website_title',
                'admin_username',
                'admin_email',
                'admin_password',
                'admin_repassword',
                'table_prefix'
            ];

	  	copy_post_to_session( $keys );

	  	$_SESSION['operating_system'] = (!isset($_POST['operating_system']))
	  	  ? 'linux'
	  	  : $_POST['operating_system'] ;

            $_SESSION["world_writeable"] = isset($_POST['world_writeable']);

            $_SESSION['install_tables'] = isset($_POST['install_tables']);

	  }

	  // Set the message
	  $_SESSION['message'] = $message;

	  // Set the element(s) to highlight
        if ($field_name != '') $_SESSION['ERROR_FIELD'] = $field_name;

	  // Specify that session support is enabled
        $_SESSION['session_support'] = '<span class="good">Enabled</span>';

	  // Redirect to first page again and exit
        header('Location: index.php?sessions_checked=true');
	  exit();
	}
}

/**
 *    Function to copy some fields from the $_POST array to the $_SESSION array.
 *
 * @param array $names An array within the keys. Call by reference.
 *
 */
function copy_post_to_session(array &$names): void
{
    foreach ($names as $key)
    {
        $_SESSION[$key] = (isset($_POST[$key])) ? $_POST[$key] : '';
    }
}


// Function to workout what the default permissions are for files created by the webserver
function default_file_mode(string $temp_dir): string
{
    if (is_writable($temp_dir))
	{
	  $filename = $temp_dir.'/test_permissions.txt';
	  $handle = fopen($filename, 'w');
	  fwrite($handle, 'This file is to get the default file permissions');
	  fclose($handle);
	  $default_file_mode = '0'.substr(sprintf('%o', fileperms($filename)), -3);
	  unlink($filename);
	} else {
	  $default_file_mode = '0777';
	}
	return $default_file_mode;
}

// Function to workout what the default permissions are for directories created by the webserver
function default_dir_mode($temp_dir) {
	if( is_writable($temp_dir))
	{
	  $dirname = $temp_dir.'/test_permissions/';
	  mkdir($dirname);
	  $default_dir_mode = '0'.substr(sprintf('%o', fileperms($dirname)), -3);
	  rmdir($dirname);
	} else {
	  $default_dir_mode = '0777';
	}
	return $default_dir_mode;
}


// Begin check to see if form was even submitted
// Set error if no post vars found
if(!isset($_POST['website_title']))
{
	set_error('Please fill-in the form below');
}
// End check to see if form was even submitted

// Begin path and timezone details code

// Check if user has entered the installation url
if(!isset($_POST['lepton_url']) || $_POST['lepton_url'] == '') {
	set_error('Please enter an absolute URL', 'lepton_url');
} else {
	$lepton_url = $_POST['lepton_url'];
}
// Remove any slashes at the end of the URL
if(substr($lepton_url, strlen($lepton_url)-1, 1) == "/") {
	$lepton_url = substr($lepton_url, 0, strlen($lepton_url)-1);
}
if(substr($lepton_url, strlen($lepton_url)-1, 1) == "\\") {
	$lepton_url = substr($lepton_url, 0, strlen($lepton_url)-1);
}
if(substr($lepton_url, strlen($lepton_url)-1, 1) == "/") {
	$lepton_url = substr($lepton_url, 0, strlen($lepton_url)-1);
}
if(substr($lepton_url, strlen($lepton_url)-1, 1) == "\\") {
	$lepton_url = substr($lepton_url, 0, strlen($lepton_url)-1);
}
// Get the default time zone
$timezone_table =  LEPTON_date::get_timezones();
if (isset($_POST['default_timezone_string']) && in_array($_POST['default_timezone_string'], $timezone_table)) {
	$default_timezone_string = $_POST['default_timezone_string'];
	date_default_timezone_set($default_timezone_string);
} else {
	set_error('Please select a valid default timezone', 'default_timezone_string');
}
// End path and timezone details code

// Get the default language
if(!isset($_POST['default_language']) ) {
	set_error('Please select a valid default backend language','default_language');
} else {
	$default_language = $_POST['default_language'];
	// make sure the selected language file exists in the language folder
	if(!file_exists('../languages/' .$default_language .'.php')) {
	  set_error('The language file: \'' .$default_language .'.php\' is missing. Upload file to language folder or choose another language','default_language');
	}
}
// End default language details code

// Begin operating system specific code
// Get operating system
if(!isset($_POST['operating_system']) || $_POST['operating_system'] != 'linux' && $_POST['operating_system'] != 'windows') {
	set_error('Please select a valid operating system');
} else {
	$operating_system = $_POST['operating_system'];
}
// Work-out file permissions
if($operating_system == 'windows') {
	$file_mode = '0644';
	$dir_mode = '0755';
} elseif(isset($_POST['world_writeable']) && $_POST['world_writeable'] == 'true') {
	$file_mode = '0666';
	$dir_mode = '0777';
} else {
	$file_mode = default_file_mode('../temp');
	$dir_mode = default_dir_mode('../temp');
}
// End operating system specific code

// Begin database details code
// Check if user has entered a database host
if(!isset($_POST['database_host']) || $_POST['database_host'] == '') {
	set_error('Please enter a database host name', 'database_host');
} else {
	$database_host = $_POST['database_host'];
}
/**
 *	Try to get the database port.
 */
$database_port = isset($_POST['database_port']) ? $_POST['database_port']: "3306";
// Check if user has entered a database username
if(!isset($_POST['database_username']) || $_POST['database_username'] == '') {
	set_error('Please enter a database username','database_username');
} else {
	if(preg_match('/^[a-z0-9][a-z0-9_\-\@]+$/i', $_POST['database_username'])) {
	  $database_username = $_POST['database_username'];
	} else {
	  set_error('Only characters a-z, A-Z, 0-9, @, - and _ allowed in database username.', 'database_username');
	}
}
// Check if user has entered a database password
if(!isset($_POST['database_password'])) {
	set_error('Please enter a database password', 'database_password');
} else {
	$database_password = $_POST['database_password'];
}
// Check if user has entered a database name
if(!isset($_POST['database_name']) || $_POST['database_name'] == '') {
	set_error('Please enter a database name', 'database_name');
} else {
	// make sure only allowed characters are specified
	if(preg_match('/^[a-z0-9][a-z0-9_-]+$/i', $_POST['database_name'])) {
	  $database_name = $_POST['database_name'];
	}else{
	  // contains invalid characters (only a-z, A-Z, 0-9 and _ allowed to avoid problems with table/field names)
	  set_error('Only characters a-z, A-Z, 0-9, - and _ allowed in database name.', 'database_name');
	}
}
// Get table prefix
if(preg_match('/^[a-z0-9_]+$/i', $_POST['table_prefix']) || $_POST['table_prefix'] == '' ) {
	$table_prefix = $_POST['table_prefix'];
} else {
	// contains invalid characters (only a-z, A-Z, 0-9 and _ allowed to avoid problems with table/field names)
	set_error('Only characters a-z, A-Z, 0-9 and _ allowed in table_prefix.', 'table_prefix');
}
// End database details code

// Begin website title code
// Get website title
if(!isset($_POST['website_title']) || $_POST['website_title'] == '') {
	set_error('Please enter a website title', 'website_title');
} else {
	$website_title = addslashes($_POST['website_title']);
}
// End website title code

// Begin admin user details code
// Get admin username
if(!isset($_POST['admin_username']) || $_POST['admin_username'] == '') {
	set_error('Please enter a username for the Administrator account','admin_username');
} else {
	$admin_username = $_POST['admin_username'];
}
// Get admin email and validate it
if(!isset($_POST['admin_email']) || $_POST['admin_email'] == '') {
	set_error('Please enter an email for the Administrator account','admin_email');
} else {
	$admin_email = $_POST['admin_email'];
	if( false == filter_var( $admin_email, FILTER_VALIDATE_EMAIL) ) {
	  set_error('Please enter a valid email address for the Administrator account','admin_email');
	}
}
// Get the two admin passwords entered, and check that they match
if(!isset($_POST['admin_password']) || $_POST['admin_password'] == '') {
	set_error('Please enter a password for the Administrator account','admin_password');
} else {
	$admin_password = $_POST['admin_password'];
}
if(!isset($_POST['admin_repassword']) || $_POST['admin_repassword'] == '') {
	set_error('Please make sure you re-enter the password for the Administrator account','admin_repassword');
} else {
	$admin_repassword = $_POST['admin_repassword'];
}
if($admin_password != $admin_repassword) {
	set_error('Sorry, the two Administrator account passwords you entered do not match','admin_repassword');
}
// End admin user details code

// Include  functions file
$lepton_path = str_replace(array('/install','\install'), '', dirname(__FILE__));

// create a new GUID for this installation
$lepton_guid = LEPTON_handle::createGUID();

define('DB_TYPE', 'mysql');
define('DB_HOST', $database_host);
define('DB_PORT', $database_port);
define('DB_USERNAME', $database_username);
define('DB_PASSWORD', $database_password);
define('DB_NAME', $database_name);
define('TABLE_PREFIX', $table_prefix);
define('LEPTON_PATH', str_replace( array("\install", "/install"), "", dirname(__FILE__)));
define('LEPTON_URL', $lepton_url);
define('ADMIN_PATH', LEPTON_PATH.'/backend');
define('ADMIN_URL', $lepton_url.'/backend');
define('LEPTON_GUID', $lepton_guid);


// Try and write settings to config file
$config_content = "" .
"<?php\n".
"\n".
"if(defined('LEPTON_PATH')) { die('By security reasons it is not permitted to load \'config.php\' twice!! ".
"Forbidden call from \''.\$_SERVER['SCRIPT_NAME'].'\'!'); }\n\n".
"// config file created by LEPTON ".LEPTON_VERSION."\n".
"\n".
"define('LEPTON_PATH', dirname(dirname(__FILE__)));\n".
"define('LEPTON_URL', '".$lepton_url."');\n".
"define('ADMIN_PATH', LEPTON_PATH.'/backend');\n".
"define('ADMIN_URL', LEPTON_URL.'/backend');\n".
"\n".
"define('LEPTON_GUID', '".$lepton_guid."');\n".
"\n".
"if (!defined('LEPTON_INSTALL_PROCESS')) require_once(LEPTON_PATH.'/framework/initialize.php');\n".
"\n";

$config_filename = '../config/config.php';

// Check if the file exists and is writable first.

if (($handle = fopen($config_filename, 'w')) === false)
{
    set_error("Cannot open the configuration file ($config_filename)");
}
else
{
    if (fwrite($handle, $config_content, strlen($config_content)) === false)
	{
        fclose($handle);
        set_error("Cannot write to the configuration file ($config_filename)");
	}
	// Close file
	fclose($handle);
}

// include needed functions and files
LEPTON_handle::register("random_string");

/**
 *  delete lepton.ini file if installation has failed before
 */
$temp_path = LEPTON_PATH . "/config/lepton.ini.php";
if (file_exists($temp_path))
{
	$result = unlink ($temp_path);
	if (false === $result)
	{
        echo "Cannot delete file " . $temp_path . ". Please check file permissions and ownership or delete file manually.";
	}
}

/**
 *  create vars for database encryption
 */
if (function_exists('openssl_cipher_iv_length'))
{
    $db_key = sprintf('%04x%04x%04x%04x%04x%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
	$cipher = 'AES-256-CBC';
	$ivlen = openssl_cipher_iv_length($cipher);
	$iv = random_string($ivlen,'pass');
}
else
{
	$db_key = sprintf('%04x%04x%04x%04x%04x%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
	$cipher = 'AES-256-CBC';
	$ivlen = 16;
	$iv = random_string($ivlen,'pass');
}

/**
 *	Write the db lepton.ini file
 */
$ini_filepath = "../config/lepton.ini.php";
$s = ";
; <?php die(); ?>
; 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
;
;

; ini file created by LEPTON ".LEPTON_VERSION."

; DataBase-setup for LEPTON-CMS
[database]
type = 'mysql'
host = '".$database_host."'
port = '".$database_port."'
user = '".$database_username."'
pass = '".$database_password."'
name = '".$database_name."'
prefix = '".$table_prefix."'

key = '".$db_key."'
cipher = '".$cipher."'
iv = '".$iv."'
options = 0

; Set length for username, password and other constants
[system_const]
AUTH_MIN_LOGIN_LENGTH = 3
AUTH_MAX_LOGIN_LENGTH = 128
AUTH_MIN_PASS_LENGTH = 6
AUTH_MAX_PASS_LENGTH = 128
SUBVERSION = ''
MAX_REGISTRATION_TIME = 3600
MAX_WYSIWYG_HISTORY = 6
CRONJOB = 0	  ; @DEPRECATED_TEMP 20251010: this class will be removed in L* > 7.5.0, use external cronjobs instead   0 = disabled, 1 = FE only, 2 = BE only, 3 = BE + FE

; Set allowed additional chars for email,usernames and passwords (details: https://doc.lepton-cms.org/docu/english/core/allowed-chars.php)
[custom_vars]
additional_email_chars = ''
additional_usernames_chars = 'äöüÄÖÜ'
additional_password_chars = '@\?'
tfa_code_expires = '3600'	; in seconds => 1 hour
";

$fp = fopen($ini_filepath, 'w');
if ($fp)
{
	fwrite( $fp , $s );
	fclose( $fp);
} else {
	set_error("Cannot open the setup file for the db!");
}

// Check if the user has entered a correct path
if (!file_exists(LEPTON_PATH . '/framework/classes/lepton_admin.php'))
{
	set_error('It seems that the absolute path you entered is incorrect');
}


// Re-connect to the database, this time using built-in database class
$database = LEPTON_database::getInstance();

/** **************
 *  Install tables
 */

// Remove tables if they exist
$tables = array(
	"pages",
	"sections",
	"settings",
	"users",
	"groups",
	"search",
	"temp",
	"addons",
	"mod_droplets",
	"mod_droplets_settings",
	"mod_droplets_permissions"
);

foreach ($tables as $table)
{
    $database->simple_query("DROP TABLE IF EXISTS `" . TABLE_PREFIX . $table . "`");
}

// Force db to utf8mb4 if possible -> to avoid mysql-error #1071 - Specified key was too long; max key length is 767 bytes
$mysql_info = $database->get_db_handle()->getAttribute(PDO::ATTR_SERVER_VERSION);
if ($mysql_info < '5.8') {
    $database->simple_query("ALTER DATABASE `" . DB_NAME . "` DEFAULT CHARACTER SET utf8 COLLATE = utf8_general_ci");
	$charset = "utf-8";
}
else
{
    $database->simple_query("ALTER DATABASE `" . DB_NAME . "` DEFAULT CHARACTER SET utf8mb4 COLLATE = utf8mb4_unicode_ci");
	$charset = "utf-8";
}

// Try installing tables
// Pages table
$table_fields ="
	  `page_id` int(11) NOT NULL auto_increment,
	  `parent` int(11) NOT NULL DEFAULT 0,
	  `root_parent` int(11) NOT NULL DEFAULT 0,
	  `level` int(11) NOT NULL DEFAULT 0,
	  `link` text,
	  `target` varchar(7) NOT NULL DEFAULT '',
	  `page_title` varchar(255) NOT NULL DEFAULT '',
	  `menu_title` varchar(255) NOT NULL DEFAULT '',
	  `description` text,
	  `keywords` text,
	  `page_trail` text,
	  `template` varchar(255) NOT NULL DEFAULT '',
	  `visibility` varchar(255) NOT NULL DEFAULT '',
	  `position` int(11) NOT NULL DEFAULT 0,
	  `menu` int(11) NOT NULL DEFAULT 0,
	  `language` varchar(5) NOT NULL DEFAULT '',
	  `page_code` varchar(100) NOT NULL DEFAULT '',
	  `open_tree` int(1) NOT NULL DEFAULT 0,
	  `searching` int(11) NOT NULL DEFAULT 0,
	  `admin_groups` text,
	  `viewing_groups` text,
	  `modified_when` int(11) NOT NULL DEFAULT 0,
	  `modified_by` int(11) NOT NULL DEFAULT 0,
	   PRIMARY KEY ( `page_id` )
	   ";
LEPTON_handle::install_table('pages', $table_fields);

// Sections table
$table_fields ="
	  `section_id` int(11) NOT NULL auto_increment,
	  `page_id` int(11) NOT NULL DEFAULT 0,
	  `position` int(11) NOT NULL DEFAULT 0,
	  `module` varchar(255) NOT NULL DEFAULT '',
	  `block` int(11) NOT NULL DEFAULT 0,
	  `publ_start` int(11) NOT NULL DEFAULT 0,
	  `publ_end` int(11) NOT NULL DEFAULT 0,
	  `name` varchar(255) NOT NULL DEFAULT 'no name',
	   PRIMARY KEY ( `section_id` )
	   ";
LEPTON_handle::install_table('sections', $table_fields);

// Settings table
$table_fields ="
	  `setting_id` int(11) NOT NULL auto_increment,
	  `name` varchar(255) NOT NULL DEFAULT '',
	  `value` TEXT NOT NULL,
	  PRIMARY KEY ( `setting_id` )
	";
LEPTON_handle::install_table('settings', $table_fields);

// insert standard settings; (10, 'prompt_mysql_errors', 'false') was obsolete and had been removed
$page_dir = (intval($_POST['page_dir']) == 0) ? '' : '/page';

$field_values =	"
	  (1, 'lepton_version', '".LEPTON_VERSION."'),
	  (2, 'website_title', '".$website_title."'),
	  (3, 'website_description', ''),
	  (4, 'website_keywords', ''),
	  (5, 'website_header', '".$website_title."'),
	  (6, 'website_footer', 'settings/website footer'),
	  (7, 'backend_title', '".$website_title."'),
	  (8, 'upload_whitelist', '".implode(',',lib_r_filemanager::allowed_image_types).",gz,pdf'),
	  (9, 'er_level', '-1'),
	  (11, 'default_language', '".$default_language."'),
	  (12, 'app_name', 'lep".$session_rand."'),
	  (13, 'sec_anchor', 'lep_'),
	  (14, 'default_timezone_string', '".$default_timezone_string."'),
	  (15, 'default_date_format', 'M d Y'),
	  (16, 'default_time_format', 'g:i A'),
	  (17, 'redirect_timer', '1500'),
	  (18, 'leptoken_lifetime', '1800'),
	  (19, 'max_attempts', '6'),
	  (20, 'home_folders', 'true'),
	  (21, 'default_template', 'semantic'),
	  (22, 'default_theme', 'lepsem'),
	  (23, 'default_charset', '".$charset."'),
	  (24, 'link_charset', '".$charset."'),
	  (25, 'multiple_menus', 'true'),
	  (26, 'page_level_limit', '4'),
	  (27, 'page_trash', 'inline'),
	  (28, 'homepage_redirection', 'false'),
	  (29, 'page_languages', 'false'),
	  (30, 'wysiwyg_editor', 'tinymce'),
	  (31, 'manage_sections', 'true'),
	  (32, 'section_blocks', 'true'),
	  (33, 'frontend_login', 'false'),
	  (34, 'frontend_signup', '0'),
	  (35, 'search', 'public'),
	  (36, 'page_extension', '.php'),
	  (37, 'page_spacer', '-'),
	  (38, 'pages_directory', '".$page_dir."'),
	  (39, 'media_directory', '/media'),
	  (40, 'operating_system', '".$operating_system."'),
	  (41, 'string_file_mode', '".$file_mode."'),
	  (42, 'string_dir_mode', '".$dir_mode."'),
	  (43, 'mailer_routine', 'phpmail'),
	  (44, 'server_email', '".$admin_email."'),
	  (45, 'mailer_default_sendername', 'LEPTON Mailer'),
	  (46, 'mailer_smtp_host', ''),
	  (47, 'mailer_smtp_auth', ''),
	  (48, 'mailer_smtp_secure', 'tls'),
	  (49, 'mailer_smtp_port', '587'),
	  (50, 'mailer_smtp_username', ''),
	  (51, 'mailer_smtp_password', ''),
	  (52, 'mediasettings', ''),
	  (53, 'tfa', '".$_POST['tfa']."'),
	  (54, 'wysiwyg_history', 'false')
	";
LEPTON_handle::insert_values('settings', $field_values);

// install table
$table_fields = "
	  `id` int(11) NOT NULL AUTO_INCREMENT,
	  `referrer` text,
	  `ip` varchar(64) NOT NULL DEFAULT '',
	  `email` varchar(128) NOT NULL DEFAULT '',
	  `modified` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
	  `active` int(1) NOT NULL DEFAULT '1',
	  PRIMARY KEY ( `id` )
";
LEPTON_handle::install_table("keepout", $table_fields);

// temp table
$table_fields ="
	  `temp_id` int(2) NOT NULL auto_increment,
	  `temp_browser` varchar(64) NOT NULL DEFAULT '',
	  `temp_ip` varchar(64) NOT NULL DEFAULT '',
	  `temp_time` int(24) NOT NULL DEFAULT 0,
	  `temp_count` int(2) NOT NULL DEFAULT 0,
	  `temp_active` int(1) NOT NULL DEFAULT 0,
	  PRIMARY KEY ( `temp_id` )
	";
LEPTON_handle::install_table('temp', $table_fields);

// log table
$table_fields ="
	  `id` int(11) NOT NULL AUTO_INCREMENT,
	  `logged` datetime NULL DEFAULT NULL,
	  `user_id` int(11) NOT NULL DEFAULT -1,
	  `username` varchar(255) NOT NULL DEFAULT '',
	  `action` varchar(255) NOT NULL DEFAULT '',
	  `log_text` text NOT NULL,
	  `comment` varchar(255) NOT NULL DEFAULT '',
	  `check` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
	  PRIMARY KEY (`id`)
	";
LEPTON_handle::install_table('log', $table_fields);

// Users table
$table_fields ="
	  `user_id` int(11) NOT NULL auto_increment,
	  `groups_id` varchar(255) NOT NULL DEFAULT '0',
	  `active` int(11) NOT NULL DEFAULT 0,
	  `statusflags` int(11) NOT NULL DEFAULT 6,
	  `username` varchar(255) NOT NULL DEFAULT '',
	  `password` varchar(255) NOT NULL DEFAULT '',
	  `last_reset` int(11) NOT NULL DEFAULT 0,
	  `pin` varchar(255) NOT NULL DEFAULT '-1',
	  `pin_set` int(1) NOT NULL DEFAULT 0,
	  `display_name` varchar(255) NOT NULL DEFAULT '',
	  `email` varchar(128) NOT NULL DEFAULT '',
	  `timezone_string` varchar(50) NOT NULL DEFAULT '".$default_timezone_string."',
	  `date_format` varchar(255) NOT NULL DEFAULT '',
	  `time_format` varchar(255) NOT NULL DEFAULT '',
	  `language` varchar(5) NOT NULL DEFAULT '".$default_language."',
	  `home_folder` text,
	  `login_when` int(11) NOT NULL DEFAULT 0,
	  `login_ip` varchar(64) NOT NULL DEFAULT '',
	  `unix_time` int(11) NOT NULL DEFAULT 0,
	   PRIMARY KEY ( `user_id` ),
	   UNIQUE KEY ( `email` ),
	   UNIQUE KEY ( `username` )
	";
LEPTON_handle::install_table('users', $table_fields);

// Groups table
$table_fields ="
	  `group_id` int(11) NOT NULL auto_increment,
	  `name` varchar(255) NOT NULL DEFAULT '',
	  `system_permissions` text,
	  `module_permissions` text,
	  `backend_access` int(1) NOT NULL DEFAULT 1,
	   PRIMARY KEY ( `group_id` ),
	   UNIQUE KEY ( `name` )
	";
LEPTON_handle::install_table('groups', $table_fields);

// Addons table
$table_fields ="
	  `addon_id` int(11) NOT NULL auto_increment,
	  `type` varchar(128) NOT NULL DEFAULT '',
	  `directory` varchar(128) NOT NULL DEFAULT '',
	  `name` varchar(255) NOT NULL DEFAULT '',
	  `description` text,
	  `function` varchar(255) NOT NULL DEFAULT '',
	  `to_delete` int(1) NOT NULL DEFAULT 1,
	  `version` varchar(255) NOT NULL DEFAULT '',
	  `guid` varchar(50) DEFAULT NULL,
	  `platform` varchar(255) NOT NULL DEFAULT '',
	  `author` varchar(255) NOT NULL DEFAULT '',
	  `license` varchar(255) NOT NULL DEFAULT '',
	  PRIMARY KEY (`addon_id`)
	";
LEPTON_handle::install_table('addons', $table_fields);

// Insert default data
// Admin and Register group
$full_system_permissions = ''; // means full access only for admins, all other groups got system_permissions via backend
$insert_admin_group = "INSERT INTO `" . TABLE_PREFIX . "groups` VALUES ('1', 'Administrators', '".$full_system_permissions."', '', 1), ('2', 'Register', '', '', 0)";
$database->simple_query($insert_admin_group);

// Admin user
$insert_admin_user = "INSERT INTO `" . TABLE_PREFIX . "users` (user_id,groups_id,active,username,password,email,display_name,`home_folder`) VALUES ('1','1','1','".$admin_username."','" . password_hash($admin_password, PASSWORD_DEFAULT) . "','".$admin_email."','Administrator', '')";
$database->simple_query($insert_admin_user);

// Make sure that nessesary constants are available defined at this time!
LEPTON_handle::include_files('/framework/constants.php');

// create a htaccess protected secure directory
if (!file_exists(LEPTON_PATH . '/temp/secure'))
{
	mkdir(LEPTON_PATH . '/temp/secure');
	LEPTON_core::change_mode(LEPTON_PATH . '/temp/secure');
}

if (!file_exists(LEPTON_PATH . '/temp/secure/.htaccess'))
{
	$htuser = $admin_username;
	$random_value = random_int(100000,999999);
	$htpassword = password_hash($random_value,PASSWORD_DEFAULT );

$htcontent = "# .htaccess-Datei
AuthType Basic
AuthName 'Protected area - Please insert password!'
AuthUserFile ".LEPTON_PATH."/temp/secure/.htpasswd
require user ".$htuser."
";

$htpwcontent = "# Password file, user:".$htuser.", password: ".$random_value." ~
".$htuser.":".$htpassword."
";

	file_put_contents(LEPTON_PATH . '/temp/secure/.htaccess', $htcontent);
	file_put_contents(LEPTON_PATH . '/temp/secure/.htpasswd', $htpwcontent);
}
// end secure directory


// @DEPRECATED_TEMP 20251010: this class will be removed in L* > 7.5.0, use external cronjobs instead
// write cronjob ini
/*
LEPTON_handle::register("random_string");
$value = random_string(8, "alphanum");

$ini_content = ";
; <?php die(); ?>
; 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
;
;

; Setup cronjobs
[file_info]
path = '/temp/secure/'
file = 'cj_example.php'
key = '".$value."'	  ; key should have a length referring to AUTH_MIN_PASS_LENGTH
interval = '3600'	  ; minimum time in sec between execution of internal cronjobs

[custom_values]
";
file_put_contents(LEPTON_PATH.'/config/cronjob.ini.php',$ini_content);

// create cronjob example file
$source = LEPTON_PATH.'/config/index.php';
$target = LEPTON_PATH.'/temp/secure/cj_example.php';
if (!copy($source , $target))
{
	echo "Copying of ".$source." failed...\n";
}
*/

LEPTON_handle::include_files('/framework/initialize.php');

$functions = array(
	"load_module",
	"load_language",
	"load_template"
);
LEPTON_handle::register($functions);


// preload droplets
load_module( 'droplets', true);

// Load addons into DB
$dirs = [
	'modules'	=> LEPTON_PATH.'/modules/',
	'templates'	=> LEPTON_PATH.'/templates/',
	'languages'	=>  LEPTON_PATH.'/languages/'
];
$ignore_files= [
	'admin.php',
	'cronjob.php', // @DEPRECATED_TEMP 20251010: this file will be removed in L* > 7.5.0, use external cronjobs instead
	'edit_module_files.php',
	'index.php'
];

foreach($dirs AS $type => $dir)
{
	if(false !== ($handle = opendir($dir))) {
	  $temp_list = array();
	  while(false !== ($file = readdir($handle))) {
	  	if(($file != '') && (substr($file, 0, 1) != '.') && (!in_array($file, $ignore_files))) {
	  	  $temp_list[] = $file;
	  	}
	  }
	  natsort($temp_list);

	  foreach($temp_list as $file) {
	  	// Get addon type

	  	if($type == 'modules') {
	  	  if($file == "droplets")
	  	  {
	  	  	continue;
	  	  }

	  	  require ($dir.'/'.$file.'/info.php');
	  	  load_module($file, true);

	  	  foreach(
	  	  	array(
	  	  	  'module_license', 'module_author'  , 'module_name', 'module_directory',
	  	  	  'module_version', 'module_function', 'module_description',
	  	  	  'module_platform', 'module_guid'
	  	  	) as $varname
	  	  )
	  	  {
	  	  	if (isset(  ${$varname} ) ) unset( ${$varname} );
	  	  }
	  	}
	  	elseif($type == 'templates')
	  	{
	  	  require ($dir.'/'.$file.'/info.php');
	  	  load_template($file);

	  	  foreach(
	  	  	array(
	  	  	  'template_license', 'template_author'  , 'template_name', 'template_directory',
	  	  	  'template_version', 'template_function', 'template_description',
	  	  	  'template_platform', 'template_guid'
	  	  	) as $varname
	  	  )
	  	  {
	  	  	if (isset(  ${$varname} ) ) unset( ${$varname} );
	  	  }

	  	}
	  	elseif($type == 'languages')
	  	{
	  	  load_language($file);
	  	}
	  }
	  closedir($handle);
	  unset($temp_list);
	}
}	// end of if install_tables

// create first standard page
	require_once("init_page.php");
	$p = new init_page();
	$p->language = $default_language;
	$p->build_page();

// redirect to the backend login
header("Location: ../install/support.php" );
