#native_company# #native_desc#
#native_cta#

iTemplate

By Igor Mladenovic
on March 27, 2002

Version: 1.02

Type: Class

Category: HTTP

License: GNU General Public License

Description: iTemplate is PHP class for dynamic creating web pages. You can simple and very fast crate parts of template whose have to be in loop, replace values from template, and include another template file…

<?

	/********************************************/
	//  iTemplate 1.0 Class for PHP 4            /
	//                                           /
	//         Author : Igor Mladenovic          /
    //                  [email protected]         /
    //                                           /
    //    version 1.02   Februar 26. 2002        /
	/********************************************/

	/**********************************************************************
	This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
	*************************************************************************/



	//define(TEMPLATE_SUBBLOCK,0); // blok je sub blok, a ne poseban fajl
	//define(TEMPLATE_FILE,1);     // iscitaj blok iz posebnog fajla

	// flags for defineBlock() function
	define("BLOCK_HEADEREXISTS", 1);
	define("BLOCK_HEADEREXIST", 1);
	define("BLOCK_FOOTEREXISTS", 2);
	define("BLOCK_FOOTEREXIST", 2);
	define("BLOCK_DUMMYEXISTS", 4); // postoje dummy podaci posle bloka (trebaju da se obrisu, sluze samo za dizajnere)
	define("BLOCK_DUMMYEXIST", 4);
	

	// flags for addValue() function
	define("ASSIGN_RECURSIVE",1);		// zamenjuj promenljive rekurzivno u svim childovima

	define("_MAIN_BLOCK_NAME_",'_MAIN_BLOCK_NAME_');		// main block name (for internal)

	define("ITEMPLATE_DISPLAY_ERRORS",true);

	// error messages
	define("FILE_NOTEXISTS","File %s doesn't exists");
	define("WRONG_TEMPLATE_BLOCK","Wrong template block : %s");

	// global functions and variables;
	$tplStatistic = array('replacements' => 0, 'blocks' => 0, 'assigments' => 0, 'block replacements'=>0, 'input size'=>0, 'output size'=>0);

	function tplError($type, $param1 = '', $param2 ='')
	{
		$txtMessage = $$type;
		if ($txtMessage == '') $txtMessage = $type;
		if (ITEMPLATE_DISPLAY_ERRORS) printf("Template ERROR : <i><font color=red>" . $txtMessage . "</font></i> !!<br>",$param1,$param2);
		$ErrorMessage = sprintf($txtMessage ,$param1,$param2);
		return $ErrorMessage;
	}
	
	function setStatistic($type,$value,$max = false)
	{
		global $tplStatistic;
		if ($max && $tplStatistic[$type]>$value )
		{
			$tplStatistic[$type] = $value;
		}
		else
		{
			$tplStatistic[$type] += $value;
		}
	}

	function printStatistic()
	{
		global $tplStatistic;
		while (list($key,$value) = each($tplStatistic))
		{
			echo "$key = $value<br>n";
		}
	}


/******************************************/	
//            class iBlock                //
/******************************************/	
	class iBlock
	{
		var $name;
		var $message;
		var $parent;
		var $output = "";
		var $text;
		var $type;
		var $vars = array();
		var $vars_rec = array();
		var $childs = array();
		var $isIncluded = false;
		var $LastError;
		

		function iBlock($name)
		{
			$this->name = $name;
		}

		function init()
		{
			$this->getBlockFromParent();
		}

		// create new blok child
		function block($name, $type = 0)
		{
			$this->childs[$name] = new iBlock($name);
			$this->childs[$name]->type = $type; 
			$this->childs[$name]->parent = &$this;
			$this->childs[$name]->init();

			setStatistic('blocks',1);

			return $this->childs[$name];
		}

		// dodeljuje vrednost nekoj variabli u bloku
		function assign($key, &$value, $assignType = -1 )
		{
			if (is_object($value) && strtolower(get_class($value))=="itemplate") 
			{
				$blockKey = "TEMPLATE_" . $key;
				$postfix = 1;
				while (isset($this->childs[$blockKey . "_" . (string)$postfix])) $postfix++;
	//			while (array_key_exists($blockKey . "_" . (string)$postfix, $this->childs)) 
				$blockKey .= "_" . (string)$postfix;

				$this->text = preg_replace("/{$key}/ims","{" . $blockKey . "}{" . $key. "}",$this->text);
				
				$newBlock = &$this->block($blockKey);
				
				$this->childs[$blockKey] = &$value;
				$this->childs[$blockKey]->parent = $newBlock->parent;
				$this->childs[$blockKey]->name = $newBlock->name;
				$this->childs[$blockKey]->type = $newBlock->type;
				$this->childs[$blockKey]->isIncluded = true; 

				// add variable for replacing original block name
				$this->vars[$key] = new iAssignment($key,"");
				//$this->childs[$key]->add();
				return;
			}

			if (is_array($key) || is_object($key)) 
			{
				$this->assignHash($key,$value,$assignType);
			}
			else
			{
				if ($assignType == ASSIGN_RECURSIVE)
					if (!(is_array($value) && ($this->vars_rec[$key]->value == $value)))
					{
						$this->vars_rec[$key] = new iAssignment($key,$value,$assignType);
						setStatistic('assigments',1);
					} else;  // don't remove this else
				else
					if (!(is_array($value) && ($this->vars[$key]->value == $value)))
					{
						$this->vars[$key] = new iAssignment($key,$value,$assignType);
						setStatistic('assigments',1);
					}

			}
		}

		function assignHash($hash, $prefix = '', $assignType = -1)
		{
			while(list($key,$value) = each($hash))
			{
				if (!is_object($value) && !is_array($value) && is_string($key))
				{
					if ($prefix != '') $key = $prefix . '_' . $key;
					$this->assign($key,$value,$assignType);
				}
			}
		}

		function add()
		{
			
			$text = $this->text;

			/***********************************************************************/
			// replace all NON recursive variables
			reset($this->vars);
			while (list($key) = each($this->vars))
			{
				$text = preg_replace("/{$key}/ism",$this->vars[$key]->getNextValue(),$text);
				setStatistic('replacements',1);
				if(!is_array($this->vars[$key]->value)) unset($this->vars[$key]);
			}
			/***********************************************************************/

			/***********************************************************************/
			// replace all childs 
			if (count($this->childs)>0) $text = $this->parseChilds($text);
			/***********************************************************************/

			/***********************************************************************/
			// replace all recursive variables
			reset($this->vars_rec);
			while (list($key) = each($this->vars_rec))
			{
				$text = preg_replace("/{$key}/ism",$this->vars_rec[$key]->getNextValue(),$text);
				setStatistic('replacements',1);
				if(isset($this->vars[$key]) && !is_array($this->vars[$key]->value)) unset($this->vars[$key]);
			}
			/***********************************************************************/
			
			$this->output .= $text;
			setStatistic('output size',strlen($this->output),true);
		}

		function parseChilds($text)
		{
			reset($this->childs);
			while (list($name, $child) = each($this->childs))
			{
				if ($child->output == '' && ($child->type & (BLOCK_HEADEREXISTS | BLOCK_FOOTEREXISTS)) != 0)
				{
					$startString = "{DYNAMIC_BLOCK_$name}";
					$endString = "{DYNAMIC_BLOCK_$name}";
					
					if (($child->type & BLOCK_HEADEREXISTS) == BLOCK_HEADEREXISTS)
						$startString = "<!-- block header : $name -->";
					if (($child->type & BLOCK_FOOTEREXISTS) == BLOCK_FOOTEREXISTS)
						$endString = "<!-- block footer : $name -->";
					
					$text = preg_replace("/$startString(.*?)$endString/ism",'',$text);
					setStatistic('block replacements',1);
				}
				else
				{
					if ($child->isIncluded)
					{
						$text = preg_replace("/{$name}/ism",$child->output,$text);
					}
					else
					{
						$text = preg_replace("/{DYNAMIC_BLOCK_$name}/ism",$child->output,$text);
					}
					setStatistic('block replacements',1);
				}
				$this->childs[$name]->output = '';
			}
			return $text;
		}

		// read block from file
		function getBlockFromFile($name, $fileName)	
		{
			if (file_exists($fileName))
			{
				$this->text = join('',file($fileName));
				setStatistic('input size',strlen($this->text));
			}
			else
			{
				$this->LastError = tplError(FILE_NOTEXISTS,$fileName);
			}
		}

		function getBlockFromParent()
		{
			$name = $this->name;
			preg_match("/<!-- start block : $name -->(.*?)<!-- end block : $name -->/ims",$this->parent->text ,$split);
			$this->parent->text = preg_replace("/<!-- start block : $name -->(.*?)<!-- end block : $name -->/ims","{DYNAMIC_BLOCK_$name}",$this->parent->text);
			if (($this->type & BLOCK_DUMMYEXISTS) == BLOCK_DUMMYEXISTS)
			{
				$this->parent->text = preg_replace("/{DYNAMIC_BLOCK_$name}.*<!-- dummy block : $name -->/ims","{DYNAMIC_BLOCK_$name}",$this->parent->text);
				$this->parent->text = preg_replace("/<!-- dummy block : $name -->.*{DYNAMIC_BLOCK_$name}/ims","{DYNAMIC_BLOCK_$name}",$this->parent->text);
			}
			if (isset($split[1]))
				$this->text = $split[1];
			else
				$this->text = ""; 
		}


		function change($content)
		{
			$this->text = $content;
		}
	}


	
	
	
/******************************************/	
// class iTemplate                        // main class for users
/******************************************/	
	class iTemplate extends iBlock
	{

		function iTemplate($fileName)
		{
			$this->fileName = $fileName;
			$this->getBlockFromFile(_MAIN_BLOCK_NAME_,$fileName);
		}

		function defineBlock($parent,$blockName,$blockParams = 0)
		{
			$parentText = $this->createBlockCode($parent);
			$codeText = $parentText . '->block' . "($blockName,$blockParams);";
			
			eval($codeText);
		}

		function addTemplate($blockName, $key, &$value, $type = 0)
		{
			$parentText = $this->createBlockCode($blockName);
			$codeText = $parentText . '->assign' . "($key, $value, $type);";
			eval($codeText);

		}

		function addValue($blockName, $key, $value = "", $type = 0)
		{
			$parentText = $this->createBlockCode($blockName);
			$codeText = $parentText . '->assign' . "($key, $value, $type);";
			eval($codeText);

		}

		function parse($blockName = '')
		{
			$parentText = $this->createBlockCode($blockName);
			$codeText = $parentText . '->add();';
			eval($codeText);
		}


		function changeBlockContent($blockName,$content)
		{
			$parentText = $this->createBlockCode($blockName);
			$codeText = $parentText . '->change' . "($content);";
			eval($codeText);

		}


		function createBlockCode($blockName)
		{
			$blocks = split(':',$blockName);

			$out = '$this';
			
			while (list($no,$bn) = each($blocks))
			{
				if ($bn != '' && (strtolower($bn) != 'main' || $no!=0)) $out .= '->childs['' . $bn . '']';
			}

			eval
			("
				if (!is_object($out)) 
				{
					$this->LastError=tplError(WRONG_TEMPLATE_BLOCK,$blockName);
					exit;
				}
			");
			return $out;
		}

		function tprint($blockName = '')
		{
			$parentText = $this->createBlockCode($blockName);
			$codeText = 'echo ' . $parentText . '->output;';
			eval($codeText);
		}

		function get($blockName = '')
		{
			$parentText = $this->createBlockCode($blockName);
			$codeText = 'return ' . $parentText . '->output;';
			return eval($codeText);
		}
	}


/******************************************/	
//            class iAssignment           //
/******************************************/	
	class iAssignment
	{
		var $key;
		var $value;
		var $type;
		var $pos;

		function iAssignment($key,$value,$type = -1)
		{
			$this->key = $key;
			$this->value = $value;
			$this->type = $type;
			$this->pos = 0;
		}

		function getNextValue()
		{
			if (!is_array($this->value)) return $this->value;

			if (($this->pos) >= count($this->value)) $this->pos = 0;
			$return = $this->value[$this->pos];
			$this->pos ++;
			return $return;
		}
	}




?>