<?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 user permissions for admintools (redirect users with wrong permissions)
$admin = LEPTON_admin::getInstance('Admintools', 'admintools', true);
$database = LEPTON_database::getInstance();

$MESSAGE = LEPTON_core::getGlobal("MESSAGE");
$TEXT = LEPTON_core::getGlobal("TEXT");

$msg = [];
$error_msg = [];

$leptoken = (isset($_GET['leptoken'])) ? "?leptoken=".$_GET['leptoken'] : "";
$backlink = "../modules/index.php".$leptoken;

if ($admin->get_permission('admintools') == true)
{
    $post_check = ['reload_modules', 'reload_templates', 'reload_languages'];
	
    // if all addons should be reloaded at once
    if (isset($_GET['reload_all']))
    {
        foreach ($post_check as $key)
        {
            $_POST[$key] = true;
	}     
    }
	
	// register function files
	$file_names = [
		"get_modul_version",
		"load_language",
		"load_module",
		"load_template",
		"scan_current_dir",
		"versionCompare"
	];
	LEPTON_handle::register($file_names);
	
	// load language file
	require_once LEPTON_PATH.'/languages/'.LANGUAGE.'.php';

	// Reload all specified Addons
	$table = TABLE_PREFIX.'addons';
	
	foreach ($post_check as $key)
	{
        if (!isset($_POST[$key]))
		{
            continue;
		}
		
		switch ($key) :
			case 'reload_modules' :
				// [1] get all modules with entry in the addons table
				$bSectionsExists = false;
				$bTablesExists = false;
				
				$aAllAddons = [];
				$database->execute_query(
				    'SELECT directory FROM '.TABLE_PREFIX.'addons WHERE type = "module" ',
				    true,
				    $aAllAddons,
				    true
				);

				// [1.1] search for "active" modules without files
                foreach($aAllAddons as $value)
                {
                    if(file_exists(LEPTON_PATH.'/modules/'.$value['directory']))
                    {
                        load_module($value['directory']);
						$msg[] = '<span class="normal bold green">'.$value['directory'].' :: '.$MESSAGE['ADDON_MODULES_RELOADED'].' [1]</span>';
						continue;
                    }
					else
					{
						// [1.1.1] see if there are sections for these modules
						$aTempPages = [];
						$database->execute_query(
							"SELECT section_id, module, page_id FROM ".TABLE_PREFIX."sections WHERE module = '".$value['directory']."'",
							true,
							$aTempPages,
							true
						);

						// there are still sections
						if(!empty($aTempPages))
						{
							$bSectionsExists = true;
							// we have to warn the user
							foreach( $aTempPages as $data)
							{
								$temp_info = $database->get_one( "SELECT `menu_title` FROM `".TABLE_PREFIX."pages` WHERE `page_id` = ".$data['page_id'] );
								
								$page_url = '<span class="normal bold"> -> <a href="'.ADMIN_URL.'/pages/sections.php?page_id='.$data['page_id'].'">'.$temp_info.'</a> ('.$TEXT['PAGE'].' '.$data['page_id'].')</span>';
								$error_msg[] = '<span class="normal bold">'.$data['module'].'</span> <span class="normal bold red">'.$MESSAGE['GENERIC_CANNOT_UNINSTALL_IN_USE'].'[10]</span>'.$page_url;
							}
						}
						else
						{
							$bSectionsExists = false;
							$msg[] = '<span class="normal bold green">'.$value['directory'].' :: '.$MESSAGE['ADDON_MODULES_RELOADED'].' [20]</span>';
						}

						// [1.1.2] are there active module tables? Loop through modules
						$aTables = [];
						$database->execute_query(
							"SHOW TABLES LIKE '".TABLE_PREFIX."mod_".$value['directory']."%'",
							true,
							$aTables,
							true
						);
						
						if(!empty($aTables))
						{
							$bTablesExists = true;
							$error_msg[] = '<span class="normal bold red">'.$value['directory'].' '.$MESSAGE['RECORD_MODIFIED_FAILED'].'</span>';
						}
						else
						{
							$bTablesExists = false;
							$msg[] = '<span class="normal bold green">'.$value['directory'].' :: '.$MESSAGE['ADDON_MODULES_RELOADED'].' [30]</span>';
						}
						
						// [1.1.3] add module to addons table to save data
						if($bSectionsExists == true || $bTablesExists == true )
						{
							$error_msg[] = '<span class="normal bold red">'.$value['directory'].' '.$MESSAGE['RECORD_MODIFIED_FAILED'].'</span>';
						}
						else
						{
							$database->simple_query("DELETE FROM ".TABLE_PREFIX."addons WHERE directory = '".$value['directory']."' ");
						}							
					}
				}
				
				
				// [2] get all modules with NO entry in the addons table
				$aModules = [];
				$aModules = scan_current_dir(LEPTON_PATH.'/modules');
				
				// [2.1] rework array for further action
				foreach($aAllAddons as $directories)
				{
					foreach($directories as $key => $value)
					{	
						$aDirectories[] = $value;
					}

				}				

				// [2.2] select modules that only have dir and no table entry 
				foreach($aModules['path'] as $check)
				{
					if(!in_array($check,$aDirectories))
					{
						// [2.2.1] see if there are sections for these modules
						$aTempPages = [];
						$database->execute_query(
							"SELECT section_id, module, page_id FROM ".TABLE_PREFIX."sections WHERE module = '".$check."' ",
							true,
							$aTempPages,
							true
						);

						// there are still sections
						if(!empty($aTempPages))
						{
							$bSectionsExists = true;
						}

						// [2.2.2] are there active module tables? Loop through modules
						$aTables = [];
						$database->execute_query(
							"SHOW TABLES LIKE '".TABLE_PREFIX."mod_".$check."%'",
							true,
							$aTables,
							true
						);
						
						if(!empty($aTables))
						{
							$bTablesExists = true;
						}
					
						// [2.2.3] add module to addons table to save data
						if($bSectionsExists == true || $bTablesExists == true )
						{
							$msg[] = '<span class="normal bold green">'.$check.' :: '.$MESSAGE['ADDON_MODULES_RELOADED'].' [15]</span>';
							load_module($check);
						}
						else
						{
							$msg[] = '<span class="normal bold red">'.$check.' '.$MESSAGE['RECORD_MODIFIED_FAILED'].'[25]</span>';
							LEPTON_handle::delete_obsolete_directories(['/modules/'.$check]);
						}					
					}
					else
					{
						//$msg[] = '<span class="normal bold green">'.$check.' :: '.$MESSAGE['ADDON_MODULES_RELOADED'].' [11]</span>'; // uncomment for tests
					}	
				}
			break;

			case 'reload_templates' :
				$templates = scan_current_dir(LEPTON_PATH.'/templates');
				if (!empty($templates['path']))
				{
					// Delete all templates from database
					$database->simple_query( "DELETE FROM  `".TABLE_PREFIX."addons`  WHERE `type` = 'template'");
					
					// Reload all templates
                    foreach ($templates['path'] as $file)
					{
						load_template($file);
					}
					// Add success message
					$msg[] = '<span class="normal bold green">'.$MESSAGE['ADDON_TEMPLATES_RELOADED'].'[1]</span>';
				}
				else
				{
					// Add error message
					$error_msg[] = '<span class="normal bold red">'.$MESSAGE['ADDON_ERROR_RELOAD'].' - No templates found!</span> ';
				}
				break;

			case 'reload_languages' :
				$languages = scan_current_dir(LEPTON_PATH.'/languages/', 'php');
				if ( !empty($languages['filename']))
				{
					// Delete all languages from database
					$database->simple_query( "DELETE FROM  ".TABLE_PREFIX."addons  WHERE type = 'language'" );
					
					// Reload all languages
					foreach($languages['filename'] as $file)
					{
						load_language($file);
					}
					
					//  Reload the current language file - otherwise wie've got the last message in e.g. russian.
					require( LEPTON_PATH . '/languages/' . LANGUAGE . '.php' );    
					
					// Add success message
					$msg[] = '<span class="normal bold green">'.$MESSAGE['ADDON_LANGUAGES_RELOADED'].'[1]</span>';
				}
				else
				{
					// Add error message
					$error_msg[] = '<span class="normal bold red">'.$MESSAGE['ADDON_ERROR_RELOAD'].' - No languages found!</span>';
				}
				break;
			endswitch;
	}
}
else
{
    $error_msg[] = '<span class="big bold red">'.$MESSAGE['ADMIN_INSUFFICIENT_PRIVILEGES'].'</span> ';
}

// go back to the correct backend-interface
if(!isset($_GET['reload_all']))
{
    switch(true)
    {
        case (isset($_POST["reload_templates"])):
            $backlink = "../templates/index.php".$leptoken;
            break;
        
        case (isset($_POST["reload_languages"])):
            $backlink = "../languages/index.php".$leptoken;
            break;
    }
}

if (!empty($error_msg))
{
    $error_msg = array_merge($error_msg, $msg);
    $admin->print_error( implode('<br />', $error_msg ), $backlink );
}
else
{
    // output success message
    $admin->print_success( implode('<br />', $msg ), $backlink );
}
				
