<?php 
/*
 *
 * @package		ARI Smart Content
 * @author		ARI Soft
 * @copyright	Copyright (c) 2011 www.ari-soft.com. All rights reserved
 * @license		GNU/GPL (http://www.gnu.org/copyleft/gpl.html)
 * 
 */

(defined('_JEXEC') && defined('ARI_FRAMEWORK_LOADED')) or die;

AriKernel::import('Application.ARISmartContent.Plugin.CollectionPlugin');

class plgArismartcontentFileloader extends AriSmartContentPluginContent
{
	function __construct(&$subject, $config)
	{
		parent::__construct($subject, $config); 

		$this->loadLanguage('', JPATH_ADMINISTRATOR);
	}

	function getTag()
	{
		return 'file';
	}

	function contentPluginHandler($params, $content, $sourceContent) 
	{
		$path = AriUtils::getParam($params, 'path');

		$error = '';

		if (empty($path))
			$error = JText::_('PLG_ARISMARTCONTENTFILELOADER_ERROR_PATHEMPTY');
		else
		{
			$path = AriUtils::resolvePath($path);

			if (!file_exists($path) || !is_file($path))
				$error = JText::sprintf('PLG_ARISMARTCONTENTFILELOADER_ERROR_PATHINCORRECT', $path);
		}

		if ($error)
			return sprintf('<div style="color:red">%1$s</div>', $error);
			
		$useVars = (bool)AriUtils::getParam($params, 'useVars', 1);

		$fileContent = file_get_contents($path);
		
		$inputEncoding = AriUtils::getParam($params, 'encoding');
		if (!empty($inputEncoding))
			$fileContent = @iconv($inputEncoding, 'UTF-8', $fileContent);

		if ($useVars && strpos($fileContent, '{$') !== false)
		{
			AriKernel::import('SimpleTemplate.SimpleTemplate');

			$vars = $this->getVars($content);
			$fileContent = AriSimpleTemplate::parse($fileContent, $vars, true);
		}

		return $fileContent;
	}
	
	function getVars($content)
	{
		$collectionPlugin = new AriSmartContentPluginContentCollection('var');
		$declVars = $collectionPlugin->getItems($content);

		$vars = array();
		if (!is_array($declVars))
			return $vars;

		foreach ($declVars as $var)
		{
			$name = AriUtils::getParam($var['params'], 'name', '');

			$vars[$name] = $var['content'];
		}

		return $vars;
	}
}