<?php

/**
 * This file is part of an ADDON for use with LEPTON Core.
 * This ADDON is released under the GNU GPL.
 * Additional license terms can be seen in the info.php of this module.
 *
 * @module          wysiwyg
 * @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 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

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

//die(LEPTON_tools::display($_POST,'pre','ui blue message'));
// Check if history is enabled
if(true == WYSIWYG_HISTORY)
{
	//	Update the mod_wysiwygs table with the contents
	if(isset($_POST['content'.$section_id]))
	{
		$_POST['content'] = str_replace("\\\$", "\$", $_POST['content'.$section_id]);

		// Searching in $text will be much easier this way
		$_POST['text'] = $_POST['content'];

		$oREQUEST = LEPTON_request::getInstance();	
		
		$_POST['last_version'] = time();		
		$_POST['content_comment'] = $_POST['comment'];
		$_POST['hist_autosave'] = 0;

		if($_POST['use_workingcopy'] == 1)  // save as working copy
		{	
			// update wysiwyg table
			$_POST['user_id_working'] = $_POST['user_id'];
			$_POST['working_content'] = str_replace("\\\$", "\$", $_POST['content'.$section_id]);
			$_POST['working_content_comment'] = $_POST['comment'];
			
			$all_names = array (
				'use_workingcopy'	=> array ('type' => 'int', 'default' => "1"),
				'user_id_working'	=> array ('type' => 'int', 'default' => "-1"),
				'working_content'	=> array ('type' => 'string_chars', 'default' => ""),
				'working_content_comment'	=> array ('type' => 'string_allowed', 'default' => "", 'range' => array('h1','h2','h3'))
			);

			$all_values = $oREQUEST->testPostValues($all_names);	
			
			$table = TABLE_PREFIX."mod_wysiwyg";
			$database->build_and_execute(
				'UPDATE', 
				$table, 
				$all_values,
				"section_id = ".$section_id
			);			
		}
		else
		{
			// save as history and save current content in history before it is overwritten
			if($_POST['use_workingcopy'] == 2 )
			{
				$check = array();
				$database->execute_query(
					"SELECT * FROM ".TABLE_PREFIX."mod_wysiwyg_history WHERE section_id = '".$_POST['section_id']."' ORDER BY version ASC",
					true,
					$check,
					true
				);
			
				
				if(count($check) == MAX_WYSIWYG_HISTORY )
				{
					// delete first in history (oldest entry) and insert a new one
					$database->simple_query("DELETE FROM ".TABLE_PREFIX."mod_wysiwyg_history WHERE section_id= ".$_POST['section_id']." ORDER BY version ASC limit 1");
					$database->simple_query("INSERT INTO ".TABLE_PREFIX."mod_wysiwyg_history (id, section_id, comment, content, text) VALUES (NULL, ".$_POST['section_id'].",'','','') ");
				}

				if(count($check) < MAX_WYSIWYG_HISTORY )
				{
					$database->simple_query("INSERT INTO ".TABLE_PREFIX."mod_wysiwyg_history (id, section_id, comment, content, text) VALUES (NULL, ".$_POST['section_id'].",'','','') ");
				}				

				// get last inserted id
				$new_insert = $database->get_one("SELECT LAST_INSERT_ID() FROM ".TABLE_PREFIX."mod_wysiwyg_history ");
			
				// get "old" content of current section
				$current_section = array();
				$database->execute_query(
					"SELECT * FROM ".TABLE_PREFIX."mod_wysiwyg WHERE section_id = '".$_POST['section_id']."' ",
					true,
					$current_section,
					false
				);

				$all_values = array (
                    'version'   => $current_section['last_version'],
                    'autosaved' => $current_section['hist_autosave'],
                    'date'      => time(),
                    'user_id'   => $current_section['user_id'],
                    'user_id_hist' => $_SESSION['USER_ID'],
                    'comment'   => $current_section['content_comment'],
                    'content'   => $current_section['content'],
                    'text'      => $current_section['text']
				);

				$database->build_and_execute(
					'UPDATE', 
					TABLE_PREFIX."mod_wysiwyg_history", 
					$all_values,
					"id = ".$new_insert
				);
				
				$_POST['hist_autosave'] == 1;
				
				$all_names = array (
					'content'           => array ('type' => 'string_chars', 'default' => ""),
					'text'              => array ('type' => 'string_chars', 'default' => ""),
					'max_history'		=> array ('type' => 'int',          'default' => ""),
					'content_comment'	=> array ('type' => 'string_allowed', 'default' => "", 'range' => array('h1','h2','h3')),
					'hist_autosave'     => array ('type' => 'int',          'default' => "0"),
					'last_version'      => array ('type' => 'int',          'default' => "0"),
					'user_id'           => array ('type' => 'int',          'default' => "-1"),
				
				);					

			}		// end $_POST['hist_autosave'] == 1
			else
			{
				// save data only, no history
				$all_names = array (
					'content'           => array ('type' => 'string_chars',     'default' => ""),
					'text'              => array ('type' => 'string_chars',     'default' => ""),
					'max_history'		=> array ('type' => 'int',              'default' => ""),
					'content_comment'	=> array ('type' => 'string_allowed',   'default' => "", 'range' => array('h1','h2','h3')),
					'hist_autosave'	    => array ('type' => 'int',              'default' => "0"),
					'last_version'	    => array ('type' => 'int',              'default' => "0"),
					'user_id'	        => array ('type' => 'int',              'default' => "-1"),
				
				);			
			}			
		
			$all_values = $oREQUEST->testPostValues($all_names);	
			
			$table = TABLE_PREFIX."mod_wysiwyg";
			$database->build_and_execute(
				'UPDATE', 
				$table, 
				$all_values,
				"section_id = ".$section_id
			);
		}
	}
}
else
{
	//	Update the mod_wysiwygs table with the contents WITHOUT HISTORY
	if(isset($_POST['content'.$section_id]))
	{
		$_POST['content'] = str_replace("\\\$", "\$", $_POST['content'.$section_id]);

		// Searching in $text will be much easier this way
        $_POST['text'] = $_POST['content'];

		$oREQUEST = LEPTON_request::getInstance();	
		
		$all_names = array (
			'content'	=> array ('type' => 'string_chars', 'default' => ""),
			'text'		=> array ('type' => 'string_chars', 'default' => "")
		);		

		$all_values = $oREQUEST->testPostValues($all_names);	
		
		$table = TABLE_PREFIX."mod_wysiwyg";
		$database->build_and_execute(
			'UPDATE', 
			$table, 
			$all_values,
			"section_id = ".$section_id
		);	
	}
}

//  Keep in mind that the "print_success" (class-)method also echos the footer!
$redirect = ADMIN_URL.'/pages/modify.php?page_id='.$page_id.'#'.SEC_ANCHOR.$section_id;
$admin->print_success($MESSAGE['PAGES_SAVED'], $redirect );

