<?php

/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP Version 4                                                        |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license,      |
// | that is bundled with this package in the file LICENSE, and is        |
// | available at through the world-wide-web at                           |
// | http://www.php.net/license/2_02.txt.                                 |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | license@php.net so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors: Victor Henrique <victor@season.com.br>                      |
// +----------------------------------------------------------------------+
//
// $Id$ 1.0.0

/**
 * Basic Template
 *
 * @package BasicTemplate
 * @author  Victor Henrique <victor@season.com.br>
 */
class BasicTemplate
{

    /**
     * stores the directory where template files are located.
     *
     * @var array
     */
    var $DIR = "./";

	/**
     * stores the directory where template files are located.
     *
     * @var string filename
     */
    var $FILE;


    /**
     * stores the template rendered
     *
     * @var string
     */
    var $OUTPUT;

    /**
     * an array containing the strings to be replaced in the main block
     *
     * @var array
     */
    var $PARSE = array();

    /**
     * an array containing the strings to be replaced in the dynamic blocks
     *
     * @var array
     */
    var $DYN_PARSE = array();

    /**
     * an array containing the dynamic blocks and its files
     *
     * @var array
     */
    var $DYN_BLOCKS = array();

    /**
     * an array containing dynamic blocks rendered
     *
     * @var array
     */
    var $DYN_OUTPUT = array();

    /**
     * an array containing all the non-fatal error messages during the render process
     *
     * @var array
     */
    var $ERROR = array();

    /**
     * an array containing all files which can be included
     *
     * @var array
     */
    var $INCLUDES = array();

    /**
     * Defines the directory where the template files are stored
     *
     * @access public
     * @param  string  The directory where template files are stored
     */
    function BasicTemplate($dir = './')
    {
    	if(!is_dir($dir))
        	$this->setError("The specified directory '$dir' is invalid",TRUE);
        else
        	$this->DIR = $dir;
    }

    /**
     * Defines the main template file
     *
     * @access public
     * @param  string  File of the main template block
     */
    function setMain($filename = '')
    {
    	$_filename = $this->DIR . "/" . $filename;
		if($filename == '')
        	setError("No file defined for the main block");
        elseif(!file_exists($_filename))
        	$this->setError("The file $filename defined for the main block is not a file or doesn't exists",TRUE);
        else
        	$this->FILE = $_filename;
    }

    /**
     * Defines a dynamic block
     *
     * @access public
     * @param  string  Name of dynamic block
     * @param  string  Template file for the dynamic block
     */
    function setDynamic($name = '', $filename = '')
    {
    	$_filename = $this->DIR . "/" . $filename;
        if(!file_exists($_filename))
        	$this->setError("File '$filename' defined for dynamic block '$name' doesn't exists");
        else {
        	$this->DYN_BLOCKS[$name] = $_filename;
        }
    }

    /**
     * Assign a template var to be replaced during rendering
     *
     * @access public
     * @param  string  Name of the template var
     * @param  string  Value to replace the template var
     * @param  string  Name of the dynamic block
     */
    function assign($name = '', $value = '', $dynamic = '')
    {
		if(is_array($name)) {
			foreach($name as $key => $int_value) {
				$name = $key;
				$value = $int_value;
			}
		}
        if($dynamic == '')
        	$this->PARSE[$name] = $value;
        else {
        	if(!is_null($this->DYN_BLOCKS[$dynamic])) {
            	$this->DYN_PARSE[$dynamic][$name] = $value;
            } else
            	$this->setError("The dynamic block $dynamic doesn't exists");
        }
    }

    /**
     * Parses the main block
     *
     * @access public
     * @param  string  dynamic block to be parsed
     */
    function parse($dynamic = '')
    {
    	if(!$dynamic) {
	    	$_filename = $this->FILE;
	    	if(!is_null($this->FILE)) {
	        	$fd = fopen($_filename,"r");
	            $read = fread($fd,filesize($_filename));
	            fclose($fd);
                if(count($this->PARSE) > 0) {
		            foreach($this->PARSE as $key => $value)
		            	$read = str_replace("{" . $key . "}",$value,$read);
                }

                $this->OUTPUT = $read;
	        }
	    } else {
        	if(!is_null($this->DYN_BLOCKS[$dynamic])) {
	        	$_filename = $this->DYN_BLOCKS[$dynamic];
				$fd = fopen($_filename,"r");
	          	$read = fread($fd,filesize($_filename));
	            fclose($fd);
	            if(count($this->DYN_PARSE[$dynamic]) > 0) {
                	foreach($this->DYN_PARSE[$dynamic] as $key => $value)
		            	$read = str_replace("{" . $key . "}",$value,$read);

                }
	            $this->DYN_OUTPUT[$dynamic] .= $read;
	        } else {
            	$this->setError("Dynamic block '$dynamic' doesn't exists");
            }
	    }
	}


    function setInclude($name = '', $filename = '')
    {
    	if(!file_exists($filename))
        	$this->setError("The file '$filename' cannot be included");
        else
        	$this->INCLUDES[$name] = $filename;
    }

    /**
     * Outputs the template file with the vars replaced
     *
     * @access public
     */
    function output()
    {
        foreach($this->DYN_BLOCKS as $key => $value) {
			$this->OUTPUT = str_replace("{dynamic name=$key}",$this->DYN_OUTPUT[$key],$this->OUTPUT);
        }
        ob_start();
        //his->_getConditionals();

    	if(count($this->ERROR) > 0) {
        	$errormsg = "The following errors were found during rendering process: <br>";
        	foreach($this->ERROR as $key => $value)
            	$errormsg .= "&nbsp;- " . $this->ERROR[$key] . " <br>";
            echo $errormsg;
        }
		echo $this->OUTPUT;
        ob_end_flush();
    }

    /**
     * Stores the current error in the error array and stops the rendering if necessary
     *
     * @access private
     * @param  string  Error message
     * @param  boolean Stop rendering
     */
    function setError($errmsg = '', $die = FALSE)
    {
    	$this->ERROR[] = $errmsg;
    	if($die){
        	$errormsg = "The following errors were found during rendering process:<br>";
            foreach($this->ERROR as $key => $value)
            	$errormsg .= "&nbsp;- " . $this->ERROR[$key] . "<br>";
            $errormsg .= "The rendering process was stopped.";
            echo $errormsg;
            exit;
	    }
    }

}

?>