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

// Check if user uploaded a file
if (!isset($_FILES['userfile']) || $_FILES['userfile']['size'] == 0)
{
    $leptoken = (true == isset($_GET['leptoken'])) ? "?leptoken=".$_GET['leptoken'] : "";
	header("Location: index.php".$leptoken);
	exit(0);
}

$files = [
	"cleanup",
	"directory_list",
	"load_module",
	"preCheckAddon",
	"rename_recursive_dirs",
	"rm_full_dir",
	"versionCompare"
];
LEPTON_handle::register($files);


$admin = LEPTON_admin::getInstance('Addons', 'modules_install');
$MESSAGE = LEPTON_core::getGlobal("MESSAGE");

// Check if module dir is writable (doesn't make sense to go on if not)
if (!is_writable(LEPTON_PATH.'/modules/'))
{
	  $admin->print_error($MESSAGE['GENERIC_BAD_PERMISSIONS']);
}

// Set temp vars
$temp_dir   = LEPTON_PATH.'/temp/';
$temp_file  = $temp_dir . $_FILES['userfile']['name'];
$temp_unzip = LEPTON_PATH.'/temp/unzip/';

// make sure the temp directory exists, is writable and is empty
rm_full_dir($temp_unzip);
LEPTON_core::make_dir($temp_unzip);

// Try to upload the file to the temp dir
if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $temp_file))
{
 	cleanup( $temp_unzip, $temp_file );
	$admin->print_error($MESSAGE['GENERIC_CANNOT_UPLOAD']);
}

// to avoid problems with two admins installing modules at the same time, we create a unique subdir
$temp_subdir = $temp_unzip.basename($_FILES['userfile']['tmp_name']).'/';
LEPTON_core::make_dir( $temp_subdir );

// Setup the PclZip object
$archive = lib_lepton::getToolInstance("pclzip",$temp_file);

// Unzip the files to the temp unzip folder
$list = $archive->extract(PCLZIP_OPT_PATH, $temp_subdir);

//	Check for GitHub zip archive.
if (!file_exists($temp_subdir."info.php")) 
{
	$temp_dirs = [];
	directory_list($temp_subdir, false, 0, $temp_dirs);
	foreach($temp_dirs as &$temp_path)
    {
		if (file_exists($temp_path."/info.php"))
        {
			$temp_subdir = $temp_path."/";
			break;
		}
	}
}

// Check if uploaded file is a valid Add-On zip file
if (!($list && file_exists($temp_subdir . 'index.php')))
{
    cleanup($temp_unzip, $temp_file);
    $admin->print_error($MESSAGE['GENERIC_INVALID_ADDON_FILE']."[1]");
}

// As we are going to check for a valid info.php, let's unset all vars expected there to see if they're set correctly
foreach(
    [
        'module_license', 'module_author'  , 'module_name', 'module_directory',
        'module_version', 'module_function', 'module_description',
        'module_platform'
    ] as $varname
) 
{
    unset( ${$varname} );
}

// Include the modules info file
require($temp_subdir.'info.php');

// Perform Add-on requirement checks before proceeding
preCheckAddon($temp_file, $temp_subdir);

// Check if the file is valid
if(
    (!isset($module_license))	||
    (!isset($module_author))	||
    (!isset($module_directory))	||
    (!isset($module_name))		||
    (!isset($module_version))	||
    (!isset($module_function))	||
	(!isset($module_guid))
	) 
{
	cleanup( $temp_unzip, $temp_file );
	$admin->print_error(sprintf($MESSAGE["MOD_MISSING_PARTS_NOTICE"], $module_name));
}

foreach(
    [
        'module_license', 'module_author'  , 'module_name', 'module_directory',
        'module_version', 'module_function', 'module_description',
        'module_platform'
    ] as $varname
	) 
{
   ${'new_lepton_'.$varname} = ${$varname};
   unset( ${$varname} );
}

// So, now we have done all preinstall checks, lets see what to do next
$module_directory   = $new_lepton_module_directory;
$action             = "install";
$temp_db_module_info = [];

if ( is_dir(LEPTON_PATH.'/modules/'.$module_directory) ) 
{
    $action = "upgrade";

	// Look into the db for this module
    $database->execute_query(
    	"SELECT * FROM ".TABLE_PREFIX."addons WHERE type = 'module' AND directory = '". $module_directory ."'",
		true,
		$temp_db_module_info,
		false
	);
	
	if(!empty($temp_db_module_info)) 
	{
    	// There is an entry in the db, look for "old" info.php
    	if ( file_exists(LEPTON_PATH.'/modules/'.$module_directory.'/info.php') ) 
		{
		    require(LEPTON_PATH.'/modules/'.$module_directory.'/info.php');

    		// Version to be installed is older than currently installed version
    		if ( versionCompare($module_version, $new_lepton_module_version, '>=') ) 
			{
    	       	cleanup( $temp_unzip, $temp_file );
				$admin->print_error( $MESSAGE['GENERIC_ALREADY_INSTALLED'] );
			}
		}
	}
}

// Set module directory
$module_dir = LEPTON_PATH.'/modules/'.$module_directory;

// Make sure the module dir exists, and chmod if needed
LEPTON_core::make_dir($module_dir);

// copy files from temp folder
if ( rename_recursive_dirs( $temp_subdir, $module_dir ) !== true ) 
{
    cleanup( $temp_unzip, $temp_file );
    $admin->print_error( $MESSAGE['GENERIC_NOT_UPGRADED'] );
}

// remove temp
cleanup( $temp_unzip, $temp_file );

// load info.php again to have current values
if ( file_exists(LEPTON_PATH.'/modules/'.$module_directory.'/info.php') ) 
{
    require(LEPTON_PATH.'/modules/'.$module_directory.'/info.php');
}

// Run the modules install // upgrade script if there is one
if ( file_exists($module_dir.'/'.$action.'.php') ) 
{
	  require($module_dir.'/'.$action.'.php');
}

// Finish installation
if ( ( $action == "install" ) || ( empty($temp_db_module_info) ) )
{
	load_module($module_directory);
	
	// let admin set access permissions for modules of type 'page' and 'tool'
	if ( $module_function == 'page' || $module_function == 'tool' )
	{
		$all_groups = [];
		$database->execute_query(
			"SELECT * FROM ".TABLE_PREFIX."groups WHERE group_id <> 1",
			true,
			$all_groups,
			true
		);

		$oTwig = lib_twig_box::getInstance();

		echo $oTwig->render(
			"@theme/set_group_permissions.lte",
			[
				'action_url'	=> ADMIN_URL."/modules/save_permissions.php",
				'all_groups'	=> $all_groups,
				'MESSAGE'		=> $MESSAGE,
				'TEXT'			=> $TEXT,
				'module_directory' => $module_directory
			]
		);
	}
   	else 
	{
		$admin->print_success($MESSAGE['GENERIC_INSTALLED']);
	}
}
elseif ( $action == "upgrade" ) 
{
	LEPTON_handle::upgrade_modules($module_directory);
	$admin->print_success($MESSAGE['GENERIC_UPGRADED']);
}

$admin->print_footer();
