<?php 
class dd_Tpl{
	public $com_dir = 'DdTpl/comdir';		//编译文件的存放目录
	public $left_limit = '{{';			//左定界符
	public $right_limit = '}}';		//右定界符
	public $tpl_vars = array();		//变量数组
	
	function assign($assign){
		if(is_array($assign)){
			$this->tpl_vars = $assign;
			unset($assign);
		}
	}
	function tpl_path($com){
	$com = $com.'/'.WAPID;
	if(!is_dir($com)){mkdir($com);}
		if($com != ''){
			$this->com_dir = $com;
		}
	
	}
	function display($name){
		$content = preg_replace("/(<\?|<\?php|\?>|<%|%>)/",' ',htmlzm(ddtpl($name),'decode'));
		$comFile = $this->com_dir.'/com_'.WAPID.'_'.$name.'_tpl.php';
		if(!is_file($comFile)||time()-filemtime($comFile)>60*5)
		{
			/*调用内部方法替换模板*/
			$repContent = $this->tpl_replace($content);
			file_put_contents($comFile,$repContent);
		}
			/*包含处理后的文件*/
			ob_start();
			include($comFile);
			$out = ob_get_contents();
			ob_end_clean();
			echo UBB($out);
	}
	
	function tpl_replace($content){
		$left = preg_quote($this->left_limit,'/');
		$right = preg_quote($this->right_limit,'/');
		$pattstr = array(
		'/'.$left.'\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*'.$right.'/i',
		'/'.$left.'\s*if\s*(.+?)\s*'.$right.'(.+?)'.$left.'\s*\/if\s*'.$right.'/ies',
	    '/'.$left.'\s*else\s*if\s*(.+?)\s*'.$right.'/ies',
		'/'.$left.'\s*else\s*'.$right.'/is',
		'/'.$left.'\s*loop\s+\$(\S+)\s+\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*'.$right.'(.+?)'.$left.'\s*\/loop\s*'.$right.'/is',
		'/'.$left.'\s*loop\s+\$(\S+)\s+\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*=>\s*\$(\S+)\s*'.$right.'(.+?)'.$left.'\s*\/loop\s*'.$right.'/is',
		'/'.$left.'\s*include\s+[\"\']?(.+?)[\"\']?\s*'.$right.'/ie'
		);
		$repl = array(
		'<?php  echo $this->tpl_vars["${1}"] ;?>',
		'$this->stripvtags(\'<?php  if(${1}){?>\',\'${2}<?php  } ?>\')',
		'$this->stripvtags(\'<?php  }elseif(${1})?>\',"")',
		'<?php  }else{ ?>',
		'<?php  foreach($this->tpl_vars["${1}"] as $this->tpl_vars["${2}"]) {?>${3}<?php  } }?>',
		'<?php  foreach($this->tpl_vars["${1}"] as $this->tpl_vars["${2}"] = > $this->tpl_vars["${3}"]){?> ${4} <?php  } ?>',
		'file_get_contents($this->tpl_dir."/${1}")'
		);
		$repContent = preg_replace($pattstr,$repl,$content);
		if(preg_match('/'.$left.'([^('.$right.')]{1,})'.$right.'/',$repContent)){
			$repContent = $this->tpl_replace($repContent);
		}
		return $repContent;
	}
	function stripvtags($expr,$statement=''){
	/*匹配变量的正则*/
	$var_pattern = '/\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*/is';
	/*把变量替换为指*/
	$expr = preg_replace($var_pattern,'$this->tpl_vars["${1}"]',$expr);
	/*将开始标记中的引号转义去掉*/
	$expr = str_replace("\\\"","\"",$expr);
	/*替换语句体和技术标记中的引号*/
	$statement = str_replace("\\\"","\"",$statement);
	/*将处理后的条件语句相连后返回*/
	return $expr.$statement;
	}
}	