<?php
/**
* @package Mambo
* @author Mambo Foundation Inc see README.php
* @copyright Mambo Foundation Inc.
* See COPYRIGHT.php for copyright notices and details.
* @license GNU/GPL Version 2, see LICENSE.php
* Mambo is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2 of the License.
*/

/**
* @version $Id: mostlyce.php
* @package Mambo_4.7
* @Based on tinymce.php
* @copyright (C) 2000 - 2007 The Mambo Foundation
* @license http://www.opensource.org/licenses/gpl-2.0.php GNU/GPL
* Mambo is Free Software
*/

/** ensure this file is being included by a parent file */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

global $mosConfig_live_site, $jspath, $mosConfig_absolute_path, $adminside;
include($mosConfig_absolute_path."/mambots/editors/mostlyce/jscripts/tiny_mce/mostlyce_config.php");

$_MAMBOTS->registerFunction( 'onInitEditor', 'botmostlyceEditorInit' );
$_MAMBOTS->registerFunction( 'onGetEditorContents', 'botmostlyceEditorGetContents' );
$_MAMBOTS->registerFunction( 'onEditorArea', 'botmostlyceEditorEditorArea' );

// --- Start custom code DHS Informatisering - opensource@dhs.nl, www.dhs.nl  
// This code makes it possible to use mostlyce in a website that combines normal and SSL-connections
if (isset($_SERVER['HTTPS']) &&  $_SERVER['HTTPS'] == "on") { 
	$jspath = "https:" . stristr ( $mosConfig_live_site, "//" );
} else {
	$jspath = "http:" . stristr ( $mosConfig_live_site, "//" );
}
// Replaced every occurrence of '$mosConfig_live_site' with '$jspath' in this file
// --- End custom code DHS Informatisering ---

//Render Row Buttons
function renderButton( $row, $remove_font )
{
    $row = explode( ',', $row );
    foreach( $row as $key => $rowitem ) {
        if( strpos( $rowitem, '-' )  === 0) {
            unset( $row[$key] );
        }
        if( $remove_font ){
            if( $rowitem == 'fontselect' || $rowitem == 'fontsizeselect' || $rowitem == 'forecolor' || $rowitem == 'backcolor' ) {
                unset( $row[$key] );
            }
        }
    }
    return $new_row = implode( ',', array_values( $row ) );
}

/**
* TinyMCE WYSIWYG Editor - javascript initialization
*/
function botmostlyceEditorInit() {
		global $mosConfig_live_site, $my, $database, $mosConfig_absolute_path, $jspath;
		global $adminside, $mosConfig_secret, $mosConfig_cachetime;
		include($mosConfig_absolute_path."/mambots/editors/mostlyce/jscripts/tiny_mce/mostlyce_config.php");

		//Setup a session variable for Image Manager and external list generator security checks
		$env = md5($_SERVER['HTTP_USER_AGENT']);
		$mostlyceRestoreKey=md5($mosConfig_secret.$env.$_SERVER['REMOTE_ADDR']);
		//Determine cookie expiration time.  Should match login timeout (though min of 1min).
		if (is_numeric($mosConfig_cachetime) && $mosConfig_cachetime>=60) {
			$cookieTimeout = $mosConfig_cachetime;
		} else {
			$cookieTimeout = 60;
		}
		setcookie("mostlyce[startup_key]", $mostlyceRestoreKey, time()+$cookieTimeout, '/');
		setcookie("mostlyce[usertype]", $my->usertype, time()+$cookieTimeout, '/');

        //Allows for dynamic editor sizing by apps like Remository
	    $get_width = mosGetParam($_GET,'width',NULL);
	    $get_height = mosGetParam($_GET,'height',NULL);
	    if ($get_width) {
	    	$editor_width = (int) $get_width; 
	    }
	    if ($get_height) {
	    	$editor_height = (int) $get_height; 
	    } 
        
        // Get the default stylesheet
        $query = "SELECT template FROM #__templates_menu WHERE client_id='0' AND menuid='0'";
        $database->setQuery( $query );
        $cur_template = $database->loadResult();
        // Assigned template
        if (isset( $Itemid ) && $Itemid != "" && $Itemid != 0) {
            $query = "SELECT template FROM #__templates_menu WHERE client_id='0' AND menuid='$Itemid' LIMIT 1";
            $database->setQuery($query);
            $cur_template = $database->loadResult() ? $database->loadResult() : $cur_template;
        }
        
        //Plugin settings and Authorization
        $invalid_elements[] = 'object,applet';

	    //Check access level and MOStlyCE Admin preference.  Set editor items accordingly.  
        //Script Elements (Only loads for Admin)
        if (($adminside>0) && ($editor_script_acl==='true')) {
        	$elements[] = "script[$editor_script_elms]";
        } else {
            $invalid_elements[] = "script";
        }
        //IFrame Elements (Only loads for Admin)
        if (($adminside>0) && ($editor_iframe_acl=='true')) {
            $elements[] = "iframe[$editor_iframe_elms]";
        }
        //Media Plugin
        if ($editor_plugin_media_acl==='true') {
        	$plugins[] = 'media';
        } 
        //Font Options
        if ($editor_font_tools_acl==='true') {
            $elements[] = "font[face|size|color|style]";
            $remove_font = false;
       } else {
            $remove_font = true;
       }
        //Emotions Plugin
        if ($editor_plugin_emotions_acl==='true') {
            $plugins[] = 'emotions';
        } 
        //Print Plugin
        if ($editor_plugin_print==='true') {
            $plugins[] = 'print';
        } 
        //Search & Replace Plugin
        if ($editor_plugin_searchreplace==='true') {
            $plugins[] = 'searchreplace';
        } 
        //Table Plugin
        if ($editor_plugin_table_acl==='true') {
            $plugins[] = 'table';
        } 
        //DateTime Plugin
        if ($editor_plugin_datetime_acl==='true') {
            $plugins[] = 'insertdatetime';
        } 
        //SpellChecker Plugin (needs Curl)
        if ($editor_plugin_spellchecker==='true' && function_exists("curl_init")) {
            $plugins[] = 'spellchecker';
			$theme_advanced_buttons4_add = 'spellchecker';
        } else {
			$theme_advanced_buttons4_add = '';
		}
        //Layer Plugin
        if ($editor_plugin_layer==='true') {
            $plugins[] = 'layer';
        }   
        //Image/File Manager Plugin
        if ($editor_plugin_img_mgr==='true') {
        	$file_browser_callback='fileBrowserCallBack';
	    } else {
			//Img/File browser not enabled
	    	$file_browser_callback='';
		}
          
        //Paragraphs or breaks
        if ($editor_newlines == 'p'){
            $p_newlines = "true";
            $br_newlines = "false";
        }
        if ($editor_newlines == 'br'){
            $p_newlines = "false";
            $br_newlines = "true";
        }

        $css_template = $mosConfig_live_site."/templates/".$cur_template."/css/";
        $content_css = ($editor_css_override === '1' ) ? $css_template.$editor_custom_css : $css_template."template_css.css";
        
        //Plugins List
        $plugins[] = $editor_extra_plugins;
		$plugins[] = 'safari,pagebreak,style,advhr,advimage,advlink,iespell,inlinepopups,preview,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras'; //These ones are always loaded
        $plugins = implode( ',', $plugins );
        $elements[] = $editor_xtd_elms;
        $elements = implode( ',', $elements );
        $invalid_elements = implode( ',', $invalid_elements );

/* Check TinyMCE compression setting and set correct file path
	Note: The TinyMCE PHP gzip compressor cannot and will not work if zlib compression is already enabled on the server.
*/
$tinyHeader = '';
if ($editor_compression==='true' && !ini_get('zlib.output_compression')) { 
	$tinyHeader = "<script type=\"text/javascript\" src=\"$jspath/mambots/editors/mostlyce/jscripts/tiny_mce/tiny_mce_gzip.js\"></script>";
	$tinyHeader .="<!-- Standard init and GZ init need to be in seperate script tags! -->
	<script type=\"text/javascript\">
	tinyMCE_GZ.init({
		plugins : '$plugins',
		themes : '$editor_themes',
		languages : '$editor_lang',
		disk_cache : true,
		debug : false
	});
	</script>";
} else {  
	$tinyHeader = "<script type=\"text/javascript\" src=\"$jspath/mambots/editors/mostlyce/jscripts/tiny_mce/tiny_mce.js\"></script>";
}
        
        return <<<EOD
<!--//TinyMCE/MOStlyCE-->
$tinyHeader
<script type="text/javascript" src="$jspath/mambots/editors/mostlyce/jscripts/tiny_mce/mostlyce_functions.js"></script>
<script type="text/javascript">
	tinyMCE.init({
			//General options
			mode : "none",
			theme : "$editor_themes",
			plugins : "$plugins",

			//Theme options
			theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,code,|,insertdate,inserttime,preview,fullscreen",
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,media,advhr,|,print,|,help",
			theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,|,forecolor,backcolor",
			theme_advanced_buttons4_add : "$theme_advanced_buttons4_add",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,

			//Drop lists for link/image/media/template dialogs
			//template_external_list_url : "",
			external_link_list_url : "$jspath/index2.php?option=com_mostlyce_frontend&task=contentlist&no_html=1",
			external_image_list_url : "$jspath/index2.php?option=com_mostlyce_frontend&task=imagelist&no_html=1",
			//media_external_list_url : "",
			
			//More MOStlyCE custom settings
			file_browser_callback : "$file_browser_callback",
			width : "$editor_width",
	        height : "$editor_height",
	        mambo_base_url: "$mosConfig_live_site/",
	        document_base_url: "$mosConfig_live_site/",
	        plugin_insertdate_dateFormat : "$editor_plugin_dateformat",
	    	plugin_insertdate_timeFormat : "$editor_plugin_timeformat",
			content_css : "$content_css",
			invalid_elements: "$invalid_elements",
	        force_br_newlines : "$br_newlines",
	        force_p_newlines : "$p_newlines",
	        directionality : "$editor_direction",
			language : "$editor_lang",
	        lang_list : "$editor_lang_list",
			pagebreak_separator : "{mospagebreak}",
			extended_valid_elements : "hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style],$elements",
			spellchecker_languages : "+English=en,Danish=da,Dutch=nl,Finnish=fi,French=fr,German=de,Italian=it,Polish=pl,Portuguese=pt,Spanish=es,Swedish=sv"
		});
		
		function fileBrowserCallBack(field_name, url, type, win) {
		var connector = "../../filemanager/browser.php?Connector=connectors/php/connector.php";
		var enableAutoTypeSelection = false;
		
		var cType;
		tinymcpuk_field = field_name;
		tinymcpuk = win;
		
		switch (type) {
			case "image":
				cType = "Image";
				break;
			case "flash":
				cType = "Flash";
				break;
			case "file":
				cType = "File";
				break;
			case "media":
				cType = "Media";
				break;
		}
		
		if (enableAutoTypeSelection && cType) {
			connector += "&Type=" + cType;
		}
		
		window.open(connector, "tinymcpuk", "modal,width=600,height=400");
	}
</script>
<!-- /tinyMCE -->
EOD;
}
/**
* TinyMCE WYSIWYG Editor - copy editor contents to form field
* @param string The name of the editor area
* @param string The name of the form field
*/
function botmostlyceEditorGetContents( $editorArea, $hiddenField ) {
        global $jspath;

        return <<<EOD
        tinyMCE.triggerSave();
EOD;
}
/**
* mostlyce WYSIWYG Editor - display the editor
* @param string The name of the editor area
* @param string The content of the field
* @param string The name of the form field
* @param string The width of the editor area
* @param string The height of the editor area
* @param int The number of columns for the editor area
* @param int The number of rows for the editor area
*/
function botmostlyceEditorEditorArea( $name, $content, $hiddenField, $width, $height, $col, $row, $showbut=1 ) {
        global $jspath, $_MAMBOTS, $mosConfig_absolute_path;
        include($mosConfig_absolute_path."/mambots/editors/mostlyce/jscripts/tiny_mce/mostlyce_config.php");

        $results = $_MAMBOTS->trigger( 'onCustomEditorButton' );
        $buttons = array();
        foreach ($results as $result) {
               $buttons[] = '<img src="'.$jspath.'/mambots/editors-xtd/'.$result[0].'" onclick="tinyMCE.execCommand(\'mceInsertContent\',false,\''.$result[1].'\')" />';
        }
        //Hide old {mosimage} button if requested
        if ($editor_mosimage_icon == 'false') {
          unset($buttons[array_search(0,$buttons)]);
        }
        $buttons = implode( "", $buttons );

        return <<<EOD
<textarea id="$hiddenField" name="$hiddenField" cols="$col" rows="$row" style="width:{$width}px; height:{$height}px;">$content</textarea>
<script type="text/javascript">tinyMCE.execCommand('mceAddControl', false, '$hiddenField');</script>
<br />$buttons
EOD;
}
?>