<?php
/**
*    Class template
*
*    	@author Nok http://www.jpw.com.ar - nok@jpw.com.ar
*	@modified by Marco Islas <markuz@islascruz.org>
*
*    @copyright Juan Pablo Winiarczyk
*
*    @version 1.1.6-markuz
*	
*	Template engine class. Includes external cache in file
*    
*	Important!!
*		This is a modified version of NokTemplate. 
*
* 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.
*/

class template {
    var $_version = '1.1.6-markuz';

    var $_path = '';

    var $_filesArray = array();

    var $_variablesArray = array();

    var $useCache = 0;

    var $_cache = '';

    var $_debug = False;

    var $_dynamicVariable = False;

    var $_tagsArray = array('begins' => '{', 'ends' => '}');

    var $_tagsArrayBlock = array('begins' => '<!-- BEGINS:', 'ends' => '<!-- ENDS:', 'close' => '-->');

    var $_tagsVarDinamicaArray = array('begins' => '<!-- beginsDynamicVar:', 'ends' => '<!-- endsDynamicVar:', 'close' => '-->');

    function template($directory='.') {
        $this->_path = $this->checkPath($directory);
    }

    function load($label, $fileName) {
        if(!empty($label) AND !empty($fileName) AND $this->_useCache != 2) {
            $this->_filesArray[$label] = $this->getFile($fileName);
        }
    }

    function VirtualLoad($label, $content) {
        if(!empty($label) AND !empty($content) AND $this->useCache != 2) {
            $this->_filesArray[$label] = $content;
        }
    }

    function set_variable($variable, $value='') {
        if(!empty($variable)) {
            $this->_variablesArray[$variable] = $value;
        }
        else {
            $this->error('Null identifier. You must specify one');
        }
    }

    function expand($variable, $label, $analyze = True) {
        if (!empty($variable) AND !empty($label)) {
            if($label{0} == '-'){
                $this->_variablesArray[$variable]='';
            }
            else {
                if($this->useCache != 2){
                    $newValue = '';
                    $concatenate = False;

                    if($label{0} == '+' OR $label{0} == '.'){
                        $label = substr($label, 1);
                        $concatenate = True;
                    }

                    if($analyze) {
                        if (!$this->_debug) {
                           $newValue = preg_replace('/{([a-zA-Z0-9_]+)}/e', "\$this->_variablesArray['\\1']", $this->_filesArray[$label]);
                        }
                        else {
                           $newValue = preg_replace('/{([a-zA-Z0-9_]+)}/e', "\$this->debugger(\\1)", $this->_filesArray[$label]);
                        }
                         // <-- Interpolación de variables
                    }
                    else {
                        $newValue = $this->_filesArray[$label];
                    }

                       if ($concatenate) {
                           $this->_variablesArray[$variable] .= $newValue;
                    }
                    else {
                        $this->_variablesArray[$variable] = $newValue;
                    }
                }
            }
        }
        else {
            $this->error("Not a valid identifier.");
        }
    }

    function print_export($variable) {
        print $this->export($variable);
    }

    function export($variable) {
        if (!empty($variable)) {
            $idFile = 0;
            switch ($this->useCache) {
                case 0:
                    return $this->_variablesArray[$variable];
                break;
                case 1: // No existe el archivo cache. Debo guardarlo.
                    $idFile = fopen($this->_cache, 'w');
                    fwrite($idFile, $this->_variablesArray[$variable]);
                    fclose($idFile);

                    return $this->_variablesArray[$variable];
                break;
                default: // Existe el archivo cache. Primero busco variables dinamicas y despues lo muestro.
                    $template = implode('', file($this->_cache));

                    if ($this->_dynamicVariable) {
                        $template = preg_replace('/' .
			 $this->_tagsVarDinamicaArray['begins'] .
			 ' ([a-zA-Z0-9_]+) ' .
			 $this->_tagsVarDinamicaArray['close'] .
			 '.*' .
			 $this->_tagsVarDinamicaArray['ends'] .
			 ' (\\1) ' .
			 $this->_tagsVarDinamicaArray['close'] .
			 '/es', "\$this->_variablesArray['\\1']", $template);
                    }
                    return $template;
                break;
            }
        }
        else {
            $this->error("Not a valid identifier.");
        }
    }

    function setCache($idCache, $cacheExpires = 0){
        if (!empty($idCache)) {
            $this->_cache = $this->_path . $idCache . '.cache';
            $this->useCache = 1;

            if (($cacheExpires == 0 OR (time() - @filemtime($this->_cache)) < $cacheExpires) AND file_exists($this->_cache)) {
                    $this->useCache = 2;
            }
        }
        else {
            $this->error('Cache null identifier. You must specify one.');
        }
    }

    function clearCache($idCache){
        @unlink ($this->_path . $idCache);
    }

    function set_dynamicVariable($variable, $value='') {
        if(!empty($variable) AND $this->useCache > 0) {
            $this->_dynamicVariable = True;
            $this->_variablesArray[$variable] = $this->_tagsVarDinamicaArray['begins'] ." ". $variable ." ". $this->_tagsVarDinamicaArray['close'] . $value . $this->_tagsVarDinamicaArray['ends'] ." ". $variable ." ". $this->_tagsVarDinamicaArray['close'];
        }
        else {
            $this->error('You must activate cache to use this function.');
        }
    }

    function setBlock($block, $template) {
        if ($this->useCache != 2) {
            $stringBlock = array();
            if(!empty($block) && !empty($template)) {
                if(preg_match('/' . $this->_tagsArrayBlock['begins'] . '[ ]*' . $block . '[ ]*' . $this->_tagsArrayBlock['close'] .
                              '(.*)' .$this->_tagsArrayBlock['ends'] . '[ ]*' . $block . '[ ]*' . $this->_tagsArrayBlock['close'] . '/s', $this->_filesArray[$template], $stringBlock)){
                        $this->_filesArray[$block] = preg_replace('/' . $this->_tagsArrayBlock['begins'] . ' (.*) ' . $this->_tagsArrayBlock['close'] . '(.*)' . $this->_tagsArrayBlock['ends'] . ' \\1 ' . $this->_tagsArrayBlock['close'] . '/s', '', $stringBlock[1]);
                }
                else
                    $this->error("Block \"$block\" does not exists in $template.");
            }
        }
    }

    function debug($bool = True){
        $this->_debug = $bool;
    }

    function version(){
        return $this->_version;
    }

    function error($message = '') {
        if (!empty($message)) {
            exit('(Template) <font color=\"red\"><b>Error: </b></font>' . $message);
        }
    }

    function checkPath($directory){
        if ($directory{strlen($directory)-1} == '/') {
            $directory = substr($directory, 0, strlen($directory)-1);
        }

        if (@is_dir($directory)) {
            return ($directory . '/');
        }
        else {
            $this->error("Dir  \"$directory\" does not exists.");
        }
    }

    function getFile($fileName){
        $realPath = $this->_path . $fileName;
        if($fileName{0} == '*') {
            $realPath = substr($fileName, 1);
        }

        if (file_exists($realPath)) {
            	return implode('', file($realPath));
        }
        else {
            $this->error("Not a valid template: \"$fileName \".");
        }
    }

    function debugger($variable) {
        if (!isset($this->_variablesArray[$variable])) {
            $this->error("<b>Debug:</b> Variable \"$variable\" defined in Template, not no está initialized.");
        }
        else {
            return $this->_variablesArray[$variable];
        }
    }
    
    function setDirectory($dir = './') 
    {
		$this->_path = $this->checkPath($dir);
	}

    function clean($variable)
    {
    		$this->_variablesArray[$variable]= "";
    }
}
?>
