<?php
/**
 * Plugin Helper File
 *
 * @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' );

/**
** Plugin that places the button
*/
class plgButtonContentTemplaterHelper
{
	function plgButtonContentTemplaterHelper( &$params )
	{
		// Load plugin parameters
		$this->params = $params;
	}

	/**
	* Display the button
	*
	* @return array A two element array of ( imageName, textToInsert )
	*/
	function render( $name )
	{
		JHTML::_( 'behavior.modal' );

		$mainframe =& JFactory::getApplication();
		$user =& JFactory::getUser();

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

		$button = new JObject();
		$button->set( 'text', '' );

		$button_style = 'contenttemplater';
		if ( !$this->params->button_icon ) {
			$button_style = 'blank blank_contenttemplater';
		}
		$button->set( 'name', $button_style );

		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();
		$script = 'var CT_root = "'.JURI::root().'";';
		$document->addScriptDeclaration( $script );
		$document->addScript( JURI::root(true).'/plugins/system/nonumberelements/js/script.js' );
		$document->addScript( JURI::root(true).'/plugins/editors-xtd/contenttemplater/js/script.js' );
		$document->addStyleSheet( JURI::root(true).'/plugins/editors-xtd/contenttemplater/css/style.css' );

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

		$options = array();
		$extra_buttons = 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 ( $pass ) {
				if ( $item->button_enabled == 2 )  {
					// template should be displayed as a button
					$style = '';
					$style = str_replace( '.png', '', $item->button_image );
					if( $style == -1 ) { $style = '';  }
					$styles[] = $style;
					$onclick = 'CT_f.getXML( \''.$item->id.'\', \''.$name.'\' );';
					if ( $this->params->show_confirm ) {
						$onclick = 'if( confirm(\''.sprintf(  JText::_( 'Are you sure?', true ), '\n').'\') ) { '.$onclick.' };';
					}
					if ( !strlen( $item->button_name ) ) {
						$item->button_name = $item->name;
					}
					$extra_buttons[] =
						'"></a></div></div>'."\n"
						.'<div class="button2-left"><div class="blank '.$style.'">'
						.'<a title="'.$item->button_name.'" onclick="'.$onclick.'">'.$item->button_name.'</a><a style="display:none;';
				} else {
					// template should be displayed in select list
					$option = '<option value="'.$item->id.'">';
					$option .= ( $item->name );
					$option .= '</option>';
					$options[] = $option;
				}
			}
		}

		$show_list = 1;
		if ( !count( $options ) ) {
			if ( $mainframe->isAdmin() && $this->params->show_empty ) {
				array_unshift( $options, '<option value="" selected="selected">- '.JText::_( 'No templates available' ).' -</option>' );
			} else {
				$button->set( 'name', '" style="display: none;' );
				$show_list = 0;
			}
		} else {
			array_unshift( $options, '<option value="" selected="selected">- '.JText::_( 'Templates' ).' -</option>' );
		}

		$selectlist = '';
		if ( $show_list ) {
			if ( $mainframe->isAdmin() ) {
				$options[] = '<option value="-1">- '.JText::_( 'Create new template' ).' -</option>';
			}

			$jsaction_insert = 'CT_f.getXML( this.value, \''.$name.'\' );';
			if ( $this->params->show_confirm ) {
				$jsaction_insert = 'if( confirm(\''.sprintf(  JText::_( 'Are you sure?', true ), '\n').'\') ) { '.$jsaction_insert.' };';
			}
			$jsaction_new =
				'if( confirm(\''.JText::_( 'Open in new window?' ).'\') ) {'
					.'window.open(\'index.php?option=com_contenttemplater&controller=item&task=edit\');'
				.'} else {'
					.'if( confirm(\''.JText::_( 'Are you sure new?' ).'\') ) {'
						.'window.location.href=\'index.php?option=com_contenttemplater&controller=item&task=edit\';'
					.'};'
				.'};';
			$jsaction = 'if( this.value == -1) {'.$jsaction_new.'} else {'.$jsaction_insert.'}';

			$selectlist = '<select class="contenttemplater" onchange="'.$jsaction.'this.options[0].selected=true;return false;">';
			$selectlist .= implode( $options ).'</select>';
		}

		$options_html = '">'.$selectlist.'</a><script type="text/javascript">var CT_editor = "'.$name.'";</script><a style="display:none;';
		$options_html .= implode( '', $extra_buttons );
		$button->set( 'options', $options_html );

		if ( count( $styles ) ) {
			$excl_styles = array( '', '-1', 'blank' );
			$styles = array_map( 'trim', $styles );
			$styles = array_unique( $styles );
			$styles = array_diff( $styles, $excl_styles );
			if ( count( $styles ) ) {
				// clean styles
				$css = array();
				foreach ( $styles as $style ) {
					$css[] = 
						'.button2-left .'.$style.' a {
							background: transparent url('.JURI::root(true).'/plugins/editors-xtd/contenttemplater/images/buttons/'.$style.'.png) 100% 3px no-repeat;
							padding-right: 19px !important;
							margin-right: 3px;
						}';
				}
				$document->addStyleDeclaration( implode( '', $css ) );
			}
		}

		return $button;
	}

	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 = explode( '\n', $item[$type.'_assignto_urls_selection_sef'] );
			} else {
				$params['URL']->selection = explode( '\n', $item[$type.'_assignto_urls_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;
	}
}