<?php

if(!defined("IN_MYBB"))
	die("This file cannot be accessed directly.");

if(!defined('IN_ADMINCP'))
{
	// gain control of $templates object
	eval('
		class phptpl_templates extends '.get_class($GLOBALS['templates']).'
		{
			function phptpl_templates(&$oldtpl)
			{
				$vars = get_object_vars($oldtpl);
				foreach($vars as $var => $val)
					$this->$var = $val;
				
				$this->def_htmlcomments = $GLOBALS[\'mybb\']->settings[\'tplhtmlcomments\'];
				$this->def_htmlcomments = (($this->def_htmlcomments == \'yes\' || $this->def_htmlcomments == 1) ? 1:0);
			}
			function get($title, $eslashes=1, $htmlcomments=1)
			{
				if(isset($this->parsed_cache[$title]) && $eslashes && $this->def_htmlcomments == $htmlcomments)
					return $this->parsed_cache[$title];
				
				$this->parsed_cache[$title] = parent::get($title, $eslashes, $htmlcomments);
				// parse the template
				phptpl_parsetpl($this->parsed_cache[$title]);
				
				return $this->parsed_cache[$title];
			}
		}
	');
	$GLOBALS['templates'] = new phptpl_templates($GLOBALS['templates']);
}

function phptpl_info()
{
	return array(
		'name'			=> 'PHP and Template Conditionals',
		'description'	=> 'Allows you to use conditionals and PHP code in templates.',
		'website'		=> 'http://mybbhacks.zingaburga.com/',
		'author'		=> 'ZiNgA BuRgA',
		'authorsite'	=> 'http://zingaburga.com/',
		'version'		=> '1.1',
		'compatibility'	=> '1*',
		'guid'			=> ''
	);
}

function phptpl_parsetpl(&$ourtpl)
{
	$ourtpl = preg_replace(array(
		'#\<\?.*?(\?\>)#se', // '#\<\?.*?(\?\>|$)#se',
		'#\<if (.*?) then\>#sie',
		'#\<elseif (.*?) then\>#sie',
		'#\<else( /)?\>#i',
		'#\</if\>#i',
		'#\<func (htmlspecialchars|htmlspecialchars_uni|intval|floatval|urlencode|rawurlencode|addslashes|stripslashes|trim|crc32|ltrim|rtrim|md5|nl2br|strrev|strtoupper|strtolower)\>#i',
		'#\</func\>#i'
	), array(
		'phptpl_evalphp(\'$0\', \'$1\')',
		'\'".phptpl_iif(\'.phptpl_unescape_string(\'$1\').\',"\'',
		'\'",\'.phptpl_unescape_string(\'$1\').\',"\'',
		'","',
		'")."',
		'".$1("',
		'")."'
	), $ourtpl);
}


// unescapes the slashes added by $templates->get(), plus addslashes() during preg_replace()
function phptpl_unescape_string($str)
{
	return strtr($str, array('\\\\"' => '"', '\\\\' => '\\'));
}

function phptpl_evalphp($str, $end)
{
	return '".eval(\'ob_start(); ?>'
		.strtr(phptpl_unescape_string($str), array('\'' => '\\\\', '\\' => '\\\\'))
		.($end?'':'?>').'<?php return ob_get_clean();\')."';
}

function phptpl_iif($condition, $true)
{
	$args = func_get_args();
	for($i=1, $c=count($args); $i<$c; $i+=2)
		if($args[$i-1]) return $args[$i];
	return (isset($args[$i-1]) ? $args[$i-1] : '');
}
?>