Location: PHPKode > scripts > Flexible Template Engine > flexible-template-engine/templateEngine.class.php
<?php
// +----------------------------------------------------------------------+
// | Template Engine Class 1.0                                            |
// +----------------------------------------------------------------------+
// | Copyright (c) Nick Tompson & Futurion Power Interactive              |
// +----------------------------------------------------------------------+
// |												  |
// | 		This source file is released as open source softwate.		  |
// | 		You may redistribute and modify software at your own will, 	  |
// |		providing the copyright, and this license is left in place.	  |
// |												  |
// +----------------------------------------------------------------------+
// | Authors: Nick Tompson <hide@address.com>                   |
// |          http://futurionpower.com                                    |
// +----------------------------------------------------------------------+
define( "TEMPL_ENGINE_IN",	1 );

/* $Id: templateEngine.class.php 00012 2008-30-06 18:43:09 +0800 Tompsonn $ Exp */

/**
 * Core path of files.
 *
 * Main path for this class and config file.
 */
#define( "TEMPL_CORE_PATH",	dirname( __FILE__ ) . "/" );

class templateEngine
{

	var 	$loadedSets		= array();	// All loaded templates in memory are accessible here.
	var	$config		= array();	// Configuration accessible from here.
	
	var 	$output		= "";
	var 	$wrapper		= "";
	var 	$setPath		= "";

	/**
	 * Constructor
	 *
	 * Setup and load class to run.
	 *
	 * @return	void
	 */
	function templateEngine()
	{
		// No constuctor required.
	}

	/**
	 * Init template engine.
	 *
	 * Sets up the configuration and pre-cache stuff.
	 *
	 * @return	void
	 */
	function initTemplateEngine( $theme="" )
	{
		if( !defined( "TEMPL_INIT_DONE" ) )
		{
			$this->_importConfiguration();	// Attempt to load the config.

			// Add in the theme that we're using.
			if( $theme AND file_exists( $this->config['templ_path'] . $theme ) )
			{
				#$theme	= preg_replace( "/\/$/", "", $theme );
				$this->setPath	= $this->config['templ_path'] . $theme . "/";
			}
			else
			{
 				$this->setPath	= $this->config['templ_path'] . $this->config['default_set'] . "/";
			}

			define( "TEMPL_INIT_DONE", 1 );
		}
	}


	/**
	 * Load a template group
	 *
	 * Grabs a template group and loads its object into memory.
	 *
	 * @param	string	$set
	 * @return	object
	 */
	function loadTemplateSet( $set )
	{	
		// Attempt to load this template set into memory.
		// Does it exist?
		
		if( file_exists( $this->setPath . $set . ".php" ) )
		{
			require $this->setPath . $set . ".php";

			if( class_exists( $set ) )
			{
				$class = new $set();
				$this->loadedSets[ $set ] =& $class;
			}

			return $class;
		}

		return FALSE;
	}

	/**
	 * Get template
	 *
 	 * Wrapper function for getting a specific template from a set.
	 *
	 * @param	string	$set
	 * @param	string	$name		Template to get.
	 * @param	[array]	$args		Optional arguments to send to function.
	 * @return	string
	 */
	function getTemplate( $set, $name, $args=array() )
	{
		// First up, check to see if we actually have this set onboard.
		if( isset( $this->loadedSets[ $set ] ) AND is_object( $this->loadedSets[ $set ] ) )
		{
			if( method_exists( &$this->loadedSets[ $set ], $name ) )
			{
				$argString 	= "";
				$returnHtml	= "";

				if( count( $args ) )
				{
					$argString = $this->_argumentsToString( $args );
				}

				$evalString	= $this->_getEvalString( $set, $name, $argString );

				eval( $evalString );
				$returnHtml	= $_parsedEvalReturn;
			}

			// Do we have any HTML to return from this function?
			if( $returnHtml != "" )
			{
				return $returnHtml;
				}
		}
	}

	/**
	 * Add output method
	 *
	 * Adds html output string to the current output variable.
	 *
	 * @param	string	$ouput
	 * @param	boolean	$append
	 * @return	void
	 */
	function addOutput( $output="", $append=TRUE )
	{
		// Add output to our main variable. We can overwrite the
		// output currently stored by setting $append to FALSE
		if( $output )
		{
			$this->output = ( $append == TRUE ) ? $this->output . $output : $output;
		}
	}

	/**
	 * Main page print function
	 *
	 * Prints the page after all output has finished loading.
	 *
	 * @param	array		$vars
	 * @param	[array]	$extraVars
	 * @param	[string]	$output
	 * @return	void
	 */
	function pagePrint( $vars=array(), $extraVars=array(), $output="" )
	{
		// INIT 
		//
		$_title	= "";
		$_header	= "";
		$_footer	= "";
		$output	= $output 	? 	$output	: $this->output;

		// Get the wrapper.
		$this->wrapper = $this->_getThemeWrapper();

		if( isset( $vars['page_title'] ) )
		{
			$_title	= $vars['page_title'];
		}

		// Attempt to get the header and footer. OK if it doesnt exist, you just won't get no 
		// custom header or footer.

		//

		if( file_exists( $this->setPath . "header.php" ) )
		{
			require_once( $this->setPath . "header.php" );
			$_header =& $HEADER;
		}

		if( file_exists( $this->setPath . "footer.php" ) )
		{
			require_once( $this->setPath . "footer.php" );
			$_footer =& $FOOTER;
		}

		$wrapVars = array( "PAGE_TITLE" => $_title,
						"CONTENT"	=> $output,
								"FOOTER"	=> $_footer, "HEADER"	=> $_header );


		// Now actually run the parse of our wrapper.
		$this->wrapper	= $this->_parseThemeWrapper( $this->wrapper, $wrapVars );

		if( count( $extraVars ) )
		{
			$this->wrapper = $this->_parseCustomMacros( $this->wrapper, $extraVars );
			}

		//
		// PRINT
		// Executes the headers, prints the wrapper, and gzips.
		//

				$this->_printHttpHeaders();
			print $this->wrapper;
			$this->_gzipOutput();

		exit();
	}

	//
	// INTERNAL CLASS METHODS
	//

	/**
	 * templateEngine::__importConfiguration
	 *
	 * Internal function, gets the app config.
	 *
	 * @access	private
	 * @return	void
	 */
	private function _importConfiguration()
	{
		if( !defined( "TEMPL_CONFIG_DONE" ) )
		{
			// Attempt to find the configuration file.
			if( file_exists( TEMPL_CORE_PATH . "config.php" ) )
			{
				require_once	TEMPL_CORE_PATH . "config.php";
				$this->config	=& $CONFIG;


				define( "TEMPL_CONFIG_DONE", 1 );
			}

			if( count( $this->config ) AND defined( "TEMPL_COFNIG_DONE" ) AND TEMPL_CONFIG_DONE == 1 )
			{

				// Try and fix up the templ path.
				if( !preg_match( "/\/$/", 	$this->config['templ_path'] ) )
				{
					$this->config['templ_path'] .= "/";
				}
			}
		}
	}

	/**
	 * templateEngine::_getThemeWrapper
	 *
	 * Gets the wrapper for this theme.
	 *
	 * @return	string
	 */
	private function _getThemeWrapper()
	{
		// Require and run the wrapper.
		require_once ( $this->setPath . "wrapper.php" );
		return $WRAPPER;
	}

	/**
	 * templateEngine::_parseThemeWrapper
	 *
	 * Parse the wrapper for this theme.
	 *
	 * @param	string	$wrapper
	 * @param	array		$vars
	 * @return	string
	 */
	private function _parseThemeWrapper( $wrapper, $vars )
	{
		$wrapper	= $this->_parseCustomMacros( $wrapper, $vars );
		return $wrapper;
	}

	/**
	 * templateEngine::_parseCustomMacros
	 *
	 * Parse the macros in output for this theme.
	 *
	 * @param	string	$wrapper
	 * @param	array		$vars
	 * @return	string
	 */
	private function _parseCustomMacros( $wrapper, $vars )
	{
		// Oh wow, this is a nice clean-o method for parsing the wrapper, isnt it?
		foreach( $vars as $k => $v )
		{
			$wrapper	= str_replace( '{%' .$k. '%}',	$v,	$wrapper );
		}

		return $wrapper;
	}
	
	/**
	 * templateEngine::_printHttpHeaders
	 *
	 * Shove in teh guv so the browser knows what we're hooking with.
	 *
	 * @return	void
	 */
	private function _printHttpHeaders()
	{
		@header("HTTP/1.0 200 OK");
			@header("HTTP/1.1 200 OK");
		@header("Content-type: text/html");
	}


	/**
	 * templateEngine::_gzipOutput
	 *
	 * Gzip's page content by running the output buffer.
	 *
	 * @return	void
	 */
	private function _gzipOutput()
	{
		// Test if GZIP compression is supported by the client, 	
		// and it's actually configured to be enabled.

		if( substr_count( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' ) )
		{
			if ( $this->config['use_gzip'] ) 
			{
				$buff		= "";
				if( count(ob_list_handlers()) ) 
				{
					ob_end_clean();
					$buff = ob_get_contents();

				}
        			@ob_start('ob_gzhandler');
				print $buff;
			}
		}
	}

	/**
	 * templateEngine::_argumentsToString
	 *
	 * Converts an array to a PHP code argument string.
	 *
	 * @param	array
	 * @return	string
	 */
	private function _argumentsToString( $argArray )
	{
		$parsedArgs		= array();

		foreach( $argArray as $k => $v )
		{
			$parsedArgs[] = '"' .$v. '"';
			}

		// Did we get any args to add in?
		if( count( $parsedArgs ) )
		{
			return implode( ",",	$parsedArgs );
		}
	}

	/**
	 * templateEngine::_getEvalString
	 *
	 * Gets the PHP code string for a template get call.
	 *
	 * @param	string	$set
	 * @param	string	$func
	 * @param	string	$argString
	 * @return	string
	 */
	private function _getEvalString( $set, $func, $argString )
	{
		// Clean up the strings before we start.
		$set	= $this->_cleanEvalString( $set  );
		$func	= $this->_cleanEvalString( $func );

		return "\$_parsedEvalReturn = \$this->loadedSets[ '{$set}' ]->{$func}( {$argString} );";
	}

	/**
	 * templateEngine::_cleanEvalString
	 *
	 * Filters out unwanted characters from func name etc.
	 *
	 * @param	string
	 * @return	string
	 */
	private function _cleanEvalString( $str )
	{
		$str 	= str_replace( "$", 	"", 	$str );
		$str	= str_replace( "{", 	"", 	$str );
		$str 	= str_replace( "}", 	"", 	$str );

		$str 	= str_replace( "(", 	"", 	$str );
		$str 	= str_replace( ")", 	"", 	$str );
		$str	= str_replace( ".",	"",	$str );

		return $str;
	}
} // END class.
?>
Return current item: Flexible Template Engine