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

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


// 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 &$sectionRef)
	{
		global $section_id;
		$section_id = $sectionRef['section_id'];

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

		// Have permission?
		$module = $sectionRef['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[$sectionRef['block']]) && trim(strip_tags(($block[$sectionRef['block']]))) != '')
				{
					$sectionRef['block_name'] = htmlentities(strip_tags($block[$sectionRef['block']]));
				} else
				{
					if ($sectionRef['block'] == 1)
					{
						$sectionRef['block_name'] = $TEXT['MAIN'];
					} else
					{
						$sectionRef['block_name'] = '#' . (int) $sectionRef['block'];
					}
				}

				ob_start();
				require(LEPTON_PATH.'/modules/'.$module.'/modify.php');
				$sectionRef['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,
    'permissions'           => [
            'p_page_modify' => ($admin->getUserPermission("pages_modify") ? 1 : 0) ,
            'p_page_delete' => ($admin->getUserPermission("pages_delete") ? 1 : 0) ,
            'p_page_add'    => ($admin->getUserPermission("pages_add")    ? 1 : 0)
        ]
);

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

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

?>