<?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-2022 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
 * @version         $Id: uninstall.php 1172 2011-10-04 15:26:26Z frankh $
 *
 */
 
// include class.secure.php to protect this file and the whole CMS!
if (defined('LEPTON_PATH')) {	
	include(LEPTON_PATH.'/framework/class.secure.php'); 
} else {
	$oneback = "../";
	$root = $oneback;
	$level = 1;
	while (($level < 10) && (!file_exists($root.'/framework/class.secure.php'))) {
		$root .= $oneback;
		$level += 1;
	}
	if (file_exists($root.'/framework/class.secure.php')) { 
		include($root.'/framework/class.secure.php'); 
	} else {
		trigger_error(sprintf("[ <b>%s</b> ] Can't include class.secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
	}
}
// end include class.secure.php

// Check if user selected template
if(!isset($_POST['template_id']) OR $_POST['template_id'] == "") {
	header("Location: index.php");
	exit(0);
} else {
	$template_id = intval($_POST['template_id']);
}

// Extra protection
if(trim($template_id) == '') {
	header("Location: index.php");
	exit(0);
}

$template_info = array();
$database->execute_query(
    "SELECT * FROM `".TABLE_PREFIX."addons` WHERE `addon_id`=".$template_id." AND `type`='template' ",
    true,
    $template_info,
    false
);

//  check for an entry - if not: exit.
if( 0 === count($template_info))
{
    header("Location: index.php");
	exit(0);
}
$file = $template_info['directory'];


$admin = new LEPTON_admin('Addons', 'templates_uninstall');

// Include the functions file
require_once(LEPTON_PATH.'/framework/summary.functions.php');

// Check if the template exists
if(!is_dir(LEPTON_PATH.'/templates/'.$file)) {
	$admin->print_error($MESSAGE['GENERIC_NOT_INSTALLED']);
}

if (!function_exists("replace_all")) 
{
	function replace_all ($aStr = "", $aArray = [] ) 
	{		
		foreach($aArray as $k=>$v)
		{   
		    $aStr = str_replace("{{".$k."}}", $v, $aStr);
		}
		return $aStr;
	}
}

/**
 *	Check if the template is the standard-template or still in use
 */
if (!isset($MESSAGE['GENERIC_CANNOT_UNINSTALL_IS_DEFAULT_TEMPLATE']) )
{
    $MESSAGE['GENERIC_CANNOT_UNINSTALL_IS_DEFAULT_TEMPLATE'] = "Can't uninstall this template <b>{{name}}</b> because it's the standardtemplate!";
}

// check whether the template is used as default theme
if($file == DEFAULT_THEME) {
	$temp = array ('name' => $file );
	$msg = replace_all( str_replace("template", "theme", $MESSAGE['GENERIC_CANNOT_UNINSTALL_IS_DEFAULT_TEMPLATE']), $temp );
	$admin->print_error( $msg );
}

if ($file == DEFAULT_TEMPLATE) {
	$temp = array ('name' => $file );
	$msg = replace_all( $MESSAGE['GENERIC_CANNOT_UNINSTALL_IS_DEFAULT_TEMPLATE'], $temp );
	$admin->print_error( $msg );

} else {
	
	/**
	 *	Check if the template is still in use by a page ...
	 */
	$aAllPages = array();
	$database->execute_query(
	    "SELECT `page_id`, `page_title` FROM `".TABLE_PREFIX."pages` WHERE `template`='".$file."' order by `page_title`",
	    true,
	    $aAllPages,
	    true
	);
	
	if (count($aAllPages) > 0)
	{
	    /**
		 *	Template is still in use, so we're collecting the page-titles
		 */
		
		/**
		 *	The base-message template-string for the top of the message
		 */
		if (!isset($MESSAGE['GENERIC_CANNOT_UNINSTALL_IN_USE_TMPL'] ) ) {
			$add = $info->numRows() == 1 ? "this page" : "these pages";
			$msg_template_str  = "<br /><br />{{type}} <b>{{type_name}}</b> could not be uninstalled because it is still in use by {{pages}}";
			$msg_template_str .= ":<br /><i>click for editing.</i><br /><br />";
		} else {
			$msg_template_str = $MESSAGE['GENERIC_CANNOT_UNINSTALL_IN_USE_TMPL'];
			$temp = explode(";",$MESSAGE['GENERIC_CANNOT_UNINSTALL_IN_USE_TMPL_PAGES']);
			$add = count($aAllPages) == 1 ? $temp[0] : $temp[1];
		}
		/**
		 *	The template-string for displaying the Page-Titles ... in this case as a link
		 */
		$page_template_str = "- <b><a href='../pages/settings.php?page_id={{id}}'>{{title}}</a></b><br />";
		
		$values = array ('type' => 'Template', 'type_name' => $file, 'pages' => $add);
		$msg = replace_all ( $msg_template_str,  $values );
		
		$page_names = "";
		
		foreach($aAllPages as $data)
		{
			$page_info = array(
				'id'	=> $data['page_id'], 
				'title' => $data['page_title']
			);
			
			$page_names .= replace_all ( $page_template_str, $page_info );
		}
		
		/**
         *	Printing out the error-message and die().
		 */
		$admin->print_error($MESSAGE['GENERIC_CANNOT_UNINSTALL_IN_USE'].$msg.$page_names);
	}
}

// Check if we have permissions on the directory
if(!is_writable(LEPTON_PATH.'/templates/'.$file)) {
	$admin->print_error($MESSAGE['GENERIC_CANNOT_UNINSTALL'].LEPTON_PATH.'/templates/'.$file);
}

// Try to delete the template dir
if(!rm_full_dir(LEPTON_PATH.'/templates/'.$file)) {
	$admin->print_error($MESSAGE['GENERIC_CANNOT_UNINSTALL']);
} else {
	// Remove entry from DB
	$database->simple_query("DELETE FROM `".TABLE_PREFIX."addons` WHERE `directory` = '".$file."' AND type = 'template'");
}

// Update pages that use this template with default template
$database->simple_query("UPDATE `".TABLE_PREFIX."pages` SET template = '".DEFAULT_TEMPLATE."' WHERE `template` = '$file'");

/**
 * Update the template-permissions inside groups
 *
 */ 
$aAllGroups = array();
$database->execute_query(
    "SELECT `group_id`,`template_permissions` FROM `".TABLE_PREFIX."groups` WHERE `template_permissions` LIKE '%".$file."%'",
    true,
    $aAllGroups,
    true
);

foreach($aAllGroups as $group) {
    $aTemp = explode(",", $group['template_permissions']);
    $aNew = array();
    foreach($aTemp as $sTempName)
    {
        if($sTempName != $file) $aNew[] = $sTempName;
    }
    $aUpdateFields = array(
        'template_permissions'  => implode(",", $aNew)
    );
    $database->build_and_execute(
        'update',
        TABLE_PREFIX."groups",
        $aUpdateFields,
        "`group_id`=".$group['group_id']
    );
}

// Print success message
$admin->print_success($MESSAGE['GENERIC_UNINSTALLED']);

// Print admin footer
$admin->print_footer();
