<?php
/**
 * TemplateManager Class.
 * @author: Ryan Demmer
 * @version: templatemanager.php 2009-04-11
 */
 
require_once( JCE_LIBRARIES .DS. 'classes' .DS. 'manager.php' );
 
class Templatemanager extends Manager{
	var $_ext = 'html=html,htm;text=txt';
	/**
	* @access	protected
	*/
	function __construct(){			
		parent::__construct();			
			
		// Set the file type map from parameters
		$this->setFileTypes( $this->getPluginParam('templatemanager_extensions', $this->_ext ) );
		// Init plugin
		$this->init();
	}
	/**
	 * Returns a reference to a plugin object
	 *
	 * This method must be invoked as:
	 * 		<pre>  $manager =& TemplateManager::getInstance();</pre>
	 *
	 * @access	public
	 * @return	The plugin object.
	 * @since	1.5
	 */
	function &getInstance(){
		static $instance;
	
		if ( !is_object( $instance ) ){
			$instance = new Templatemanager();
		}
		return $instance;
	}
	function init(){
		// check the user/group has editor permissions
		$this->checkPlugin() or die( JError::raiseError( 403, JText::_( 'Access Forbidden' ) ) );
		
		parent::init();
		
		$params = $this->getPluginParams();
		
		if( $params->get('templatemanager_allow_save', '1') ){
			$this->addAction( 'save', '', 'this.saveTemplate', JText::_('Create Template') );
			$this->setXHR( array( $this, 'saveTemplate' ) );
		}
		$this->setXHR( array( $this, 'loadTemplate' ) );
		
		// Set javascript file array
		$this->script( array( 'templatemanager' ), 'plugins' );
		$this->css( array( 'templatemanager' ), 'plugins' );
		
		// Load extensions if any
		$this->loadExtensions();
		// Process requests
		$this->processXHR();
	}
	function getFileDetails( $file ){
		clearstatcache();
		
		$path 	= Utils::makePath( $this->getBaseDir(), rawurldecode( $file ) );
		$url 	= Utils::makePath( $this->getBaseUrl(), rawurldecode( $file ) );
		
		$date 	= Utils::formatDate( @filemtime( $path ) );
		$size 	= Utils::formatSize( @filesize( $path ) );
		
		$h = array(
			'size'		=>	$size, 
			'modified'	=>	$date,
		);
		
		return $h;
	}
	function saveTemplate(){	
		
		$dir 	= JRequest::getVar( 'dir', '' );
		$data 	= JRequest::getVar( 'data', '', 'POST', 'STRING', JREQUEST_ALLOWRAW );
		$name 	= JRequest::getVar( 'name', '' );
		$type 	= JRequest::getVar( 'type', '' );

		jimport('joomla.filesystem.file');		
		$path = Utils::makePath( $this->getBaseDir(), rawurldecode( $dir ) );
		$name = JFile::makeSafe( $name ) . '.html';		
		$path = Utils::makePath( $path, $name );
		
		// Remove any existing template div
		$data = preg_replace( '/<div(.*?)class="mceTmpl"([^>]*?)>([\s\S]*?)<\/div>/i', '$3', $data );
		
		if( $type == 'template' ){
			$data = '<div class="mceTmpl">' . $data . '</div>';
		}
		
		if( JFile::exists( $path ) ){
			$this->_result['error'] = JText::_('File Exists');
		}else{
			$content  =  "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
			$content .=  "<head>\n";
			$content .=  "<title>" . $name . "</title>\n";
			$content .=  "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n";
			$content .=  "</head>\n";
			$content .=  "<body>\n";
			$content .=  $data;
			$content .= "\n</body>\n";
			$content .= "</html>";

			if( !@JFile::write( $path, stripslashes( $content ) ) ){
			  $this->_result['error'] = JText::_('Write Error');
			}
		}
		return $this->returnResult();
	}
	function replaceVars( $matches ){
		switch( $matches[1] ){
			case 'modified':
				return strftime( $this->getPluginParam('templatemanager_mdate_format', '%Y-%m-%d %H:%M:%S' ) );
				break;
			case 'created':
				return strftime( $this->getPluginParam('templatemanager_cdate_format', '%Y-%m-%d %H:%M:%S' ) );
				break;
			case 'username':
			case 'usertype':
			case 'name':
			case 'email':
				$user =& JFactory::getUser();
				return isset( $user->$matches[1] ) ? $user->$matches[1] : $matches[1];
				break;
			default:
				// Replace other pre-defined variables
				$params = $this->getPluginParam('templatemanager_replace_values');
				if( $params ){
					foreach( explode( ',', $params ) as $param ){
						$k = preg_split( '/[:=]/', $param );
						if( trim( $k[0] ) == $matches[1] ){
							return trim( $k[1] );
						}
					}
				}	
				break;
		}
	}
	function loadTemplate( $file ){
		jimport('joomla.filesystem.file');
		
		$file 		= Utils::makePath( $this->getBaseDir(), rawurldecode( $file ) );
		$content 	= JFile::read( $file );	
		
		// Remove body etc.
		if( preg_match( '/<body[^>]*>([\s\S]+?)<\/body>/', $content, $matches ) ){
			$content = trim( $matches[1] );
		}
		// Replace variables
		$content = preg_replace_callback( '/\{\$(.+?)\}/i', array( $this, 'replaceVars' ), $content );	
		return $content;
	}
	function getViewable(){
		return $this->getFileTypes( 'list' );
	}
}
?>