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


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

echo ('<h3>Current process : updating to LEPTON 4.3.0</h3>');

// [2] db changes
// [2.1]
echo '<h5>Install new field [tfa] in settings table</h5>';
$bTempResult = $database->get_one("SELECT `value` from `".TABLE_PREFIX."settings` WHERE `name`='tfa'");
if( NULL === $bTempResult )
{
    $database->simple_query('INSERT INTO `'.TABLE_PREFIX.'settings` (`setting_id`, `name`, `value`) VALUES (NULL, "tfa", "false")');
    if($database->is_error()) {
	    echo LEPTON_tools::display( $database->get_Error() , "div", "ui red message");
    } else {
	    echo '<h5>install new field [tfa] in settings table: successful</h5>'; 
    }
}

// [2.2]
echo '<h5>install new fields in users table</h5>';

$aTableFields = [];
$database->describe_table( TABLE_PREFIX."users", $aTableFields );
$aLookFor = ["pin" => 0, "pin_set" => 0];
foreach($aTableFields as $ref)
{
    foreach($aLookFor as $key => &$value)
    {
        if($ref['Field'] == $key)
        {
            $value = 1; // 1 stands for: "found; field exists"
            break;
        }
    }
}
// [2.2.1] entries
// [2.2.1.1]
$bGotErrors = false;
if( 0 === $aLookFor["pin"] )
{
    $database->simple_query('ALTER TABLE `'.TABLE_PREFIX.'users` ADD `pin` VARCHAR(255) NOT NULL DEFAULT "-1" AFTER `last_reset` ');
    if($database->is_error()) {
        $bGotErrors = true;
	    echo LEPTON_tools::display( $database->get_Error() , "div", "ui red message");
    }
}
// [2.2.1.2]
if( 0 === $aLookFor["pin_set"] )
{
    $database->simple_query('ALTER TABLE `'.TABLE_PREFIX.'users` ADD `pin_set` INT(1) NOT NULL DEFAULT "0" AFTER `pin` ');
    if($database->is_error()) {
        $bGotErrors = true;
	    echo LEPTON_tools::display( $database->get_Error() , "div", "ui red message");
    }
}

echo "<h5>install new fields in users table: ".( ($bGotErrors === false) ? "successful" : "failed!" ). "</h5>"; 

echo '<h5>set default in pages table</h5>';
$database->simple_query('ALTER TABLE '.TABLE_PREFIX.'pages CHANGE page_code page_code VARCHAR(100) NOT NULL DEFAULT "" ');
if($database->is_error()) {
	echo LEPTON_tools::display( $database->get_Error() , "div", "ui red message");
} else {
	echo '<h5>set default in pages table: successful</h5>'; 
}

// add secure vars
/*
echo ('<h5>Current process : add secure vars</h5>');	
require_once LEPTON_PATH.'/framework/functions/function.random_string.php';

$filename = LEPTON_PATH.'/config/lepton.ini.php';

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');
	
}
*/

// [1] modify lepton.ini
echo ('<h5>Current process : modify lepton.ini</h5>');	
$filename = LEPTON_PATH.'/config/lepton.ini.php';

$aTempConfig = parse_ini_string(";".file_get_contents($filename), true );

$sIniAddition = "";
if(!isset($aTempConfig['system_const']))
{
    // [1.1] The comlete key/chapter is missing
    $sIniAddition = "
; Set length for username and password
[system_const]
AUTH_MIN_LOGIN_LENGTH = 3
AUTH_MAX_LOGIN_LENGTH = 128
AUTH_MIN_PASS_LENGTH = 6
AUTH_MAX_PASS_LENGTH = 128
SUBVERSION = ''
";
} else {
    // [1.2] The key/chapter is there - so we have to look for the basic values
    
    // [1.2.1] AUTH_MIN_LOGIN_LENGTH
    if(!isset($aTempConfig['system_const']['AUTH_MIN_LOGIN_LENGTH']))
    {
       $sIniAddition .= "
AUTH_MIN_LOGIN_LENGTH = 3";
        echo("<p>Add missing key for <strong>AUTH_MIN_LOGIN_LENGTH</strong>.</p>"); 
    }
    
    // [1.2.2] AUTH_MAX_LOGIN_LENGTH
    if(!isset($aTempConfig['system_const']['AUTH_MAX_LOGIN_LENGTH']))
    {
       $sIniAddition .= "
AUTH_MAX_LOGIN_LENGTH = 128";
        echo("<p>Add missing key for <strong>AUTH_MAX_LOGIN_LENGTH</strong>.</p>");
    }
    
    // [1.2.3] AUTH_MIN_PASS_LENGTH
    if(!isset($aTempConfig['system_const']['AUTH_MIN_PASS_LENGTH']))
    {
       $sIniAddition .= "
AUTH_MIN_PASS_LENGTH = 6";
        echo("<p>Add missing key for <strong>AUTH_MIN_PASS_LENGTH</strong>.</p>");
    }
    
    // [1.2.4] AUTH_MAX_PASS_LENGTH
    if(!isset($aTempConfig['system_const']['AUTH_MAX_PASS_LENGTH']))
    {
       $sIniAddition .= "
AUTH_MAX_PASS_LENGTH = 128";
        echo("<p>Add missing key for <strong>AUTH_MAX_PASS_LENGTH</strong>.</p>");
    }
    
    // [1.2.5] SUBVERSION
    if(!isset($aTempConfig['system_const']['SUBVERSION']))
    {
       $sIniAddition .= "
SUBVERSION = ''";
        echo("<p>Add missing key for <strong>SUBVERSION</strong>.</p>");
    }
    
}

// [1.3] Update the file
if ( (strlen($sIniAddition) > 0 ) && ( is_writable($filename) ) )
{
    if (!$handle = fopen($filename, "a")) // append
    {
        echo('Cannot open file'); 
    }

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

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

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

// install new modules
echo '<h5>install new addon lib_fomantic</h5>';
if (!function_exists('load_module')) require_once( LEPTON_PATH."/framework/summary.functions.php");

$install = array (
	"/modules/lib_fomantic",
	"/modules/reset_pin"
);

// install
foreach ($install as $module)
{
    $temp_path = LEPTON_PATH . $module ;

	require ($temp_path.'/info.php');
	load_module( $temp_path, 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} );
		}
} 

echo '<h5>install new addon lib_fomantic: successful</h5>'; 

// upgrade updated modules
echo '<h5>Current process : run modules upgrade.php</h5>';  
		 
$module_names = array(
	"addon_info",
	"code2",
	"cookie",
	"droplets",
	"edit_area",
	"initial_page",
	"lib_jquery",
	"lib_lepton",
	"lib_phpmailer",
	"lib_twig",
	"news",
	"quickform",
	"tinymce",
	"wysiwyg_admin"
);
LEPTON_handle::upgrade_modules($module_names);

echo "<h5>run upgrade.php of modified modules: successfull</h5>";

		
echo '<h5>reload all addons</h5>';
		
if (file_exists (LEPTON_PATH.'/install/update/reload.php')) {
		require_once(LEPTON_PATH . '/install/update/reload.php');
}	
		
echo "<h5>reload all addons: successfull</h5>";

// update release and success message
echo ('<h5>Current process : set new release no</h5>');	
$database->simple_query("UPDATE `".TABLE_PREFIX."settings` SET value ='4.3.0' WHERE name='lepton_version'");
if($database->is_error()) {
	echo LEPTON_tools::display( $database->get_Error() , "div", "ui message red");
} else {
	echo "<h3>update to LEPTON 4.3.0 successfull!</h3><br />"; 
}

?>
