<?php
/**
 * Plugin Helper File
 *
 * @package     Content Templater editor button
 * @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' );

/**
* System Plugin that places a Content Templater code block into the text
*/
class plgSystemContentTemplaterHelper
{
	function plgSystemContentTemplaterHelper( &$params )
	{
		// Load plugin parameters
		$this->params = $params;
	}

	/**
	* Display the System
	*
	* @return array A two element array of ( imageName, textToInsert )
	*/
	function placeContent()
	{
		$mainframe =& JFactory::getApplication();

		$document =& JFactory::getDocument();

		if ( !isset( $document->_buffer['component'] ) || !is_array( $document->_buffer['component'] ) ) {
			return;
		}

		$editor_id = 0;
		foreach ( $document->_buffer['component'] as $key => $val ) {
			$match = preg_match( '#CT_editor = "(.*?)"#', $val, $matches );
			if ( $matches ) {
				$editor_id = $matches['1'];
			}
		}
		if ( !$editor_id ) {
			return;
		}

		$empty_editor = 0;
		$regex = '#(<textarea[^>]* id="'.preg_quote( $editor_id, '#' ).'"[^>]*>)\s*(</textarea>)#s';
		foreach ( $document->_buffer['component'] as $key => $val ) {
			if ( preg_match( $regex, $val ) ) {
				$empty_editor = 1;
			}
		}

		if ( !$empty_editor ) {
			return;
		}

		require_once JPATH_PLUGINS.DS.'system'.DS.'nonumberelements'.DS.'helpers'.DS.'assignments.php';
		$this->assignments = new NoNumberElementsAssignmentsHelper;

		$user =& JFactory::getUser();

		require_once JPATH_ADMINISTRATOR.DS.'components'.DS.'com_contenttemplater'.DS.'models'.DS.'list.php';
		$list = new ContentTemplaterModelList();
		$list->setState( 'limit', 0 );
		$list->setState( 'limitstart', 0 );
		$items = $list->getAllParams();

		$document =& JFactory::getDocument();

		$default = 0;
		$url_load = JRequest::getCmd( 'ctid' );

		$options = array();
		$extra_Systems = array();
		$styles = array(); 

		foreach( $items as $item ) {
			// not enabled if: not published
			if ( !$item->published ) { continue; }

			$item_params = array();
			foreach( $item as $key => $val ) {
				$item_params[$key] = $val;
			}

			$pass = $this->passChecks( $item_params );

			// check if template should be loaded by url
			if (	$url_load && $url_load == $item->id
				&&	$this->passChecks( $item_params, 'url', $pass )
			) {
				$default = $item->id;
			}
			// check if template should be loaded by default
			if (	!$default
				&&	$this->passChecks( $item_params, 'load', $pass )
			) {
				$default = $item->id;
			}
		}

		if ( $default ) {

			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( $default );
			$item->getData( 0, false, 1 );

			foreach ( $document->_buffer['component'] as $key => $val ) {
				if ( preg_match( $regex, $val ) ) {
					$document->_buffer['component'][ $key ] = preg_replace( $regex, '\1'.$item->_data->content.'\2', $val );
				}
			}

			$script = '
			var CT_f_loaded = 0;
				window.addEvent( \'domready\', function() {
					if( CT_f_loaded == 0 ) {
						CT_f_loaded = 1;
						( function() { CT_f.getXML( '.$default.', \'\', 1 ) } ).delay( '.(int) ( $this->params->url_delay * 1000 ).' );
					}
				});
			';
			$document->addScriptDeclaration( $script );
		}
	}

	function passChecks( &$item, $type = 'button', $button_pass = 0 )
	{
		if ( !$item[$type.'_enabled'] ) {
			return 0;
		}

		if ( $type != 'button' && $item[$type.'_enabled'] == 2 ) {
			return $button_pass;
		}

		$mainframe =& JFactory::getApplication();

		// not enabled if: not active in this area (frontend/backend)
		if (
			( $mainframe->isAdmin() && $item[$type.'_enable_in_frontend'] == 2 ) ||
			( $mainframe->isSite() && $item[$type.'_enable_in_frontend'] == 0 )
		) {
			return 0;
		}

		// return true if no extra assignment settings are used
		if ( !$item[$type.'_use_assignments'] ) {
			return 1;
		}

		$params = array();

		if ( $item[$type.'_assignto_menuitems'] ) {
			$params['MenuItem'] = null;
			$params['MenuItem']->assignment = $item[$type.'_assignto_menuitems'];
			$params['MenuItem']->selection = $item[$type.'_assignto_menuitems_selection'];
			$params['MenuItem']->params = null;
			$params['MenuItem']->params->inc_children = $item[$type.'_assignto_menuitems_inc_children'];
			$params['MenuItem']->params->inc_noItemid = $item[$type.'_assignto_menuitems_inc_noitemid'];
		}
		if ( $item[$type.'_assignto_urls'] ) {
			$params['URL'] = null;
			$params['URL']->assignment = $item[$type.'_assignto_urls'];

			$config =& JFactory::getConfig();
			if ( $config->getValue('config.sef') == 1 ) {
				$params['URL']->selection = $item[$type.'_assignto_urls_selection_sef'];
			} else {
				$params['URL']->selection = $item[$type.'_assignto_urls_selection'];
			}
			$params['URL']->selection = str_replace( '\n', "\n", $params['URL']->selection );
			$params['URL']->selection = str_replace( '[:REGEX_ENTER:]', '\n', $params['URL']->selection );
			$params['URL']->selection = explode( "\n", $params['URL']->selection );
		}
		if ( $item[$type.'_assignto_browsers'] ) {
			$params['Browsers'] = null;
			$params['Browsers']->assignment = $item[$type.'_assignto_browsers'];
			$params['Browsers']->selection = $item[$type.'_assignto_browsers_selection'];
		}
		if ( $item[$type.'_assignto_date'] ) {
			$params['Date'] = null;
			$params['Date']->assignment = $item[$type.'_assignto_date'];
			$params['Date']->params = null;
			$params['Date']->params->publish_up = $item[$type.'_assignto_date_publish_up'];
			$params['Date']->params->publish_down = $item[$type.'_assignto_date_publish_down'];
		}
		if ( $item[$type.'_assignto_usergrouplevels'] ) {
			$params['UserGroupLevels'] = null;
			$params['UserGroupLevels']->assignment = $item[$type.'_assignto_usergrouplevels'];
			$params['UserGroupLevels']->selection = $item[$type.'_assignto_usergrouplevels_selection'];
		}
		if ( $item[$type.'_assignto_users'] ) {
			$params['Users'] = null;
			$params['Users']->assignment = $item[$type.'_assignto_users'];
			$params['Users']->selection = $item[$type.'_assignto_users_selection'];
		}
		if ( $item[$type.'_assignto_components'] ) {
			$params['Components'] = null;
			$params['Components']->assignment = $item[$type.'_assignto_components'];
			$params['Components']->selection = $item[$type.'_assignto_components_selection'];
		}
		if ( $item[$type.'_assignto_articles'] ) {
			$params['Articles'] = null;
			$params['Articles']->assignment = $item[$type.'_assignto_articles'];
			$params['Articles']->selection = $item[$type.'_assignto_articles_selection'];
		}
		if ( $item[$type.'_assignto_secscats'] ) {
			$params['SecsCats'] = null;
			$params['SecsCats']->assignment = $item[$type.'_assignto_secscats'];
			$params['SecsCats']->selection = $item[$type.'_assignto_secscats_selection'];
			$params['SecsCats']->params = null;
			$incs = explode( ',', $item[$type.'_assignto_secscats_inc'] );
			$params['SecsCats']->params->inc_sections = in_array( 'inc_secs', $incs );
			$params['SecsCats']->params->inc_categories = in_array( 'inc_cats', $incs );
			$params['SecsCats']->params->inc_articles = in_array( 'inc_arts', $incs );
			$params['SecsCats']->params->inc_others = in_array( 'inc_others', $incs );
		}
		if ( $item[$type.'_assignto_languages'] ) {
			$params['Languages'] = null;
			$params['Languages']->assignment = $item[$type.'_assignto_languages'];
			$params['Languages']->selection = $item[$type.'_assignto_languages_selection'];
		}
		if ( $item[$type.'_assignto_templates'] ) {
			$params['Templates'] = null;
			$params['Templates']->assignment = $item[$type.'_assignto_templates'];
			$params['Templates']->selection = $item[$type.'_assignto_templates_selection'];
		}
		if ( $item[$type.'_assignto_php'] ) {
			$params['PHP'] = null;
			$params['PHP']->assignment = $item[$type.'_assignto_php'];
			$params['PHP']->selection = $item[$type.'_assignto_php_selection'];
		}

		if ( $item[$type.'_assignto_k2cats'] && JFile::exists( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'admin.k2.php' ) ) {
			$params['Categories_K2'] = null;
			$params['Categories_K2']->assignment = $item[$type.'_assignto_k2cats'];
			$params['Categories_K2']->selection = $item[$type.'_assignto_k2cats_selection'];
			$params['Categories_K2']->params = null;
			$params['Categories_K2']->params->inc_children = $item[$type.'_assignto_k2cats_inc_children'];
			$incs = explode( ',', $item[$type.'_assignto_k2cats_inc'] );
			$params['Categories_K2']->params->inc_categories = in_array( 'inc_cats', $incs );
			$params['Categories_K2']->params->inc_items = in_array( 'inc_items', $incs );
		}

		if ( $item[$type.'_assignto_mrcats'] && JFile::exists( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_resource'.DS.'resource.php' ) ) {
			$params['Categories_MR'] = null;
			$params['Categories_MR']->assignment = $item[$type.'_assignto_mrcats'];
			$params['Categories_MR']->selection = $item[$type.'_assignto_mrcats_selection'];
			$params['Categories_MR']->params = null;
			$params['Categories_MR']->params->inc_children = $item[$type.'_assignto_mrcats_inc_children'];
			$incs = explode( ',', $item[$type.'_assignto_mrcats_inc'] );
			$params['Categories_MR']->params->inc_categories = in_array( 'inc_cats', $incs );
			$params['Categories_MR']->params->inc_items = in_array( 'inc_items', $incs );
		}

		$pass = $this->assignments->passAll( $params, $item[$type.'_match_method'] );

		return $pass;
	}
}