<?php
/**
  * BLOG:CMS: PHP/MySQL Personal Content Management System (CMS)
  * http://blogcms.com/
  * ----------------------------------------------------------------
  *
  * Copyright (C) 2003-2006 Radek HULÁN
  * http://hulan.cz/contact/
  *
  * ----------------------------------------------------------------
  * This program 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; either version 2
  * of the License, or (at your option) any later version.
**/

global $DIR_PLUGINS;
if (!is_dir($DIR_PLUGINS)) 
	die('System is not configured properly - NP_WYSIWYG.php');
require($DIR_PLUGINS.'smartypants/smartypants.php');
require($DIR_PLUGINS.'textile/class.textile.php');
require($DIR_PLUGINS.'texy/mytexy.php');

class NP_WYSIWYG extends NucleusPlugin {

	function getName() 		{ return 'Article editor'; }
	function getAuthor()  	{ return 'Radek HULAN'; }
	function getURL()  		{ return 'http://hulan.cz/blog/'; }
	function getVersion() 	{ return '1.0'; }
	function getDescription() {
		return 'This plugin supports multiple WYSIWYG editors, like FCKEditor.net or XStandard.';
	}

	function supportsFeature($what) {
		switch($what)
		{
			case 'SqlTablePrefix':
				return 1;
			default:
				return 0;
		}
	}

	function install() {
			$this->createMemberOption('use_wysiwyg', 'Which article editor you want to use?', 'select', 'fck', 'Advanced ActiveX Editor: XStandard.com|xstandard|JavaScript Editor: FCKEditor.net|fck|Textile Syntax|textile|Texy Syntax|texy|XHTML Syntax|none');
			$this->createMemberOption('smartypantsDefault','Allow SmartyPants by default:','yesno','no');
     	$this->createMemberOption('detextile','DeTextile before editing (only for Textile Syntax):','yesno','no');

    	$this->createMemberOption('texyHighlight', 'Use Texy Syntax highlighting (only for Texy Syntax):',  'yesno', 'no');
    	$this->createMemberOption('texySmilies', 'Use Texy smilies (only for Texy Syntax):', 'yesno', 'yes');
	}

	function getEventList() {
		return array(
			'AdminPrePageHead',     
			'BookmarkletExtraHead',	
			'PreSendContentType', 	
			'AddItemFormExtras',
			'EditItemFormExtras',
			'PrepareItemForEdit',
			'PreAddItem',
			'PreUpdateItem',
			'PostAddItem',
			'PreUpdateComment',
			'PreAddComment'
		);
	}
	
	function init() {
		global $member;
		if (isset($member)) 
			$this->editor = $this->getMemberOption($member->getID(),'use_wysiwyg');
		else
			$this->editor = 'none';
	}

	function event_PrepareItemForEdit(&$data) {
		// FCKEDITOR.NET
		if ($this->editor == 'fck') {
			$parts = array('body','more');
			foreach ($parts as $part) {
  				$data['item'][$part] = preg_replace('/<%image\((.*?)\)%>/', '[%image(\\1)%]', $data['item'][$part]);
  				$data['item'][$part] = preg_replace('/<%popup\((.*?)\)%>/', '[%popup(\\1)%]', $data['item'][$part]);
    		}
    	}
	  	// TEXTILE
	  	if ($this->editor == 'textile') {
	  		global $member;
	  		if ($this->getMemberOption($member->getID(),'detextile') == 'yes') {
    			$query=sql_query("select editor from ".sql_table('item')." where inumber=".intval($data['item']['itemid']));
    			if ($row=sql_fetch_object($query)) 
    				if (intval($row->editor) == 1) {
  						$parts = array('body','more');
  						$textile =& new Textile();
  						foreach ($parts as $part) 
        					$data['item'][$part] = $textile->DeTextileThis($data['item'][$part]);
  					}
			}
		}
		 // TEXY
		 if ($this->editor == 'texy') {
    		$id = (int) $data['item']['itemid'];
    		$query = sql_query("select `texybody`, `texymore` from ".sql_table('item')." where inumber=$id");
    		if ($row = sql_fetch_object($query))
    			if ($row->texybody) { 
      				$data['item']['body'] = $row->texybody;
      				$data['item']['more'] = $row->texymore;
      			}
    	}
	}

	function event_PreAddItem(&$data) {
		// FCKEDITOR.NET
		if ($this->editor == 'fck') {
			$parts = array('body','more');
			foreach ($parts as $part) {
				// pseudo tags into BLOG:CMS pseudo-tags
  				$data[$part] = preg_replace('/\[%image\((.*?)\)%\]/', '<%image(\\1)%>', $data[$part]);
  				$data[$part] = preg_replace('/\[%popup\((.*?)\)%\]/', '<%popup(\\1)%>', $data[$part]);
    		}
    	}
		// TEXTILE
		if ($this->editor == 'textile') {
      		if (requestVar('textile_on') == 'yes') {
      			//find blog:cms media markup and convert it to stop clashes with textile
      			$data['body'] = preg_replace("/[\[<]%(.*?)%[\]>]/",":::$1:::",$data['body']);
      			$data['more'] = preg_replace("/[\[<]%(.*?)%[\]>]/",":::$1:::",$data['more']);
      			//do dat textile thang
      			$textile =& new Textile();
      			$data['body'] = $textile->TextileThis($data['body']);
      			$data['more'] = $textile->TextileThis($data['more']);
      			//now return the media markup back to original
      			$data['body'] = preg_replace("/:::(.*?):::/","<%$1%>",$data['body']);
      			$data['more'] = preg_replace("/:::(.*?):::/","<%$1%>",$data['more']);
      		}
      	}
		if ($this->editor != 'texy') {
    		// SMARTYPANTS
			if (requestVar('smartypants_on') == 'yes') {
				$parts = array('title','body','more');
				foreach ($parts as $part) $data[$part] = SmartyPants($data[$part], DEFAULT_OPERATION_MODE | DO_QUOT_CONV);
			}
			// ENTITIES
			$content = array('title'=>&$data['title'],'body'=>&$data['body'],'more'=>&$data['more']);
			$this->parseStringEntities($content);
		}
	}

	function event_PreUpdateItem($data) {
		 // TEXY
		 if ($this->editor == 'texy') {
    		$id = (int) $data['itemid'];
    		if (requestVar('Texy_on') == 'yes') { 
      			// format
      			$texy = &new MyTexy();
      			global $member;
      			if ($this->getMemberOption($member->getID(),'texyHighlight') == 'yes') 
      				$texy->useHighlighter();
      			if ($this->getMemberOption($member->getID(),'texySmilies') == 'yes') 
      				$texy->smiliesModule->allowed = true;
      			$texybody = addslashes($data['body']);
      			$texymore = addslashes($data['more']);  
      			$data['body'] = $texy->process($data['body']);
      			$data['more'] = $texy->process($data['more']);
      			sql_query("update ".sql_table('item')." set editor=2, `texybody`='$texybody', `texymore`='$texymore' where `inumber`=$id");    
      			return;
    		}
      		$texybody = $texymore = '';  
      		sql_query("update ".sql_table('item')." set editor=0, `texybody`='$texybody', `texymore`='$texymore' where `inumber`=$id");    
    	}

    	// FCKEDITOR.NET + XSTANDARD + TEXTILE
		$this->event_PreAddItem($data);

		// TEXTILE
		if ($this->editor == 'textile'){
	   		if (requestVar('textile_on') == 'yes')
				sql_query('UPDATE '.sql_table('item').' SET editor=1 WHERE inumber='.intval($data['itemid']));
		}
	}

	 function event_PostAddItem(&$data) {
	 	// TEXTILE
	 	if ($this->editor == 'textile') {
	   		if (requestVar('textile_on') == 'yes') {
		   		$q = 'UPDATE '.sql_table('item').' SET editor=1 WHERE inumber='.intval($data['itemid']);
		   		sql_query($q);
		 	}
		 }
		 // TEXY
		 if ($this->editor == 'texy') {
    		if (requestVar('Texy_on') == 'yes') {
    			$id = (int) $data['itemid'];  
    			$query = sql_query("select `ibody`, `imore` from ".sql_table('item')." where inumber=$id");
    			$row = sql_fetch_object($query);
    			// format
    			$texy = &new MyTexy();
    			global $member;
    			if ($this->getMemberOption($member->getID(),'texyHighlight') == 'yes') 
    				$texy->useHighlighter();
    			if ($this->getMemberOption($member->getID(),'texySmilies') == 'yes') 
    				$texy->smiliesModule->allowed = true;
    			$texybody = addslashes($row->ibody);
    			$texymore = addslashes($row->imore);
    			$ibody = addslashes($texy->process($row->ibody));
    			$imore = addslashes($texy->process($row->imore));
    			sql_query("update ".sql_table('item')." set editor=2, `ibody`='$ibody', `imore`='$imore', `texybody`='$texybody', `texymore`='$texymore' where `inumber`=$id");
    		}
    	}
	 }

	function event_BookmarkletExtraHead(&$data) {
		// FCKEDITOR.NET
		if ($this->editor == 'fck') {
			$this->_getExtraHead($data['extrahead']);
		}
	}

	function event_AdminPrePageHead(&$data) {
		// FCKEDITOR.NET
		if ($this->editor == 'fck') {
			$action = $data['action'];
			if (($action != 'createitem') && ($action != 'itemedit')) 
				return;
			$this->_getExtraHead($data['extrahead']);
		}
	}

	function event_AddItemFormExtras(&$data) {
    	// SMARTYPANTS
		global $member, $CONF;
		if ($this->getMemberOption($member->getID(),'smartypantsDefault') == 'yes')
			$s=" checked='checked' ";
		echo "<h3>SmartyPants &#8212; <a href='".$CONF['PluginURL']."smartypants/info.html' target='_blank'>more info&#8230;</a></h3><p>Use &#8220;SmartyPants&#8221; for this article: <input type='checkbox' name='smartypants_on' value='yes' $s />?</p>";
		// TEXTILE
     	if ($this->editor == 'textile') {
     		echo "<h3>Textile &#8212; <a href='".$CONF['PluginURL']."textile/info.html' target='_blank'>more info&#8230;</a></h3><p>Use &#8220;Textile&#8221; for this article: <input type='checkbox' name='textile_on' value='yes' checked='checked' />?</p>";
     	}
		// TEXY
		if ($this->editor == 'texy') {
    		echo "<h3>Texy! (<a href='".$CONF['PluginURL']."texy/info.html' target='_blank'>more info&#8230;</a>)</h3><p>Use Texy! for this article: <input type='checkbox' name='Texy_on' value='yes' checked='checked' />?</p>";
    	}
	}

	function event_EditItemFormExtras(&$data) {
    	// SMARTYPANTS
		global $member, $CONF;
		if ($this->getMemberOption($member->getID(),'smartypantsDefault') == 'yes') 
			$s=" checked='checked' ";
		echo "<h3>SmartyPants &#8212; <a href='".$CONF['PluginURL']."smartypants/info.html' target='_blank'>more info&#8230;</a></h3><p>Use &#8220;SmartyPants&#8221; for this article: <input type='checkbox' name='smartypants_on' value='yes' $s />?</p>";
		// TEXTILE
		if ($this->editor == 'textile') {
     		if ( $this->getOption('textileDefault') == 'yes' ) 
     			$s=" checked='checked' "; 
     		else 
     			$s='';
     		$query=sql_query("select editor from ".sql_table('item')." where inumber=".intval($data['itemid']));
     		if ($row=sql_fetch_object($query)) 
     			if ($row->editor==1) 
     				$s=" checked='checked' ";
     		echo "<h3>Textile &#8212; <a href='".$CONF['PluginURL']."textile/info.html' target='_blank'>more info&#8230;</a></h3><p>Use &#8220;Textile&#8221; for this article: <input type='checkbox' name='textile_on' value='yes' $s />?</p>";
     	}
		// TEXY
		if ($this->editor == 'texy') {
    		$id = (int) $data['itemid'];
    		$query = sql_query("select `texybody` from ".sql_table('item')." where inumber=$id");
    		$row = sql_fetch_object($query);
    		if ($row->texybody) 
    			$s=" checked='checked'"; 
    		else 
    			$s = '';
    		echo "<h3>Texy! (<a href='".$CONF['PluginURL']."texy/info.html' target='_blank'>more info&#8230;</a>)</h3><p>Use Texy! for this article: <input type='checkbox' name='Texy_on' value='yes' $s />?</p>";
    	}
	}

	function event_PreAddComment(&$data) {
		// ENTITIES
		$data['comment']['body'] = entity_to_decimal_value($data['comment']['body']); 
	}

	function event_PreUpdateComment(&$data) {
		// ENTITIES
		$data['body'] = entity_to_decimal_value($data['body']); 
	}

  	var $bUseEditor;
  
	function _getExtraHead(&$extrahead) {
		global $CONF, $member;
		// FCKEDITOR.NET
		$this->bUseEditor	= ($this->getMemberOption($member->getID(), 'use_wysiwyg') == 'fck');
		if ($this->bUseEditor) {
   			$baseUrl = $this->getAdminURL();
	    	$editorCode = '<script type="text/javascript" src="'.$baseUrl.'fckeditor.js"></script>'."\n"
	            . '<script type="text/javascript">'."\n"
							. 'window.onload = function(){'."\n"
    	        . 'var editor1=new FCKeditor("more",622,390,"Default","");'."\n"
    	        . 'editor1.BasePath="'.$baseUrl.'";'."\n" 
    	        . 'editor1.MediaURL = "'.$CONF['MediaURL'].'";'."\n"
    	        . 'editor1.AuthorID = "'.strval($member->getID()).'";'."\n"
    	        . 'editor1.Config["LinkBrowserURL"] = editor1.BasePath+"editor/filemanager/browser/default/browser.html?Connector=connectors/php/connector.php&ServerPath='.$CONF['MediaURL'].strval($member->getID()).'";'."\n"
    	        . 'editor1.Config["ImageBrowserURL"] = editor1.BasePath+"editor/filemanager/browser/default/browser.html?Connector=connectors/php/connector.php&Type=Image&ServerPath='.$CONF['MediaURL'].strval($member->getID()).'";'."\n"
    	        . 'editor1.Config["FlashBrowserURL"] = editor1.BasePath+"editor/filemanager/browser/default/browser.html?Connector=connectors/php/connector.php&Type=Flash&ServerPath='.$CONF['MediaURL'].strval($member->getID()).'";'."\n"
    	        . 'editor1.ReplaceTextarea();'."\n"
    	        . 'var usingFCK = editor1._IsCompatibleBrowser() ? true : false;'."\n"
    	        . 'var editor2=new FCKeditor("body",622,390,"Default","");'."\n"
    	        . 'editor2.BasePath="'.$baseUrl.'";'."\n" 
    	        . 'editor2.MediaURL = "'.$CONF['MediaURL'].'";'."\n"
    	        . 'editor2.AuthorID = "'.strval($member->getID()).'";'."\n"
    	        . 'editor2.Config["LinkBrowserURL"] = editor2.BasePath+"editor/filemanager/browser/default/browser.html?Connector=connectors/php/connector.php&ServerPath='.$CONF['MediaURL'].strval($member->getID()).'";'."\n"
    	        . 'editor2.Config["ImageBrowserURL"] = editor2.BasePath+"editor/filemanager/browser/default/browser.html?Connector=connectors/php/connector.php&Type=Image&ServerPath='.$CONF['MediaURL'].strval($member->getID()).'";'."\n"
    	        . 'editor2.Config["FlashBrowserURL"] = editor2.BasePath+"editor/filemanager/browser/default/browser.html?Connector=connectors/php/connector.php&Type=Flash&ServerPath='.$CONF['MediaURL'].strval($member->getID()).'";'."\n"
    	        . 'editor2.ReplaceTextarea();'."\n"
    	        . 'if (usingFCK) hideElements(); '."\n";
    		if (strstr(serverVar('REQUEST_URI'),'bookmarklet'))
        		$editorCode.= 'nucleus_initbm();'."\n";
      		$editorCode.= '}; '."\n".'</script>'."\n";
   			$extrahead .= $editorCode;
		}
	}

	function event_PreSendContentType(&$data) {
		$pageType = $data['pageType'];
		if ($pageType == 'skin')
			return;
		if (	($pageType != 'bookmarklet-add')
			&&	($pageType != 'bookmarklet-edit')
			&&	($pageType != 'admin-createitem')
			&& 	($pageType != 'admin-itemedit')
			)
			return;
		if ($data['contentType'] == 'application/xhtml+xml') 
			$data['contentType'] = 'text/html';
	}

	function parseStringEntities(&$content) {
		$keys=array('title','body','more');
		foreach ($keys as $key)
			$content[$key] = entity_to_decimal_value($content[$key]);
   }
}
?>