<?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-2021 LEPTON Project 
 *  @license        GNU General Public License
 *  @license terms  see info.php of this module
 *  @platform       see info.php of this module
 * 
 */

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

// Get id
if(!isset($_POST['post_id']) OR !is_numeric($_POST['post_id']))
{
	header("Location: ".ADMIN_URL."/pages/index.php");
	exit( 0 );
}
else
{
	$id = $_POST['post_id'];
	$post_id = $id;
	if(WYSIWYG_HISTORY == 1)
	{
		$_POST['history_post_id'] = $post_id;
		$_POST['history_user'] = $_POST['user_id'];
		$_POST['history_max'] = MAX_WYSIWYG_HISTORY;
		$_POST['history_time'] = date("Y-m-d H:i:s",time());
		
	}
}

function create_file($filename, $filetime=NULL )
{
    global $page_id, $section_id, $post_id;

	// We need to create a new file
	// First, delete old file if it exists
	if(file_exists(LEPTON_PATH.PAGES_DIRECTORY.$filename.PAGE_EXTENSION))
    {
        $filetime = isset($filetime) ? $filetime :  filemtime($filename);
		unlink(LEPTON_PATH.PAGES_DIRECTORY.$filename.PAGE_EXTENSION);
	}
    else {
        $filetime = isset($filetime) ? $filetime : time();
    }
	// The depth of the page directory in the directory hierarchy
	// '/pages' is at depth 1
	$pages_dir_depth = count(explode('/',PAGES_DIRECTORY))-1;
	// Work-out how many ../'s we need to get to the index page
	$index_location = '../';
	for($i = 0; $i < $pages_dir_depth; $i++)
    {
		$index_location .= '../';
	}

	// Write to the filename
	$content = ''.
'<?php
$page_id = '.$page_id.';
$section_id = '.$section_id.';
$post_id = '.$post_id.';
define("POST_SECTION", $section_id);
define("POST_ID", $post_id);
require("'.$index_location.'/index.php");
?>';
	if($handle = fopen($filename, 'w+'))
    {
    	fwrite($handle, $content);
    	fclose($handle);
        if($filetime)
        {
        touch($filename, $filetime);
        }
    	change_mode($filename);
    }
}

// Include admin wrapper script
$update_when_modified = true; // Tells script to update when this page was last updated
require(LEPTON_PATH.'/modules/admin.php');

// Validate all fields
if($admin->get_post('title') == '' AND $admin->get_post('url') == '')
{
	$admin->print_error($MESSAGE['GENERIC_FILL_IN_ALL'], LEPTON_URL.'/modules/news/modify_post.php?page_id='.$page_id.'&section_id='.$section_id.'&post_id='.$id);
}
else
{
	// Aldus 2020-02-05 :: Lepton V
	$aLookUpFields = [
	    "title"         => ["type" => "string_chars",        "default" => ""],
	    "short"         => ["type" => "string_chars",        "default" => ""],
	    "long"          => ["type" => "string_chars",        "default" => ""],
	    "commenting"    => ["type" => "string_allowed",        "default" => "none"],   // 'none', 'public' or 'private'
	    "active"        => ["type" => "integer",    "default" => 0],
	    "link"          => ["type" => "str",        "default" => ""],
	    "group"         => ["type" => "integer",    "default" => 0],
	    "published_when"    => ["type" => "string_clean",    "default" => "0"],   // not "type" => "date"!
	    "published_until"   => ["type" => "string_clean",    "default" => "0"],    // not "type" => "date"!
		"history_post_id"   => ["type" => "integer",    "default" => -1],
		"history_user"	    => ["type" => "integer",    "default" => -1],
		"history_max"	    => ["type" => "integer",    "default" => MAX_WYSIWYG_HISTORY],
		"history_time"	    => ["type" => "string",    "default" => '2000-01-01 12:00:00'],
		"history_type"	    => ["type" => "integer",    "default" => -1],
		"history_comment"   => ["type" => "string_chars",    "default" => ""]		
	];
	
	$aPostedFields = LEPTON_request::getInstance()->testPostValues( $aLookUpFields );
	
	extract($aPostedFields); 

	if ($history_type == -1)
	{
		$history_post_id = -1;
		$history_user = -1;
		$history_max = -1;
		$history_comment = '';
	}
	
	$old_link = $link; // $admin->get_post_escaped('link');
	$group_id = $group; // $admin->get_post_escaped('group');
}

if( ( $old_link === null ) || ( $old_link == "" ) ) $old_link = "/posts/";


// Get page link URL
$page = array();
$database->execute_query(
	"SELECT level, link FROM ".TABLE_PREFIX."pages WHERE page_id = ".$page_id ,
	true,
	$page,
	false
);
$page_level = $page['level'];
$page_link = $page['link'];

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

// Work-out what the link should be
$post_link = '/posts/'.save_filename($title).PAGE_SPACER.$post_id;

// Make sure the post link is set and exists
// Make news post access files dir
make_dir(LEPTON_PATH.PAGES_DIRECTORY.'/posts/');
$file_create_time = '';
if(!is_writable(LEPTON_PATH.PAGES_DIRECTORY.'/posts/'))
{
	$admin->print_error($MESSAGE['PAGES_CANNOT_CREATE_ACCESS_FILE']);
}
elseif(($old_link != $post_link) OR !file_exists(LEPTON_PATH.PAGES_DIRECTORY.$post_link.PAGE_EXTENSION))
{
	// We need to create a new file
	// First, delete old file if it exists
	if(file_exists(LEPTON_PATH.PAGES_DIRECTORY.$old_link.PAGE_EXTENSION))
    {
        $file_create_time = filemtime(LEPTON_PATH.PAGES_DIRECTORY.$old_link.PAGE_EXTENSION);
		unlink(LEPTON_PATH.PAGES_DIRECTORY.$old_link.PAGE_EXTENSION);
	}

    // Specify the filename
    $filename = LEPTON_PATH.PAGES_DIRECTORY.'/'.$post_link.PAGE_EXTENSION;
    create_file($filename, $file_create_time);
}

/**
 *  Get instance from the LEPTON dateTools to transform date to timestamp string
 */
$oDateTools         = lib_lepton::getToolInstance("datetools");
$published_when     = $oDateTools->calendarToTimestamp( $published_when );
$published_until    = $oDateTools->calendarToTimestamp( $published_until );
//die(LEPTON_tools::display($published_when,'pre','ui message'));
if($published_when == 0)
{
	$published_when = $database->get_one("SELECT `published_when`  FROM `".TABLE_PREFIX."mod_news_posts` WHERE `post_id` = ".$post_id );
}

if($published_until == '')
{
    $published_until = 0;
}

// Update row
$fields = array(
	'group_id' 	=> $group_id,
	'title' 	=> $title,
	'link'		=> $post_link,
	'content_short'	=> $short,
	'content_long'	=> $long,
	'commenting'	=> $commenting,
	'active'		=> $active,
	'published_when'=> $published_when,
	'published_until'=> $published_until,
	'posted_when'	=> time(),
	'posted_by'		=> $admin->get_user_id(),
	'history_comment' => $history_comment
	);
//die(LEPTON_tools::display($fields,'pre','ui message'));
$database->build_and_execute(
	'UPDATE',
	TABLE_PREFIX."mod_news_posts",
	$fields,
	"post_id = ".$post_id
);

// Save existing post for history
if ($history_type != -1)
{
	// History ...
	$fields["history_post_id"] = $history_post_id;
    $fields["history_max"]     = $history_max;
	$fields["history_user"]    = $history_user;
	$fields["history_time"]    = $history_time;	
    $fields["history_type"]    = $history_type;
    $fields["history_comment"] = $history_comment;
	
	if ($history_type == 1)
	{
		// make sure that there is only one working copy!
		$wc_exist = $database->get_one("SELECT post_id FROM ".TABLE_PREFIX."mod_news_posts WHERE history_type = 1 AND history_post_id = ".$post_id);
		if($wc_exist != NULL)
		{
			$database->build_and_execute(
				'update',
				TABLE_PREFIX."mod_news_posts",
				$fields,
				"post_id = ".$wc_exist
			);			
		}
		else
		{
			$database->build_and_execute(
				"insert",
				TABLE_PREFIX."mod_news_posts",
				$fields
			);				
		}
		
	}
	else
	{
		$database->build_and_execute(
			"insert",
			TABLE_PREFIX."mod_news_posts",
			$fields
		);
		
		/**
		 *  [3] Any "old" one to delete? See: MAX_WYSIWYG_HISTORY
		 */
		$aTempAllHistories = array();
		$database->execute_query(
		    "SELECT `post_id` FROM `".TABLE_PREFIX."mod_news_posts` WHERE `history_post_id` = ".$post_id." AND `history_type` = 2 ORDER BY `history_time` DESC",
		    true,
		    $aTempAllHistories,
		    true
		);

		// 3.1
		$iNumOfHistories = count($aTempAllHistories);
		
		// 3.2
		if( $iNumOfHistories > MAX_WYSIWYG_HISTORY)
		{
		    // 3.2.1
		    for($i = MAX_WYSIWYG_HISTORY; $i < ($iNumOfHistories-1); $i++)
		    {
		        $database->simple_query("DELETE FROM `".TABLE_PREFIX."mod_news_posts` WHERE `post_id`=".$aTempAllHistories[ $i ][ 'post_id' ] );
		    }
		}
	}

}

//$iLastInsertID = $database->get_one("SELECT LAST_INSERT_ID()");
//$database->simple_query("UPDATE `".TABLE_PREFIX."mod_news_posts` SET `history_id`='".$post_id."_".$iLastInsertID."' WHERE `post_id`=".$iLastInsertID );

// Check if the user uploaded an image or wants to delete one
if(isset($_FILES['newspic']['tmp_name']) AND $_FILES['newspic']['tmp_name'] != '')
{
	// Look for the target folder:
	$sTargetDirectory = LEPTON_PATH.MEDIA_DIRECTORY.'/newspics';
	if(!file_exists($sTargetDirectory))
	{
		make_dir($sTargetDirectory);
	}
	
	// Get real filename and set new filename
	$filename = $_FILES['newspic']['name'];
	
	// Aldus - 24.09.2019
	$aTempTerms = explode(".", $filename);
	$sMimeType = strtolower( array_pop($aTempTerms) );
	
	$new_filename = $sTargetDirectory.'/image'.$post_id.'.'.$sMimeType;
	$new_filename = str_replace("/", DIRECTORY_SEPARATOR, $new_filename);
		
	// Make sure the image is a jpg file
	$file4=substr($filename, -4, 4);
	
	if(($file4 != '.jpg')and($file4 != '.JPG')and($file4 != '.png')and($file4 != '.PNG') and ($file4 !='jpeg') and ($file4 != 'JPEG'))
    {
		$admin->print_error($MESSAGE['GENERIC_FILE_TYPE'].' JPG (JPEG) or PNG a');
	} elseif(
	    (($_FILES['newspic']['type']) != 'image/jpeg' AND mime_content_type($_FILES['newspic']['tmp_name']) != 'image/jpg')
	        and
	    (($_FILES['newspic']['type']) != 'image/png' AND mime_content_type($_FILES['newspic']['tmp_name']) != 'image/png')
	    )
	    {
		    $admin->print_error($MESSAGE['GENERIC_FILE_TYPE'].' JPG (JPEG) or PNG b');
	}
  
	// Upload image
	move_uploaded_file($_FILES['newspic']['tmp_name'], $new_filename);
	// Check if we need to create a thumb
	$resize = $database->get_one("SELECT resize FROM ".TABLE_PREFIX."mod_news_settings WHERE section_id = ".$section_id );
	if($resize != 0)
    {
		// Resize the image
		$thumb_location = LEPTON_PATH.MEDIA_DIRECTORY.'/newspics/thumb'.$post_id.'.'.$sMimeType;
		if(make_thumb($new_filename, $thumb_location, $resize))
        {
			// Delete the actual image and replace with the resized version
			unlink($new_filename);
			rename($thumb_location, $new_filename);
		}
	}
}

if(isset($_POST['delete_image']) AND $_POST['delete_image'] != '')
{
	$aTempList = ["jpg", "jpeg", "png", "gif"];
	foreach($aTempList as &$sFileType)
	{
	    // Try unlinking image
	    $sTempFilePath = LEPTON_PATH.MEDIA_DIRECTORY.'/newspics/image'.$post_id.'.'.$sFileType;
	    
	    if(file_exists($sTempFilePath))
        {
		    unlink($sTempFilePath);
	    }
	}
}

// Check if there is a db error, otherwise say successful
if($database->is_error())
{
	$admin->print_error($database->get_error(), LEPTON_URL.'/modules/news/modify_post.php?page_id='.$page_id.'&section_id='.$section_id.'&post_id='.$admin->getIDKEY($id));
}
else
{
	$admin->print_success($TEXT['SUCCESS'], ADMIN_URL.'/pages/modify.php?page_id='.$page_id);
}

