<?php
/**
 * Main Component File
 * Used for the editor button (template xml)
 *
 * @package     Content Templater
 * @version     1.5.4
 *
 * @author      Peter van Westen <peter@nonumber.nl>
 * @link        http://www.nonumber.nl
 * @copyright   Copyright (C) 2010 NoNumber! All Rights Reserved
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

$class = new plgButtonContentTemplaterData();
$params = $class->getParams();

$mainframe =& JFactory::getApplication();
if ( $mainframe->isSite() ) {
	$user =& JFactory::getUser();
	if ( $user->get( 'guest' ) ) {
		die( 'Restricted access' );
	}

	if ( !$params->enable_frontend ) {
		die( 'Restricted access' );
	}
}

$class->render( $params );
exit;

class plgButtonContentTemplaterData
{
	function getParams() {
		jimport( 'joomla.plugin.plugin' );

		$component =& JComponentHelper::getComponent( 'com_contenttemplater' );
		require_once JPATH_PLUGINS.DS.'system'.DS.'nonumberelements'.DS.'helpers'.DS.'parameters.php';
		$parameters =& NNePparameters::getParameters();
		$params = $parameters->getParams( $component->params, JPATH_ADMINISTRATOR.DS.'components'.DS.'com_contenttemplater'.DS.'config.xml' );

		return $params;
	}

	function render( &$params )
	{
		header('Content-Type: text/html; charset=utf-8');

		// Content

		$id = JRequest::getInt( 'id' );

		if ( !$id ) {
			return;
		}

		$nocontent = JRequest::getInt( 'nocontent', 0 );
		$user =& JFactory::getUser();
		$unprotected = ( $user->usertype == 'Super Administrator' ) ? JRequest::getInt( 'unprotect' ) : 0;

		require_once( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_contenttemplater'.DS.'controllers'.DS.'item.php');
		require_once( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_contenttemplater'.DS.'models'.DS.'item.php');

		// Create a new class of classname and set the default task: display
		$item = new ContentTemplaterModelItem();
		$item->setId( $id );
		$item->getData( 0, false, 1 );

		$output = array();

		$ignore = array(
			'view_state',
			'id',
			'ordering',
			'name',
			'description',
			'ordering',
			'published',
			'checked_out',
			'checked_out_time'
		);

		$customfields = array();
		foreach ( $item->_data as $key => $val ) {
			if (
					is_string( $val )
				&&	$val != ''
				&&	!in_array( $key, $ignore )
				&&	strpos( $key, '@' ) !== 0
				&&	strpos( $key, 'button_' ) !== 0
				&&	strpos( $key, 'load_' ) !== 0
				&&	strpos( $key, 'url_' ) !== 0
				&&	!isset( $output[$key] )
			) {
				if ( $key == 'content' && $nocontent ) {
					continue;
				}
				if ( strpos( $key, 'customfield' ) === 0 ) {
					$field = explode( '_', $key );
					$name = str_replace( '_key', '', str_replace( '_value', '', $key ) );
					if ( !isset( $customfields[$field['0']] ) ) {
						$customfields[$field['0']] = '';
					}
					$customfields[$field['0']]->$field['1'] = $val;
				} else {
					$default = '';

					if ( isset( $item->defaults->$key ) ) {
						$default = $item->defaults->$key;
					}
					if ( $val != $default ) {
						$output[$key] = $this->getStr( $key, $val, $default );
					}
				}
			}
		}

		foreach( $customfields as $customfield ) {
			if ( isset( $customfield->key ) && $customfield->key != '' && isset( $customfield->value ) ) {
				$output[$customfield->key] = $this->getStr( $customfield->key, $customfield->value, 'customfield' );
			}
		}

		$str = implode( "\n", $output );
		if ( !$unprotected ) {
			$str = base64_encode( $str );
			$str = wordwrap( $str, 80, "\n", 1 );
		}
		echo $str;
	}

	function getStr( $key, $val, $default = '' )
	{
		switch ( $key ) {
			case 'categories_k2':
				$key = 'catid';
				break;
			case 'categories_mr':
				$key = 'categories';
				break;
		}
		if ( $key != 'content' ) {
			$this->makeSafeHtml( $val );
		}
		$this->replaceVars( $val );

		return '[CT]'.$key.'[CT]'.$default.'[CT]'.$val.'[/CT]';
	}
	function makeSafeHtml( &$str )
	{
		//return html_entity_decode( $str, ENT_QUOTES, 'UTF-8' );
		// TEST IF THIS WORKS ON ALL SETUPS!!!!
		// html_entity_decode GAVE TIMEOUTS ON SOME SETUPS?!?!

		if ( $str == '' ) { return; }

		static $trans_tbl;

		// replace numeric entities
		$str = preg_replace( '~&#x([0-9a-f]+);~ei', 'code2utf(hexdec("\1"))', $str );
		$str = preg_replace( '~&#([0-9]+);~e', 'code2utf(\1)', $str );

		// replace literal entities
		if ( !isset( $trans_tbl ) ) {
			$trans_tbl = array();

			foreach ( get_html_translation_table( HTML_ENTITIES ) as $val => $key ) {
				$trans_tbl[$key] = utf8_encode( $val );
			}
		}

		$str = strtr( $str, $trans_tbl );
	}
	function replaceVars( &$str )
	{
		if( !(strpos( $str, '[[user:' ) === false ) ) {
			$user =& JFactory::getUser();
			if( !(strpos( $str, '[[user:name]]' ) === false ) ) {
				$str = str_replace( '[[user:name]]', $user->name, $str );
			}
			if( !(strpos( $str, '[[user:username]]' ) === false ) ) {
				$str = str_replace( '[[user:username]]', $user->username, $str );
			}
			if( !(strpos( $str, '[[user:id]]' ) === false ) ) {
				$str = str_replace( '[[user:id]]', $user->id, $str );
			}
		}
		if( !(strpos( $str, '[[date:' ) === false ) ) {
			while ( preg_match( '#\[\[date:([^\]]*)\]\]#', $str, $matches ) ) {
				$date = @date( $matches[1], time() );
				$str = str_replace( $matches[0], $date, $str );
			}
		}
	}
}