<?php

/**
 *  @module         news
 *  @version        see info.php of this module
 *  @author         Ryan Djurovich, Rob Smith, Dietrich Roland Pehlke, Christian M. Stefan (Stefek), Jurgen Nijhuis (Argos), LEPTON Project
 *  @copyright      2004-2010 Ryan Djurovich, Rob Smith, Dietrich Roland Pehlke, Christian M. Stefan (Stefek), Jurgen Nijhuis (Argos) 
 *  @copyright      2010-2026 LEPTON Project 
 *  @license        GNU General Public License
 *  @license terms  see info.php of this module
 *  @platform       see info.php of this module
 * 
 */

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


// Get id
if(!isset($_GET['post_id']) || !is_numeric($_GET['post_id'])) 
{
	header("Location: ".ADMIN_URL."/pages/index.php");
	exit(0);
} 
else 
{
	$post_id = intval($_GET['post_id']);
}

// Include admin wrapper script
require(LEPTON_PATH.'/modules/admin.php');
$oNP = news::getInstance();

// Get header and footer
$current_content = [];
$query_content = $database->execute_query(
	"SELECT * FROM `".TABLE_PREFIX."mod_news_posts` WHERE `post_id` = ".$post_id,
	true,
	$current_content,
	false
);


//  aldus - 2021-06-18
news::cleanUpString( $current_content['title'] );

$id_list=["short","long"];
LEPTON_handle::register('display_wysiwyg_editor');

$use_images = TRUE;

// Get the groups for this page/section
$groups = [];
$database->execute_query(
	"SELECT group_id, title FROM ".TABLE_PREFIX."mod_news_groups WHERE section_id = ".$section_id." ORDER BY position ASC",
	true,
	$groups,
	true
);

foreach($groups as &$ref) {
	$ref['selected'] = ($ref['group_id'] == $current_content['group_id'])
		? "selected='selected'"
		: ""
		;
}

// Get the comments for this post
$comments = [];
$database->execute_query(
	"SELECT * FROM ".TABLE_PREFIX."mod_news_comments WHERE section_id = ".$section_id." AND post_id = ".$post_id." ORDER BY commented_when DESC",
	true,
	$comments,
	true
);


// Here we go
$bFileExists = false;
$aMimetypes = LEPTON_core::imageTypesAllowed();
$sImageFilePath = "";
foreach($aMimetypes as &$sFiletype)
{
    $sImageFilePath = MEDIA_DIRECTORY.'/newspics/image'.$post_id.'.'.$sFiletype;
    if(file_exists(LEPTON_PATH.$sImageFilePath))
    {
        $bFileExists = true;
        $sImageFilePath = LEPTON_URL.$sImageFilePath;
        break;
    }
}
//  Get user date format here.
$sTempDateFormat = $database->get_one("SELECT `date_format` FROM `".TABLE_PREFIX."users` WHERE `user_id`=".$_SESSION["USER_ID"]);
if ((NULL != $sTempDateFormat ) && (strlen($sTempDateFormat) > 0))
{
    // keep it as it is
} 
else 
{
    // use the currend date_format setting
    $sTempDateFormat = DATE_FORMAT;
}

$oLEPTON_DATE = LEPTON_date::getInstance();
$current_content['published_when_formated'] = $oLEPTON_DATE->formatWithMySQL($sTempDateFormat, $current_content['published_when']);
$current_content['published_until_formated'] = $oLEPTON_DATE->formatWithMySQL($sTempDateFormat, $current_content['published_until']);

if (str_contains($sTempDateFormat, "S"))
{
    // 1
    $patterns = [
        "/([0-9]{1,2})th/i",
        "/([0-9]{1,2})rd/i",
        "/([0-9]{1,2})st/i",
    ];

    $current_content['published_when_formated'] = preg_replace(
            $patterns,
            "$1".(LANGUAGE == "NL" ? "" : "."),
            $current_content['published_when_formated']
    );
    $current_content['published_until_formated'] = preg_replace(
            $patterns,
            "$1".(LANGUAGE == "NL" ? "" : "."),
            $current_content['published_until_formated']
    );
}
// check for WC
$wc_exist = $database->get_one("SELECT post_id FROM ".TABLE_PREFIX."mod_news_posts WHERE history_type = 1 AND history_post_id = ".$post_id);

// see status of settings commenting
$settings_commenting = $database->get_one("SELECT commenting FROM ".TABLE_PREFIX."mod_news_settings WHERE section_id = ".$section_id );

$sDatepickerFormat = LEPTON_date::getInstance()->formatToDatepicker($sTempDateFormat);
if (LANGUAGE == "NL")
{
    if (str_contains($sTempDateFormat, "S"))
    {
        $sDatepickerFormat = str_replace(".", "", $sDatepickerFormat);
    }    
}

$form_values = array(
    'MEDIA_DIRECTORY'   => MEDIA_DIRECTORY,
	'WYSIWYG_HISTORY'   => WYSIWYG_HISTORY,
	'DEFAULT_LANGUAGE'  => LANGUAGE,
	'oNP' 				=> $oNP,
	'user_id'           => $_SESSION['USER_ID'],
    'page_id'           => $page_id,
    'section_id'        => $section_id,
    'post_id'           => $post_id,
	'wc_exist'          => $wc_exist,
    'link'              => $current_content['link'],
    'title'             => $current_content['title'],
    'groups'            => $groups,
    'commenting'        => $current_content['commenting'],
    'active'            => lib_fomantic::BuildCheckbox(
            "active",   // name
            "active",   // html-id
            $TEXT["ACTIVE"], // label
            1,          // value
            $current_content['active'],   // state
            ""          // css class?
        ),
    'published_when'    => $current_content['published_when'],
    'published_until'   => $current_content['published_until'],
    'published_when_formated'    => $current_content['published_when_formated'],
    'published_until_formated'   => $current_content['published_until_formated'],

    'use_images'        => $use_images,

    'got_image'         => ($bFileExists == true) ? 1 : 0,
    'image_file_url'    => $sImageFilePath,
    
    'show_wysiwyg_editor_short' => display_wysiwyg_editor('short','short_id', $current_content['content_short'],100,200, false),
    'show_wysiwyg_editor_long'  => display_wysiwyg_editor('long','long_id', $current_content['content_long'],100,550, false),    
    'num_of_comments'   => count($comments),
	'settings_commenting'   => $settings_commenting,	
    'comments'          => $comments,
    'row'               => 'a',
    'DATE_FORMAT'       => $sTempDateFormat,
    'DATEPICKER_FORMAT' => $sDatepickerFormat,
    'leptoken'          => get_leptoken()
);

$_SESSION['last_edit_section'] = $section_id;

$oTWIG = lib_twig_box::getInstance();
$oTWIG->registerModule("news");

echo $oTWIG->render(
	'@news/modify_post.lte',
	$form_values
);

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