<?php

class render {
    
    var $tpl_cache = array();
    
	function globalsets($tpl) {
		global $cat, $url_arr,$uauth, $shop, $geoip;

		
		/* includes */
        if ( preg_match_all('/{include:(.*?)}/', $tpl, $arr ) ) {
            global $cat;
 			$path = _BASE_DIR . 'tpls/';

            foreach( $arr[1] as $filename ) {
                if ( !$this->tpl_cache[$path . $filename][''] ) {
             		$subtpl = @file_get_contents($path . $filename);
                    $this->tpl_cache[$path . $filename][''] = $subtpl;
                } else {
                    $subtpl = $this->tpl_cache[$path . $filename][''];
                }
         		$subtpl = @file_get_contents($path . $filename);
                $tpl = $this->set('include:'.$filename, $subtpl, $tpl );
            }
        }

		/* global sets */
		$tpl = $this->set('cur_cat', $cat->cat, $tpl);
		$tpl = $this->set('cur_year', date('Y'), $tpl);
		$tpl = $this->set('cur_date', date('d.m.Y'), $tpl);
		$tpl = $this->set('cur_cat_name', $cat->cat_name, $tpl);
		$tpl = $this->set('getRand', rand(), $tpl);
		$tpl = $this->set('_SITE_TITLE_', _SITE_TITLE_, $tpl);
		$tpl = $this->set('_SITE_ROOT_', _SITE_ROOT_, $tpl);
		$tpl = $this->set('_STATIC_ROOT_', _STATIC_ROOT_, $tpl);

		if ($url_arr) {
		    $tpl = $this->set('cur_url', implode('/', $url_arr), $tpl);
        }
		/* */
		return $tpl;
	}

	function getTpl($filename, $section ='', $path = '') {
		if (!$path ) $path = _BASE_DIR . '/tpls/';
        if ( !$tpl_cache[$path . $filename][$section] ) {
     		$tpl = file_get_contents($path . $filename);
     		if ( $section ) {
     				preg_match ("/\#\[".$section."\]\#(.*?)\#\[!".$section."\]\#/s", $tpl, $r);
     			$tpl = $r[1];
     		}
            $tpl_cache[$path . $filename][$section] = $tpl;
        } else {
            $tpl = $tpl_cache[$path . $filename][$section];
        }
 		$tpl = $this->globalsets($tpl);
 	return $tpl;
	}

	function set($x, $y, $tpl) {
        global $statistica;
        $starttime = microtime(true);
 		$tpl = str_replace('{' . $x . '}', $y, $tpl);
        
        $statistica['render_time'] += microtime(true) - $starttime;
        
        
 		return $tpl;
	}

	function parse($x, $y, $tpl) {
        global $statistica;
        $starttime = microtime(true);
 		$tpl = str_replace('{' . $x . '}', $y . '{' . $x . '}', $tpl);
        $statistica['render_time'] += microtime(true) - $starttime;

 		return $tpl;
	}

	
	function clear($tpl) {
        global $statistica;
        $starttime = microtime(true);
		$tpl = preg_replace ("/\{[^\s]{1,}?\}/", '', $tpl);
        $statistica['render_time'] += microtime(true) - $starttime;
 		return $tpl;
	}
    
    function getVars($tpl) {
		preg_match_all ("/{(.*?)}/", $tpl, $r);
        return $r[1];
    }


}

?>