<?php
/**
 * @version $Id$
 * @package    Contact_Enhanced
 * @subpackage Controllers
 * @author     Douglas Machado {@link http://ideal.fok.com.br}
 * @author     Created on 04-Dec-09
 * @license		GNU/GPL, see license.txt
 * Contact Enhanced  is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses. */

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

jimport('joomla.application.component.controller');

class Contact_EnhancedsControllerTemplates extends JController
{
	var $cid;

	function __construct()
	{
		parent::__construct();
		// Register Extra tasks
		$this->registerTask( 'add'  	, 	'edit' );
		$this->registerTask( 'unpublish', 	'publish');
		$this->registerTask( 'apply'	, 	'save');
		
		// Set default view
		JRequest::setVar( 'view', 'templates' );
		JRequest::setVar( 'layout', 'default'  );
		$this->cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger($this->cid, array(0));
	}
	
	function edit()
	{
		JRequest::setVar( 'view', 'template' );
		JRequest::setVar( 'layout', 'edit'  );
		JRequest::setVar('hidemainmenu', 1);
		parent::display();
	}
	
	function view()
	{
		JRequest::setVar( 'view', 'templates' );
		JRequest::setVar( 'layout', 'default'  );
		JRequest::setVar('hidemainmenu', 0);
		parent::display();
	}
	
	function save()
	{
		global $mainframe;

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize some variables

		$template	= JRequest::getVar('id', '', 'method', 'cmd');
		$option		= JRequest::getVar('option', '', '', 'cmd');
		$templateType= JRequest::getVar('templateType', 'email');
		$params		= JRequest::getVar('params', array(), 'post', 'array');
		$filecontent= JRequest::getVar('filecontent', '', 'post', 'string', JREQUEST_ALLOWRAW);
		
		$tBaseDir 	= JPATH_ROOT.DS.'components'.DS.COMPONENT_FOLDER.DS.'templates'.DS.$templateType;
		if (!$template) {
			$mainframe->redirect('index.php?option='.$option.'&controller=templates', JText::_('Operation Failed').': '.JText::_('No template specified.'));
		}elseif (!$filecontent) {
			$mainframe->redirect('index.php?option='.$option.'&controller=templates', JText::_('Operation Failed').': '.JText::_('Template content empty.'));
		}

		// Set FTP credentials, if given
		jimport('joomla.client.helper');
		JClientHelper::setCredentialsFromRequest('ftp');
		$ftp = JClientHelper::getCredentials('ftp');

		$file = $tBaseDir.DS.$template.DS.'params.ini';

		jimport('joomla.filesystem.file');
		if (JFile::exists($file) && count($params))
		{
			$registry = new JRegistry();
			$registry->loadArray($params);
			$txt = $registry->toString();
			
			if(!is_writable($file)){
				// Try to make the params file writeable
				if (!$ftp['enabled'] && JPath::isOwner($file) && !JPath::setPermissions($file, '0755')) {
					JError::raiseNotice('SOME_ERROR_CODE', JText::_('Could not make the template parameter file writable'));
				}
			}
			
			$return = JFile::write($file, $txt);

			if (!$return) {
				$mainframe->redirect('index.php?option='.$option.'&controller=templates&templateType='.$templateType, JText::_('Operation Failed').': '.JText::sprintf('Failed to open param.ini file for writing.', $file));
			}
		}
		
		$file = $tBaseDir.DS.$template.DS.'index.html';
		if(!is_writable($file)){
			// Try to make the template file writeable
			if (!$ftp['enabled'] && !JPath::setPermissions($file, '0755')) {
				JError::raiseNotice('SOME_ERROR_CODE', JText::_('Could not make the template file writable'));
			}
		}

		$return = JFile::write($file, $filecontent);

		if ($return)
		{
			$task = JRequest::getCmd('task');
			switch($task)
			{
				case 'apply':
					$mainframe->redirect('index.php?option='.$option.'&controller=templates&templateType='.$templateType.'&task=edit&cid='.$template, JText::_('Template source saved'));
					break;

				case 'save':
				default:
					$mainframe->redirect('index.php?option='.$option.'&controller=templates&templateType='.$templateType, JText::_('Template source saved'));
					break;
			}
		}
		else {
			$mainframe->redirect('index.php?option='.$option.'&controller=templates&templateType='.$templateType, JText::_('Operation Failed').': '.JText::sprintf('Failed to open file for writing.', $file));
		}

	}

	function cancel()
	{
		global $mainframe;

		// Initialize some variables
		$option	= JRequest::getCmd('option');
		$mainframe->redirect('index.php?option='.$option.'&controller=templates', JText::_('Operation cancelled'));
	}

}
