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

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

/** ****************************
 *	Input validation
 * ***************************** */
$oREQUEST = LEPTON_request::getInstance();

	// input validation on $_GET
	$input_fields = array (
		  'page_id'		=> array ('type' => 'integer+', 'default' => -1)
		, 'section_id'	=> array ('type' => 'integer+', 'default' => -1)
	);
	$valid_fields = $oREQUEST->testGetValues($input_fields);
	$page_id	= intval($valid_fields['page_id']);
	$section_mod= intval($valid_fields['section_id']);

// Check page id
/**
 *	If the page_id is not set we try to get a valid one from the db; the first inside the tree
 *	M.f.i.: Aldus - 27.11.2016
 */
$display_details = true;
if ( $page_id < 0 )
{
	$temp = $database->get_one( "SELECT `page_id` FROM `".TABLE_PREFIX."pages` order by `position` LIMIT 1" );
	if ( is_numeric($temp))
	{
		$page_id = $temp;
	} else {
		$page_id = NULL;
		$display_details = false;
	}
}

// get TWIG engine
$oTWIG = lib_twig_box::getInstance();

// Create new LEPTON_admin object
$admin = LEPTON_admin::getInstance();

// include twig globals
if ( file_exists(THEME_PATH."/globals/lte_globals.php"))
{
	require_once(THEME_PATH."/globals/lte_globals.php");
}

if ( true === $display_details )
{
	// Get permissions
	if ( ! $admin->get_page_permission($page_id,'admin'))
	{
		$admin->print_error($MESSAGE['PAGES_INSUFFICIENT_PERMISSIONS']);
	}

	// Get page details
	$current_page = $admin->get_page_details($page_id);

	// Get display name of person who last modified the page
	$user = $admin->get_user_details($current_page['modified_by']);

	// Convert the unix ts for modified_when to human a readable form
	$modified_ts = ($current_page['modified_when'] != 0)
		? $modified_ts = date(TIME_FORMAT.', '.DATE_FORMAT, $current_page['modified_when'])
		: 'Unknown' ;
}

//	Get all pages as (array-) tree
if ( ! function_exists("page_tree"))	{ require_once( LEPTON_PATH."/framework/functions/function.page_tree.php"); }
$all_pages = array();
$fields = array('page_id','page_title','menu_title','parent','position','visibility','link');
page_tree( 0, $all_pages, $fields );

// get template used for the displayed page (for displaying block details)
if ( SECTION_BLOCKS )
{
	$result = $database->get_one("SELECT `template` from `" . TABLE_PREFIX . "pages` WHERE `page_id` = '".$page_id."' ");
	if ($result != NULL) {
		$page_template = ($result == '') ? DEFAULT_TEMPLATE : $result;
		// include template info file if exists
		if (file_exists(LEPTON_PATH . '/templates/' . $page_template . '/info.php'))
		{
			include_once(LEPTON_PATH . '/templates/' . $page_template . '/info.php');
		}
	}
}

// check for admin rights
$temp = $admin->get_groups_id();
if(!is_array($temp))
{
	$bHasAdminPrivilegs = ($temp == 1) ? true : false;
} else {
	$bHasAdminPrivilegs = ( true == in_array( 1, $temp ) ) ? true : false;
}

// Get all sections for this page
$all_sections = array();
$database->execute_query(
	'SELECT `section_id`, `module`, `block`, `name` FROM `'.TABLE_PREFIX.'sections` WHERE `page_id` = '.$page_id.' ORDER BY `position` ASC',
	true,
	$all_sections,
	true
);

// build page detail
$all_section_ids = array();
if ( count($all_sections) > 0 )
{

	foreach( $all_sections as &$section)
	{
		global $section_id;
		$section_id = $section['section_id'];

		// collect section_id
		$all_section_ids[] = $section_id;

		// Have permission?
		$module = $section['module'];
		if( (true == $bHasAdminPrivilegs) || (is_numeric(array_search($module, $_SESSION['MODULE_PERMISSIONS']))))
		{
			// Include the modules editing script if it exists
			if ( file_exists(LEPTON_PATH.'/modules/'.$module.'/modify.php'))
			{
				if (isset($block[$section['block']]) && trim(strip_tags(($block[$section['block']]))) != '')
				{
					$section['block_name'] = htmlentities(strip_tags($block[$section['block']]));
				} else
				{
					if ($section['block'] == 1)
					{
						$section['block_name'] = $TEXT['MAIN'];
					} else
					{
						$section['block_name'] = '#' . (int) $section['block'];
					}
				}

				ob_start();
				require(LEPTON_PATH.'/modules/'.$module.'/modify.php');
				$section['content'] = ob_get_clean();
			}
		}
	}

	//  handle last edit section
	if (( $section_mod >= 0 ) && ( in_array( $section_mod, $all_section_ids )))
	{
		// use the section id passed from section maintenance
		$_SESSION['last_edit_section'] = $section_mod;
	}
	elseif (( ! isset($_SESSION['last_edit_section']) ) || ( ! in_array( $_SESSION['last_edit_section'], $all_section_ids )))
	{
		// last section is not set or invalid: use first section
		$_SESSION['last_edit_section'] = $all_section_ids[0];
	}

} else {
	//  No sections on this page
	$_SESSION['last_edit_section'] = 0;
}


/** ****************************
 *	Collect vars
 * ***************************** */
$page_values = array(
	 'page'					=> $current_page
	,'MODIFIED_BY'			=> $user['display_name']
	,'MODIFIED_BY_USERNAME' => $user['username']
	,'MODIFIED_WHEN'		=> $modified_ts
	,'SEC_ANCHOR'			=> SEC_ANCHOR
	,'MANAGE_SECTIONS'		=> MANAGE_SECTIONS
	,'leptoken'				=> get_leptoken()
	,'last_edit_section'	=> $_SESSION['last_edit_section']
	,'allowedPageSettings'	=> ( (false == $bHasAdminPrivilegs) ? LEPTON_admin::getUserPermission("page_settings") : true )
	,'all_pages'			=> $all_pages
	,'all_sections'			=> $all_sections
	,'display_details'		=> $display_details
);

/** ****************************
 *	TALGOS enhancement
 * ***************************** */
$oTALG = talgos::getInstance();
$page_values['oTALG'] = $oTALG;

/** ****************************
 *	Render page
 * ***************************** */
$oTWIG->registerPath( THEME_PATH."theme","pages_modify" );
echo $oTWIG->render(
	"@theme/pages_modify.lte",
	$page_values
);

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

?>