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


// set error level
ini_set('display_errors', 1);
error_reporting(E_ALL);

// routine [1]: remove not installed standard templates
$lepton3 = $database->get_one("SELECT addon_id FROM ".TABLE_PREFIX."addons WHERE type = 'template' and directory = 'lepton3' ");
if(is_null($lepton3))
{
	LEPTON_handle::delete_obsolete_directories(['/templates/lepton3']);
}

$semantic = $database->get_one("SELECT addon_id FROM ".TABLE_PREFIX."addons WHERE type = 'template' and directory = 'semantic' ");
if(is_null($semantic))
{
	LEPTON_handle::delete_obsolete_directories(['/templates/semantic']);
}

$blank = $database->get_one("SELECT addon_id FROM ".TABLE_PREFIX."addons WHERE type = 'template' and directory = 'blank' ");
if(is_null($blank))
{
	LEPTON_handle::delete_obsolete_directories(['/templates/blank']);
}

// routine [2]: remove pages directory if not /page
if(PAGES_DIRECTORY != '/page')
{
	LEPTON_handle::delete_obsolete_directories(['/page']);
}

// start with update
echo ('<h3>Current process: updating to LEPTON 7.4.0</h3>');

// add field to users table, used for tfa
echo '<h5>Add field to users table</h5>';

$fields = [];
$database->describe_table(
    TABLE_PREFIX."users",
    $fields,
    LEPTON_database::DESCRIBE_ONLY_NAMES
);

if (!in_array('unix_time', $fields)) 
{
	$database->simple_query("ALTER TABLE ".TABLE_PREFIX."users ADD `unix_time` INT (11) NOT NULL DEFAULT '0' AFTER `login_ip` ");
}

echo "<h5>Add field to users table: successfull</h5>";

// LEPTON 7.4: add field to users table, used to keep open/close state of page tree
echo '<h5>Add field to pages table</h5>';

$fields = [];
$database->describe_table(
    TABLE_PREFIX."pages",
    $fields,
    LEPTON_database::DESCRIBE_ONLY_NAMES
);

if (!in_array('open_tree', $fields)) 
{
	$database->simple_query("ALTER TABLE ".TABLE_PREFIX."pages ADD `open_tree` INT (1) NOT NULL DEFAULT '0' AFTER `page_code` ");
}
echo "<h5>Add field to pages table: successfull</h5>";

// Add fields to lepton.ini and rewrite the ini file
echo ('<h5>Current process : modify lepton.ini</h5>');	

$filename = LEPTON_PATH.'/config/lepton.ini.php';
$aCurrConfig = parse_ini_string(";".file_get_contents($filename), true );
if (is_writable($filename))
{
    $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
;
;
;   Re-written by upgrade-script for L* 7.4.0
;
; DataBase-setup for LEPTON-CMS
[database]
type = '".$aCurrConfig['database']['type']."'
host = '".$aCurrConfig['database']['host']."'
port = '".$aCurrConfig['database']['port']."'
user = '".$aCurrConfig['database']['user']."'
pass = '".$aCurrConfig['database']['pass']."'
name = '".$aCurrConfig['database']['name']."'
prefix = '".$aCurrConfig['database']['prefix']."'

key = '".$aCurrConfig['database']['key']."';
cipher = '".$aCurrConfig['database']['cipher']."'
iv = '".$aCurrConfig['database']['iv']."'
options = '".$aCurrConfig['database']['options']."'


; Set length for username, password and other constants
[system_const]
AUTH_MIN_LOGIN_LENGTH = '".$aCurrConfig['system_const']['AUTH_MIN_LOGIN_LENGTH']."'
AUTH_MAX_LOGIN_LENGTH = '".$aCurrConfig['system_const']['AUTH_MAX_LOGIN_LENGTH']."'
AUTH_MIN_PASS_LENGTH = '".$aCurrConfig['system_const']['AUTH_MIN_PASS_LENGTH']."'
AUTH_MAX_PASS_LENGTH = '".$aCurrConfig['system_const']['AUTH_MAX_PASS_LENGTH']."'
SUBVERSION = '".$aCurrConfig['system_const']['SUBVERSION']."'
MAX_REGISTRATION_TIME = '".$aCurrConfig['system_const']['MAX_REGISTRATION_TIME']."'
MAX_WYSIWYG_HISTORY = '".$aCurrConfig['system_const']['MAX_WYSIWYG_HISTORY']."'
CRONJOB = '".$aCurrConfig['system_const']['CRONJOB']."'		; 0 = disabled, 1 = FE only, 2 = BE only, 3 = BE + FE

; Set allowed additional chars for email,usernames and passwords (see https://doc.lepton-cms.org/docu/english/core/allowed-chars.php) 
[custom_vars]
additional_email_chars = '".$aCurrConfig['custom_vars']['additional_email_chars']."'
additional_usernames_chars = '".$aCurrConfig['custom_vars']['additional_usernames_chars']."'
additional_password_chars = '".$aCurrConfig['custom_vars']['additional_password_chars']."'
tfa_code_expires = '3600'	; in seconds => 1 hour
";    
    if (!$handle = fopen($filename, "w")) // NOT append!
    {
        echo('Cannot open file'); 
    }

    if (!fwrite($handle, $content)) 
	{
         echo('Cannot write into file'); 
    }

    fclose($handle);
	echo ('<h5>Current process : rewrite lepton.ini successful</h5>');	

}
 else 
{
   echo ('<h5>Current process : rewrite lepton.ini failed!</h5>');	
}
// End of "update the ini-file


// rework root parents in pages table
echo '<h5>Rework root parents in pages table</h5>';
$aAllPages = [];
$database->execute_query(
	"SELECT page_id FROM ".TABLE_PREFIX."pages WHERE root_parent = 0 ",
	true,
	$aAllPages,
	true	
);

foreach ($aAllPages as $page)
{
	$database->simple_query("UPDATE ".TABLE_PREFIX."pages SET root_parent  = ".$page['page_id']." WHERE page_id  = ".$page['page_id']);
}
echo "<h5>Rework root parents in pages table: successfull</h5>";


// rename _custom language files to _add files
echo '<h5>Rename _custom language files to _add files</h5>';
$files = glob(LEPTON_PATH.'/languages/*_custom.php');
$message = 'Language filename was modified to LANGUAGE_add.php';
if (!empty($files))
{
    foreach ($files as $language)
    {
        $language_add = str_replace('_custom.php', '_add.php', $language);
        rename($language, $language_add);
        echo (LEPTON_tools::display($message, 'pre', 'ui orange message'));
    }
} else
{
    echo (LEPTON_tools::display('No files to be renamed', 'pre', 'ui orange message'));
}

echo "<h5>Rename _custom language files to _add files: successfull</h5>";


// remove files and directories
echo '<h5>Current process: delete not needed files and directories</h5>';
// [1] directories
$directory_names = [
	'/modules/lib_lepton/datetools',
];
LEPTON_handle::delete_obsolete_directories( $directory_names );


// [2] files
$file_names = [
	'/framework/functions/function.show_wysiwyg_editor.php',
	'/backend/users/users.php',			// seems that this one was forgtten in one release
	'/templates/lepsem/templates/message.lte',		// this file is not in use
	'/templates/semantic/frontend/login/tfa_form.lte',		// this file is not in use
	'/backend/pages/master_page.php',		// this file is not in use any longer
];
LEPTON_handle::delete_obsolete_files( $file_names );
echo "<h5>Delete not needed files and directories: successfull</h5>";

// upgrade updated modules
echo '<h5>Current process: run modules upgrade.php</h5>';

$module_names = [];
$database->execute_query(
	"SELECT directory FROM ".TABLE_PREFIX."addons WHERE type = 'module'",
	true,
	$module_names,
	true	
);

$all_modules = [];
foreach($module_names as $item)
{
	$all_modules[] = $item['directory'];
}

LEPTON_handle::upgrade_modules($all_modules);
echo "<h5>run upgrade.php of all modules: successfull</h5>";


// update release and success message
echo ('<h5>Current process: set new release number</h5>');
	$database->simple_query("UPDATE ".TABLE_PREFIX."settings SET value ='7.4.0' WHERE name = 'lepton_version' ");
echo "<h5>update to LEPTON 7.4.0 successfull!</h5><br />";