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

class wysiwyg extends LEPTON_abstract
{
	public $database = 0;
	public $admin = 0;
    public $wysiwyg_editor_loaded = false;
    public $got_wysiwyg_editor = true;
	public $users = array();
	public $action_url = LEPTON_URL.'/backend/pages/modify.php?page_id=';
    
	// Own instance for this class!
    static $instance;
	
    /**
     *  Holds a linear list with all section-id with type "wysiwyg" of the currend page.
     *  @var array 
     */
    public $allSectionIDs = array();
    
    public function initialize() 
    {
    
        if (!defined('WYSIWYG_EDITOR') OR WYSIWYG_EDITOR=="none" OR !file_exists(LEPTON_PATH.'/modules/'.WYSIWYG_EDITOR.'/include.php'))
        {
            $this->got_wysiwyg_editor = false;
            
            if(!function_exists("show_wysiwyg_editor"))
            {
                function show_wysiwyg_editor( $name, $id, $content, $width, $height, $promt=true )
                {
                    $sHTML = '<textarea name="'.$name.'" id="'.$id.'" style="width: '.$width.'; height: '.$height.';">'.$content.'</textarea>';
                
                    if( true === $promt)
                    {
                        echo $sHTML;
                    } else {
                        return $sHTML;
                    }
                }
            }
        } 
		else 
		{
			$this->database = LEPTON_database::getInstance();		
			$this->admin = LEPTON_admin::getInstance();				
			
			// get all users
			$this_users = array();
			$this->database->execute_query(
				"SELECT user_id, display_name FROM ".TABLE_PREFIX."users ",
				true,
				$this_users,
				true
			);				
        
            global $page_id;
            $iTempPageID = (isset($page_id))
                ? $page_id
                : (defined("PAGE_ID") ? PAGE_ID : 0 )
                ;
            $this->action_url = LEPTON_URL.'/backend/pages/modify.php?page_id='.$iTempPageID;
            $this->allSectionIDs = array();
               
            $all_sections = array();
            LEPTON_database::getInstance()->execute_query(
                "SELECT `section_id` FROM `".TABLE_PREFIX."sections` WHERE `page_id`= '".$iTempPageID."' AND `module`= 'wysiwyg' order by `position`",
                true,
                $all_sections,
                true
            );
            foreach($all_sections as $wysiwyg_section) {
                $this->allSectionIDs[] = abs(intval($wysiwyg_section['section_id']));
            }

            // At last we call the "include.php" of the current wysiwyg editor
            require_once LEPTON_PATH.'/modules/'.WYSIWYG_EDITOR.'/include.php';
        }
    }
	
    public function display_history($section_id = -1)
	{
		if(!isset($_POST['show_history']) && $_POST['show_history'] < 1)
		{
			die('[1]');
		}
		else
		{
			$section_id = intval($_POST['show_history']);
			$page_id = $this->database->get_one("SELECT page_id FROM ".TABLE_PREFIX."sections WHERE section_id = '".$section_id."' ");
		}
		
		// get all histories of current section
		$all_histories = array();
		$this->database->execute_query(
			"SELECT * FROM `".TABLE_PREFIX."mod_wysiwyg_history` WHERE `section_id`= '".$section_id."' order by id",
			true,
			$all_histories,
			true
		);	
		
		$aKnownUsers = [];
		foreach($all_histories as &$ref)
		{
            // a
		    $iTempUserId = $ref['user_id'];
		    
		    if(!isset($aKnownUsers[ $iTempUserId ]))
		    {
		        $aKnownUsers[ $iTempUserId ] = $this->database->get_one("SELECT `display_name` FROM `".TABLE_PREFIX."users` WHERE `user_id` = ".$iTempUserId);
		    }
		    $ref['user_id_display_name'] = $aKnownUsers[ $iTempUserId ];
		    
		    // b
		    $iTempUserId = $ref['user_id_hist'];
		    
		    if(!isset($aKnownUsers[ $iTempUserId ]))
		    {
		        $aKnownUsers[ $iTempUserId ] = $this->database->get_one("SELECT `display_name` FROM `".TABLE_PREFIX."users` WHERE `user_id` = ".$iTempUserId);
		    }
		    $ref['user_id_hist_display_name'] = $aKnownUsers[ $iTempUserId ];
		    
		}
		
		//echo(LEPTON_tools::display($_SESSION,'pre','ui blue message'));
		//  Collect the values
		$form_values = array(
			'oWGH'		=> $this,
			'page_id'	=> $page_id,
			'section_id'=> $section_id,
			'leptoken'	=> get_leptoken(),
			'all_histories'=> $all_histories
		);

		// Get instance of the template engine and render the output
		$oTWIG = lib_twig_box::getInstance();
		$oTWIG->registerModule("wysiwyg");

		echo $oTWIG->render( 
			"@wysiwyg/history.lte", // template-filename
			$form_values	//	template-data
		);
	}

    public function delete_version($id = -1)
	{
		if(!isset($_POST['delete_version']) && $_POST['delete_version'] < 1)
		{
			die('[1]');
		}
		else
		{
//			die(LEPTON_tools::display($this, 'pre','ui blue message'));
			$id_del = intval($_POST['delete_version']);
			$this->database->simple_query("DELETE FROM ".TABLE_PREFIX."mod_wysiwyg_history WHERE id = ".$id_del." ");
			
			$redirect = ADMIN_URL.'/pages/modify.php?page_id='.$_POST['page_id'].'#'.SEC_ANCHOR.$_POST['section_id'];
			$this->admin->print_success($this->language['save_ok'], $redirect );
		}
	}

    public function get_working_copy($section_id = -1)
	{
		if(!isset($_POST['get_working_copy']) && $_POST['get_working_copy'] < 1)
		{
			die('[1]');
		}
		else
		{
			$section_id = intval($_POST['get_working_copy']);
			$page_id = $this->database->get_one("SELECT page_id FROM ".TABLE_PREFIX."mod_wysiwyg WHERE section_id = '".$section_id."' ");
		}
		
		// get all data of current working copy
		$aWCopy = array();
		$this->database->execute_query(
			"SELECT * FROM `".TABLE_PREFIX."mod_wysiwyg` WHERE `section_id`= '".$section_id."' AND `use_workingcopy` > 0 ",
			true,
			$aWCopy,
			false
		);	
		
            // a
		    $iTempUserId = $aWCopy['user_id'];
		    $aWCopy['user_id_display_name'] = $this->database->get_one("SELECT `display_name` FROM `".TABLE_PREFIX."users` WHERE `user_id` = ".$iTempUserId);
	    
		    // b
		    $iTempUserId = $aWCopy['user_id_working'];
			$aWCopy['working_copy_display_name'] = $this->database->get_one("SELECT `display_name` FROM `".TABLE_PREFIX."users` WHERE `user_id` = ".$iTempUserId);
	
		//  Collect the values
		$form_values = array(
			'oWGH'		=> $this,
			'page_id'	=> $page_id,
			'section_id'=> $section_id,
			'leptoken'	=> get_leptoken(),
			'aWCopy'	=> $aWCopy
		);
	
		// Get instance of the template engine and render the output
		$oTWIG = lib_twig_box::getInstance();
		$oTWIG->registerModule("wysiwyg");

		echo $oTWIG->render( 
			"@wysiwyg/wcopy.lte", // template-filename
			$form_values	//	template-data
		);
	}
	
    public function delete_working_copy($id = -1)
	{
		if(!isset($_POST['delete_wc']) && $_POST['delete_wc'] < 1)
		{
			die('[1]');
		}
		else
		{
			$id_del = intval($_POST['delete_wc']);
			$oREQUEST = LEPTON_request::getInstance();
			// reset wysiwyg table
			$_POST['user_id_working'] = $_SESSION['USER_ID'];  // see who has deleted the working copy
			
			$all_names = array (
				'use_workingcopy'	=> array ('type' => 'int', 'default' => "0"),
				'user_id_working'	=> array ('type' => 'int', 'default' => "-1"),
				'working_content'	=> array ('type' => 'str', 'default' => ""),
				'working_content_comment'	=> array ('type' => 'int', 'default' => "")
			);

			$all_values = $oREQUEST->testPostValues($all_names);	
			
			$table = TABLE_PREFIX."mod_wysiwyg";
			$this->database->build_and_execute(
				'UPDATE', 
				$table, 
				$all_values,
				"section_id = ".$id_del
			);			
		}			
			
		$redirect = ADMIN_URL.'/pages/modify.php?page_id='.$_POST['page_id'].'#'.SEC_ANCHOR.$_POST['section_id'];
		$this->admin->print_success($this->language['save_ok'], $redirect );

	}	
	
	/**
	 *  Replace <script> tags with <p> tag and additioal class "illegal".
	 *
	 *  @param  string  $sSource    The source-content. Pass-by-reference!
	 *
not needed any longer, see lepton_request	
	static public function harmlessScriptTags( &$sSource )
	{
	    
        //Handle possible js tags
        $aFindReplace = [
            "<script"   => "<p class='illegal' ",
            "</script"  => "</p"
        ];
    
        $sSource = str_ireplace(
            array_keys( $aFindReplace ),
            array_values( $aFindReplace ),
            $sSource
        );
	}
*/	
}