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

$admin = LEPTON_admin::getInstance('Pages', 'pages_add');
$database = LEPTON_database::getInstance();
LEPTON_core::getGlobal('MESSAGE');

$functions = [
	"save_filename",
	"get_page_details",
	"root_parent"
];
LEPTON_handle::register($functions);

// Get values
$title = LEPTON_core::getValue('title');

// Make sure that postet modulename contains only lowercases, numbers and "-" or "_".
$module = LEPTON_core::getValue('type','string_secure','post');

$iParentId =  LEPTON_core::getValue('parent','integer','post');
$aParentInfo = get_page_details($iParentId);

$visibility = LEPTON_core::getValue('visibility','string_secure','post');
if (!in_array($visibility, LEPTON_core::$aPageVisibility))
{
    $visibility = 'public';
}

$viewing_groups_post = $admin->getValue('viewing_groups', 'array', default: []);
$viewing_groups_post[] = 1;
sort($viewing_groups_post);
$viewing_groups = implode(",", $viewing_groups_post);

$admin_groups_post = $admin->getValue('admin_groups', 'array', default: []);
$admin_groups_post[] = 1;
sort($admin_groups_post);
$admin_groups = implode(",", $admin_groups_post);

if ($iParentId != 0) 
{
	if (!$admin->get_page_permission($iParentId,'admin'))
    {
        $admin->print_error($MESSAGE['PAGES_INSUFFICIENT_PERMISSIONS']." [1]");
    }
} 
elseif (!$admin->get_permission('pages_add_level_0','system'))
{
	$admin->print_error($MESSAGE['PAGES_INSUFFICIENT_PERMISSIONS']." [2]");
}

// Validate data
if (is_null($title) || str_starts_with($title, '.'))
{
	$admin->print_error($MESSAGE['PAGES_BLANK_PAGE_TITLE']);
}

// Check to see if page created has needed permissions
if(!in_array(1, $admin->getValue('groups_id', 'string', 'session',',')))
{
	$admin_perm_ok = false;
	foreach ($admin_groups as $adm_group)
    {
		if (in_array($adm_group, $admin->getValue('groups_id', 'string', 'session',',')))
        {
			$admin_perm_ok = true;
		}
	}
	
	if ($admin_perm_ok == false)
    {
		$admin->print_error($MESSAGE['PAGES_INSUFFICIENT_PERMISSIONS']." [3]");
	}
}



// Work-out what the link and page filename should be
if($iParentId == 0)
{
	$link = '/'.save_filename($title);
	// rename menu titles: index to prevent clashes with core file /pages/index.php
	if($link == '/index')
    {
		$link .= '_0';
		$filename = LEPTON_PATH .PAGES_DIRECTORY.$link.PAGE_EXTENSION;
	} 
	else 
	{
		$filename = LEPTON_PATH.PAGES_DIRECTORY.$link.PAGE_EXTENSION;
	}
} 
else 
{
	$sParentLink = $aParentInfo['link'];	
	
	if($sParentLink == '/') { $sParentLink = ''; }
	
	$link = $sParentLink.'/'.save_filename($title);
	$filename = LEPTON_PATH.PAGES_DIRECTORY.$link.PAGE_EXTENSION;
	
	LEPTON_core::make_dir(LEPTON_PATH.PAGES_DIRECTORY.'/'.$sParentLink);

	$source = ADMIN_PATH."/pages/master_index.php";
	copy($source, LEPTON_PATH.PAGES_DIRECTORY.'/'.$sParentLink."/index.php");
}

// Check if a page with same page filename exists
$get_same_page = $database->get_one("SELECT page_id FROM ".TABLE_PREFIX."pages WHERE link = '".$link."' ");
if (!is_null($get_same_page) || file_exists(LEPTON_PATH.PAGES_DIRECTORY.$link.PAGE_EXTENSION))
{
    $admin->print_error($MESSAGE['PAGES_PAGE_EXISTS']." [1]");
}

// Include the ordering class, use LEPTON_order
$order = LEPTON_order::getInstance(TABLE_PREFIX.'pages', 'position', 'page_id', 'parent');

// First clean order
$order->clean($iParentId);

// Get new order
$position = $order->get_new($iParentId);

// Work-out if the page parent (if selected) has a separate template or language to the default

$template = $aParentInfo['template'] ?? '' != '' ?  $aParentInfo['template'] : '';
$language = $aParentInfo['language'] ?? DEFAULT_LANGUAGE != DEFAULT_LANGUAGE ?  $aParentInfo['language'] : DEFAULT_LANGUAGE;

// Insert page into pages table
$fields = [
	'parent' 		=> $iParentId,
	'target'		=> $aParentInfo['target'] ?? '_top',
	'page_title'	=> $title,
	'menu_title'	=> $title,
	'template'		=> $template,
	'visibility'	=> $visibility,
	'position'		=> $position,
	'menu'			=> $aParentInfo['menu'] ?? 1,
	'language'		=> $language,
	'searching'		=> $aParentInfo['searching'] ?? 1,
	'modified_when'	=> time(),
	'modified_by'	=> LEPTON_core::getValue('USER_ID','integer','session'),
	'admin_groups'	=> $admin_groups,
	'viewing_groups' => $viewing_groups,
	'link'			=> $link,
	'description'	=> '',
	'keywords'		=> '',
	'page_trail'	=> ''   // Empty, as at this time we have no (page-)id!
];

$table = TABLE_PREFIX.'pages';
$database->build_and_execute(
	'insert',
	$table,
	$fields
);

// Get the page id
$page_id = $database->get_one("SELECT LAST_INSERT_ID() FROM ".$table);

if($iParentId != 0)
{
	$sParentPageTrail = $database->get_one("SELECT page_trail FROM ".$table." WHERE page_id = ".$iParentId);
	$aParentPageTrail = explode(',',$sParentPageTrail);
	$aParentPageTrail[] = $page_id;
	$sNewPageTrail = implode(',',$aParentPageTrail);
	
	// get root parent
	$iRootParent = $aParentPageTrail[0];
}
else
{
	$sNewPageTrail = $page_id;
	$iRootParent = $page_id;
}

// Update page with new level and link
$fields2 = [
	'root_parent'	=> $iRootParent,
	'level'			=> LEPTON_core::level_count($page_id),
	'link'			=> $link,
	'page_trail'	=> $sNewPageTrail	
];

$database->build_and_execute(
	'update',
	$table,
	$fields2,
	'page_id = '.$page_id
);

// Create a new file in the /pages dir
LEPTON_core::create_access_file($filename, $page_id, $level);

// add new section at position 1 to the new page
$iSectionPosition = 1;

// Add new record into the sections table
$aValuesForSections = [
	'page_id'	=> $page_id,
	'position'	=> $iSectionPosition,
	'module'	=> $module,
	'name'		=> 'no name',
	'block'		=> 1
];

$database->build_and_execute(
	'insert',
	TABLE_PREFIX.'sections',
	$aValuesForSections
);

// Get the section id
$section_id = $database->get_one("SELECT LAST_INSERT_ID() FROM ".TABLE_PREFIX.'sections');

// Call the "add.php" of the module.
LEPTON_handle::include_files ('/modules/'.$module.'/add.php');

$admin->print_success($MESSAGE['PAGES_ADDED'], ADMIN_URL.'/pages/modify.php?page_id='.$page_id);
