<?php
/* PageCookery Framework
*
* Author: Explon
*
* Copyright (C) 2007 Explon <explon@gmail.com>
*/

class Template
{
	private $html = '';
	private $css = '';
	private $rss = '';
	private $current = '';
	
	public function __construct($file = '', $css = '', $current = '')
	{
		if ($css)
		{
			if (defined('STATIC_SERVER_ROOT'))
			{
				$css_root = STATIC_SERVER_ROOT;
			}
			else if (DEBUG != true)
			{
				$domain = parse_url(BASE_URL);
			
				$css_root = $domain['host'];
			}
			
			if (is_array($css))
			{
				foreach ($css AS $stylesheet)
				{
					if (DEBUG == true OR !defined('STATIC_SERVER_ROOT'))
					{
						$this->css .= link_tag('css/' . $stylesheet . '.css');
					}
					else
					{
						$f_string .= 'css%2F' . $css_root . '%2F' . $stylesheet . '.css,';
					}
				}
				
				if (DEBUG != true AND defined('STATIC_SERVER_ROOT'))
				{
					$this->css = link_tag(STATIC_SERVER . '?f=' . substr($f_string, 0, strlen($f_string) - 1));
				}
			}
			else
			{
				if (DEBUG == true OR !defined('STATIC_SERVER_ROOT'))
				{
					$this->css = link_tag(BASE_URL . 'css/' . $css . '.css');
				}
				else
				{
					$this->css = link_tag(STATIC_SERVER . '?f=css%2F' . $css_root . '%2F' . $css . '.css');
				}
			}
		}
		
		if ($current)
		{
			$this->current = $current;
		}
		
		$this->Load($file);
	}
	
	public function ImportRSS($rss = array())
	{
		foreach ($rss AS $title => $link)
		{
			$this->rss .= link_tag($link, 'alternate', 'application/rss+xml', $title);
		}
	}
	
	private function Load($template)
	{
		global $template_files;
		
		if (file_exists('template/' . $template . '.html'))
		{
			$file_content = file_get_contents('template/' . $template . '.html');
			
			if (DEBUG == true AND !strstr($this->GetHtml(), '<meta'))
			{
				$file_content = "\n<!-- " . $template . ".html Begin -->\n" . $file_content;
			}

			if (DEBUG == true)
			{
				$file_content .= "\n<!-- " . $template . ".html End -->\n";
			}

			$template_files .= "\n" . $template . '.html';
		}
		else if (strstr($template, '<'))
		{
			$file_content = $template;
		}
		else
		{
			exit('Template file: ' . $template . '.html not exists.');
		}
	
		$this->SetHTML($file_content);
	}

	public function Get($template)
	{
		global $template_files;
		
		$template_files = $template_files . "\n" . $template . '.html';
		
		$file_content = @file_get_contents('template/' . $template . '.html');
		
		if ($file_content === false)
		{
			exit('Template file: ' . $template . '.html not exists.');
		}
		
		if (DEBUG == true AND $this->GetHTML())
		{
			$file_content = "\n<!-- " . $template . ".html Begin -->\n" . $file_content;
		}
		
		if (DEBUG == true)
		{
			$file_content .= "\n<!-- " . $template . ".html End -->\n";
		}
		
		$template_files .= "\n" . $template . '.html';
		
		return $file_content;
	}
	
	public function GetHTML()
	{
		return $this->html;
	}
	
	public function SetHTML($data)
	{
		$this->html = $data;
	}
	
	public function Parse($return = false)
	{
		$cache_dir = COOKERY_FRAMEWORK_DIR . 'cache/template/';
		
        $template = '<?php $current = \'' . $this->current . '\'; ?>' . $this->GetHTML();
		
		if ($return == false)
		{
			$template .= '<?php output_debug(); exit;';
		}
		
		$template = preg_replace("/\{template (.+?)\}/e", "load_template('\\1')", $template);
		
		$cache_id = strtoupper(md5($template)) . '.php';
		
		$cache_location = $cache_dir . $cache_id;
		
		if (!file_exists($cache_location))
		{
	        $template = str_replace('{$css}', $this->css, $template);
			$template = str_replace('{$rss}', $this->rss, $template);
	        $template = str_replace('{$base_url}', BASE_URL, $template);

			$template = preg_replace("/<\?xml\s+(.+?)\?\>/s", "<?php echo '<?xml \\1?>'; ?>\n", $template);
			
			$template = str_replace('<php>', '<?php ', $template);
			$template = str_replace('<echo>', '<?php echo ', $template);
			$template = str_replace(array('</php>', '</echo>'), ' ?>', $template);

			$template = preg_replace("/<!--\{(if|while|foreach|for)\s+(.+?)\}-->/s", "<?php \\1 \\2 { ?>", $template);
			$template = preg_replace("/<!--\{else if\s+(.+?)\}-->/s", '<?php } else if \\1 { ?>', $template);
			$template = str_replace('<!--{else}-->', '<?php } else { ?>', $template);
			
			$template = str_replace(array('<!--{/if}-->', '<!--{/while}-->', '<!--{/foreach}-->', '<!--{/for}-->'), "<?php } ?>", $template);

			/*$template = preg_replace("/\{(\\\$[a-zA-Z0-9_\[\]\'\"\$\.\x7f-\xff]+)\}/s", '<?php echo \\1; ?>', $template);*/

			$template = preg_replace("/\{\\\$(.+?)\}/s", '<?php echo $\\1; ?>', $template);
			
			$template = preg_replace("/<t>(.+?)<\/t>/s", "<?php echo _t('\\1'); ?>", $template);
			
			$template = str_ireplace(array('href="#"' , "href='#'"), 'href="javascript:void(0)"', $template);

			if (DEBUG != true)
			{
				$template = preg_replace("~>\s+\r~", '>', preg_replace("~>\s+\n~", '>', $template));
				$template = preg_replace("~>\n+\t~", '>', $template);
				$template = preg_replace("~>\t+~", '>', $template);
			}
			
			if (!file_put_contents($cache_location, $template))
			{
				exit('Template cache directory: ' . $cache_dir . ' is not writeable.');
			}
		}
		
		unset($template);
		
		return $cache_location;
	}
	
	public function DrawTitle($navbar = array())
	{
		$title = SITE_NAME;
		
		if (sizeof($navbar) > 0)
		{
			foreach ($navbar AS $link => $text)
			{
				$title = $text . ' - ' . $title;
			}
		}
		
		return $title;
	}
}